llama.cpp 657 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687
  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, &free, &total);
  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, &free, &total);
  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, &free, &total);
  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. // Remove split metadata
  11248. gguf_remove_key(ctx_out, ml.llm_kv(LLM_KV_SPLIT_NO).c_str());
  11249. gguf_remove_key(ctx_out, ml.llm_kv(LLM_KV_SPLIT_COUNT).c_str());
  11250. gguf_remove_key(ctx_out, ml.llm_kv(LLM_KV_SPLIT_TENSORS_COUNT).c_str());
  11251. if (params->kv_overrides) {
  11252. const std::vector<llama_model_kv_override> & overrides = *(const std::vector<llama_model_kv_override> *)params->kv_overrides;
  11253. for (auto & o : overrides) {
  11254. if (o.key[0] == 0) break;
  11255. if (o.tag == LLAMA_KV_OVERRIDE_TYPE_FLOAT) {
  11256. gguf_set_val_f32(ctx_out, o.key, o.float_value);
  11257. } else if (o.tag == LLAMA_KV_OVERRIDE_TYPE_INT) {
  11258. gguf_set_val_i32(ctx_out, o.key, o.int_value);
  11259. } else if (o.tag == LLAMA_KV_OVERRIDE_TYPE_BOOL) {
  11260. gguf_set_val_bool(ctx_out, o.key, o.bool_value);
  11261. } else {
  11262. LLAMA_LOG_WARN("%s: unknown KV override type for key %s\n", __func__, o.key);
  11263. }
  11264. }
  11265. }
  11266. for (int i = 0; i < ml.n_tensors; ++i) {
  11267. const struct ggml_tensor * meta = ml.get_tensor_meta(i);
  11268. const std::string name = ggml_get_name(meta);
  11269. // TODO: avoid hardcoded tensor names - use the TN_* constants
  11270. if (name.find("attn_v.weight") != std::string::npos ||
  11271. name.find("attn_qkv.weight") != std::string::npos) {
  11272. ++qs.n_attention_wv;
  11273. } else if (name == LLM_TN(model.arch)(LLM_TENSOR_OUTPUT, "weight")) {
  11274. qs.has_output = true;
  11275. }
  11276. }
  11277. qs.n_ffn_down = qs.n_ffn_gate = qs.n_ffn_up = (int)model.hparams.n_layer;
  11278. // sanity checks
  11279. //
  11280. // - qs.n_attention_wv == 0 for Mamba models
  11281. // - qs.n_attention_wv == model.hparams.n_layer for Transformer models
  11282. //
  11283. GGML_ASSERT((qs.n_attention_wv == 0 || qs.n_attention_wv == (int)model.hparams.n_layer) && "n_attention_wv is unexpected");
  11284. size_t total_size_org = 0;
  11285. size_t total_size_new = 0;
  11286. std::vector<std::thread> workers;
  11287. workers.reserve(nthread);
  11288. int idx = 0;
  11289. std::vector<no_init<uint8_t>> read_data;
  11290. std::vector<no_init<uint8_t>> work;
  11291. std::vector<no_init<float>> f32_conv_buf;
  11292. // populate the original tensors so we get an initial meta data
  11293. for (int i = 0; i < ml.n_tensors; ++i) {
  11294. const struct ggml_tensor * meta = ml.get_tensor_meta(i);
  11295. gguf_add_tensor(ctx_out, meta);
  11296. }
  11297. std::ofstream fout(fname_out, std::ios::binary);
  11298. fout.exceptions(std::ofstream::failbit); // fail fast on write errors
  11299. const size_t meta_size = gguf_get_meta_size(ctx_out);
  11300. LLAMA_LOG_INFO("%s: meta size = %zu bytes\n", __func__, meta_size);
  11301. // placeholder for the meta data
  11302. ::zeros(fout, meta_size);
  11303. const auto tn = LLM_TN(model.arch);
  11304. for (int i = 0; i < ml.n_tensors; ++i) {
  11305. struct ggml_tensor * tensor = ml.get_tensor_meta(i);
  11306. const std::string name = ggml_get_name(tensor);
  11307. if (!ml.use_mmap) {
  11308. if (read_data.size() < ggml_nbytes(tensor)) {
  11309. read_data.resize(ggml_nbytes(tensor));
  11310. }
  11311. tensor->data = read_data.data();
  11312. }
  11313. ml.load_data_for(tensor);
  11314. LLAMA_LOG_INFO("[%4d/%4d] %36s - [%s], type = %6s, ",
  11315. ++idx, ml.n_tensors,
  11316. ggml_get_name(tensor),
  11317. llama_format_tensor_shape(tensor).c_str(),
  11318. ggml_type_name(tensor->type));
  11319. // This used to be a regex, but <regex> has an extreme cost to compile times.
  11320. bool quantize = name.rfind("weight") == name.size() - 6; // ends with 'weight'?
  11321. // quantize only 2D and 3D tensors (experts)
  11322. quantize &= (ggml_n_dims(tensor) >= 2);
  11323. // do not quantize norm tensors
  11324. quantize &= name.find("_norm.weight") == std::string::npos;
  11325. quantize &= params->quantize_output_tensor || name != "output.weight";
  11326. quantize &= !params->only_copy;
  11327. // do not quantize expert gating tensors
  11328. // NOTE: can't use LLM_TN here because the layer number is not known
  11329. quantize &= name.find("ffn_gate_inp.weight") == std::string::npos;
  11330. // do not quantize positional embeddings and token types (BERT)
  11331. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_POS_EMBD, "weight");
  11332. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_TOKEN_TYPES, "weight");
  11333. // do not quantize Mamba's small yet 2D weights
  11334. // NOTE: can't use LLM_TN here because the layer number is not known
  11335. quantize &= name.find("ssm_conv1d.weight") == std::string::npos;
  11336. quantize &= name.find("ssm_x.weight") == std::string::npos;
  11337. quantize &= name.find("ssm_dt.weight") == std::string::npos;
  11338. enum ggml_type new_type;
  11339. void * new_data;
  11340. size_t new_size;
  11341. if (quantize) {
  11342. new_type = default_type;
  11343. // get more optimal quantization type based on the tensor shape, layer, etc.
  11344. if (!params->pure && ggml_is_quantized(default_type)) {
  11345. new_type = llama_tensor_get_type(qs, new_type, tensor, ftype);
  11346. }
  11347. if (params->token_embedding_type < GGML_TYPE_COUNT && strcmp(tensor->name, "token_embd.weight") == 0) {
  11348. new_type = params->token_embedding_type;
  11349. }
  11350. if (params->output_tensor_type < GGML_TYPE_COUNT && strcmp(tensor->name, "output.weight") == 0) {
  11351. new_type = params->output_tensor_type;
  11352. }
  11353. // If we've decided to quantize to the same type the tensor is already
  11354. // in then there's nothing to do.
  11355. quantize = tensor->type != new_type;
  11356. }
  11357. if (!quantize) {
  11358. new_type = tensor->type;
  11359. new_data = tensor->data;
  11360. new_size = ggml_nbytes(tensor);
  11361. LLAMA_LOG_INFO("size = %8.3f MB\n", ggml_nbytes(tensor)/1024.0/1024.0);
  11362. } else {
  11363. const int64_t nelements = ggml_nelements(tensor);
  11364. const float * imatrix = nullptr;
  11365. if (imatrix_data) {
  11366. auto it = imatrix_data->find(tensor->name);
  11367. if (it == imatrix_data->end()) {
  11368. LLAMA_LOG_INFO("\n====== %s: did not find weights for %s\n", __func__, tensor->name);
  11369. } else {
  11370. if (it->second.size() == (size_t)tensor->ne[0]*tensor->ne[2]) {
  11371. imatrix = it->second.data();
  11372. } else {
  11373. LLAMA_LOG_INFO("\n====== %s: imatrix size %d is different from tensor size %d for %s\n", __func__,
  11374. int(it->second.size()), int(tensor->ne[0]*tensor->ne[2]), tensor->name);
  11375. // this can happen when quantizing an old mixtral model with split tensors with a new incompatible imatrix
  11376. // this is a significant error and it may be good idea to abort the process if this happens,
  11377. // since many people will miss the error and not realize that most of the model is being quantized without an imatrix
  11378. // tok_embd should be ignored in this case, since it always causes this warning
  11379. if (name != tn(LLM_TENSOR_TOKEN_EMBD, "weight")) {
  11380. throw std::runtime_error(format("imatrix size %d is different from tensor size %d for %s",
  11381. int(it->second.size()), int(tensor->ne[0]*tensor->ne[2]), tensor->name));
  11382. }
  11383. }
  11384. }
  11385. }
  11386. if ((new_type == GGML_TYPE_IQ2_XXS ||
  11387. new_type == GGML_TYPE_IQ2_XS ||
  11388. new_type == GGML_TYPE_IQ2_S ||
  11389. new_type == GGML_TYPE_IQ1_S ||
  11390. (new_type == GGML_TYPE_IQ1_M && strcmp(tensor->name, "token_embd.weight") && strcmp(tensor->name, "output.weight")) ||
  11391. (new_type == GGML_TYPE_Q2_K && params->ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && strcmp(tensor->name, "token_embd.weight") != 0)) && !imatrix) {
  11392. LLAMA_LOG_ERROR("\n\n============================================================\n");
  11393. LLAMA_LOG_ERROR("Missing importance matrix for tensor %s in a very low-bit quantization\n", tensor->name);
  11394. LLAMA_LOG_ERROR("The result will be garbage, so bailing out\n");
  11395. LLAMA_LOG_ERROR("============================================================\n\n");
  11396. throw std::runtime_error(format("Missing importance matrix for tensor %s in a very low-bit quantization", tensor->name));
  11397. }
  11398. float * f32_data;
  11399. if (tensor->type == GGML_TYPE_F32) {
  11400. f32_data = (float *) tensor->data;
  11401. } else if (ggml_is_quantized(tensor->type) && !params->allow_requantize) {
  11402. throw std::runtime_error(format("requantizing from type %s is disabled", ggml_type_name(tensor->type)));
  11403. } else {
  11404. llama_tensor_dequantize_internal(tensor, f32_conv_buf, workers, nelements, nthread);
  11405. f32_data = (float *) f32_conv_buf.data();
  11406. }
  11407. LLAMA_LOG_INFO("converting to %s .. ", ggml_type_name(new_type));
  11408. fflush(stdout);
  11409. if (work.size() < (size_t)nelements * 4) {
  11410. work.resize(nelements * 4); // upper bound on size
  11411. }
  11412. new_data = work.data();
  11413. const int64_t n_per_row = tensor->ne[0];
  11414. const int64_t nrows = tensor->ne[1];
  11415. static const int64_t min_chunk_size = 32 * 512;
  11416. 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);
  11417. const int64_t nelements_matrix = tensor->ne[0] * tensor->ne[1];
  11418. const int64_t nchunk = (nelements_matrix + chunk_size - 1)/chunk_size;
  11419. const int64_t nthread_use = nthread > 1 ? std::max((int64_t)1, std::min((int64_t)nthread, nchunk)) : 1;
  11420. // quantize each expert separately since they have different importance matrices
  11421. new_size = 0;
  11422. for (int64_t i03 = 0; i03 < tensor->ne[2]; ++i03) {
  11423. const float * f32_data_03 = f32_data + i03 * nelements_matrix;
  11424. void * new_data_03 = (char *)new_data + ggml_row_size(new_type, n_per_row) * i03 * nrows;
  11425. const float * imatrix_03 = imatrix ? imatrix + i03 * n_per_row : nullptr;
  11426. 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);
  11427. }
  11428. LLAMA_LOG_INFO("size = %8.2f MiB -> %8.2f MiB\n", ggml_nbytes(tensor)/1024.0/1024.0, new_size/1024.0/1024.0);
  11429. }
  11430. total_size_org += ggml_nbytes(tensor);
  11431. total_size_new += new_size;
  11432. // update the gguf meta data as we go
  11433. gguf_set_tensor_type(ctx_out, name.c_str(), new_type);
  11434. gguf_set_tensor_data(ctx_out, name.c_str(), new_data, new_size);
  11435. // write tensor data + padding
  11436. fout.write((const char *) new_data, new_size);
  11437. zeros(fout, GGML_PAD(new_size, align) - new_size);
  11438. }
  11439. // go back to beginning of file and write the updated meta data
  11440. {
  11441. fout.seekp(0);
  11442. std::vector<uint8_t> data(gguf_get_meta_size(ctx_out));
  11443. gguf_get_meta_data(ctx_out, data.data());
  11444. fout.write((const char *) data.data(), data.size());
  11445. }
  11446. fout.close();
  11447. gguf_free(ctx_out);
  11448. LLAMA_LOG_INFO("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  11449. LLAMA_LOG_INFO("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  11450. if (qs.n_fallback > 0) {
  11451. LLAMA_LOG_WARN("%s: WARNING: %d of %d tensor(s) required fallback quantization\n",
  11452. __func__, qs.n_fallback, qs.n_k_quantized + qs.n_fallback);
  11453. }
  11454. }
  11455. static int llama_apply_lora_from_file_internal(
  11456. const struct llama_model & model, const char * path_lora, float scale, const char * path_base_model, int n_threads
  11457. ) {
  11458. LLAMA_LOG_INFO("%s: applying lora adapter from '%s' - please wait ...\n", __func__, path_lora);
  11459. const int64_t t_start_lora_us = ggml_time_us();
  11460. llama_file fin(path_lora, "rb");
  11461. // verify magic and version
  11462. {
  11463. uint32_t magic = fin.read_u32();
  11464. if (magic != LLAMA_FILE_MAGIC_GGLA) {
  11465. LLAMA_LOG_ERROR("%s: bad file magic\n", __func__);
  11466. return 1;
  11467. }
  11468. uint32_t format_version = fin.read_u32();
  11469. if (format_version != 1) {
  11470. LLAMA_LOG_ERROR("%s: unsupported file version\n", __func__ );
  11471. return 1;
  11472. }
  11473. }
  11474. int32_t lora_r = fin.read_u32();
  11475. int32_t lora_alpha = fin.read_u32();
  11476. float scaling = scale * (float)lora_alpha / (float)lora_r;
  11477. LLAMA_LOG_INFO("%s: r = %d, alpha = %d, scaling = %.2f\n", __func__, lora_r, lora_alpha, scaling);
  11478. // load base model
  11479. std::unique_ptr<llama_model_loader> ml;
  11480. if (path_base_model) {
  11481. LLAMA_LOG_INFO("%s: loading base model from '%s'\n", __func__, path_base_model);
  11482. ml.reset(new llama_model_loader(path_base_model, /*use_mmap*/ true, /*kv_overrides*/ nullptr));
  11483. ml->init_mappings(/*prefetch*/ false); // no prefetching
  11484. }
  11485. struct tensor_meta {
  11486. std::string name;
  11487. ggml_type type;
  11488. int32_t ne[2];
  11489. size_t offset;
  11490. };
  11491. std::map<std::string, tensor_meta> tensor_meta_map;
  11492. // load all tensor meta
  11493. while (true) {
  11494. if (fin.tell() == fin.size) {
  11495. // eof
  11496. break;
  11497. }
  11498. int32_t n_dims;
  11499. int32_t name_len;
  11500. int32_t ftype;
  11501. fin.read_raw(&n_dims, sizeof(n_dims));
  11502. fin.read_raw(&name_len, sizeof(name_len));
  11503. fin.read_raw(&ftype, sizeof(ftype));
  11504. if (n_dims != 1 && n_dims != 2) {
  11505. LLAMA_LOG_ERROR("%s: unsupported tensor dimension %d\n", __func__, n_dims);
  11506. return 1;
  11507. }
  11508. int32_t ne[2] = { 1, 1 };
  11509. for (int i = 0; i < n_dims; ++i) {
  11510. fin.read_raw(&ne[i], sizeof(ne[i]));
  11511. }
  11512. std::string name;
  11513. {
  11514. GGML_ASSERT(name_len < GGML_MAX_NAME);
  11515. char buf[GGML_MAX_NAME];
  11516. fin.read_raw(buf, name_len);
  11517. name = std::string(buf, name_len);
  11518. }
  11519. // check for lora suffix
  11520. std::string lora_suffix;
  11521. if (name.length() > 6) {
  11522. lora_suffix = name.substr(name.length() - 6);
  11523. }
  11524. if (lora_suffix != ".loraA" && lora_suffix != ".loraB") {
  11525. LLAMA_LOG_ERROR("%s: error: '%s' is not a lora tensor\n", __func__, name.c_str());
  11526. return 1;
  11527. }
  11528. // tensor type
  11529. ggml_type wtype;
  11530. switch (ftype) {
  11531. case 0: wtype = GGML_TYPE_F32; break;
  11532. case 1: wtype = GGML_TYPE_F16; break;
  11533. default:
  11534. {
  11535. LLAMA_LOG_ERROR("%s: invalid tensor data type '%d'\n",
  11536. __func__, ftype);
  11537. return 1;
  11538. }
  11539. }
  11540. // data offset
  11541. size_t offset = fin.tell();
  11542. offset = (offset + 31) & -32;
  11543. // skip tensor data
  11544. fin.seek(offset + ggml_row_size(wtype, ne[0]) * ne[1], SEEK_SET);
  11545. tensor_meta_map.emplace(name, tensor_meta{ name, wtype, { ne[0], ne[1] }, offset });
  11546. }
  11547. bool warned = false;
  11548. int n_tensors = 0;
  11549. // apply
  11550. ggml_backend_t backend_cpu = ggml_backend_cpu_init();
  11551. if (backend_cpu == nullptr) {
  11552. LLAMA_LOG_ERROR("%s: error: failed to initialize cpu backend\n", __func__);
  11553. return 1;
  11554. }
  11555. ggml_backend_cpu_set_n_threads(backend_cpu, n_threads);
  11556. std::vector<no_init<uint8_t>> read_buf;
  11557. for (const auto & it : model.tensors_by_name) {
  11558. const std::string & base_name = it.first;
  11559. ggml_tensor * model_t = it.second;
  11560. if (tensor_meta_map.find(base_name + ".loraA") == tensor_meta_map.end() ||
  11561. tensor_meta_map.find(base_name + ".loraB") == tensor_meta_map.end()) {
  11562. continue;
  11563. }
  11564. tensor_meta & metaA = tensor_meta_map.at(base_name + ".loraA");
  11565. tensor_meta & metaB = tensor_meta_map.at(base_name + ".loraB");
  11566. ggml_init_params lora_init_params = {
  11567. /* .mem_size */ ggml_tensor_overhead()*128 + ggml_graph_overhead(),
  11568. /* .mem_buffer */ nullptr,
  11569. /* .no_alloc */ true,
  11570. };
  11571. ggml_context * lora_ctx = ggml_init(lora_init_params);
  11572. if (lora_ctx == nullptr) {
  11573. LLAMA_LOG_ERROR("%s: error: failed to initialize lora context\n", __func__);
  11574. ggml_backend_free(backend_cpu);
  11575. return 1;
  11576. }
  11577. // create tensors
  11578. ggml_tensor * loraA = ggml_new_tensor_2d(lora_ctx, metaA.type, metaA.ne[0], metaA.ne[1]);
  11579. ggml_tensor * loraB = ggml_new_tensor_2d(lora_ctx, metaB.type, metaB.ne[0], metaB.ne[1]);
  11580. ggml_set_name(loraA, metaA.name.c_str());
  11581. ggml_set_name(loraB, metaB.name.c_str());
  11582. ggml_tensor * base_t;
  11583. if (ml) {
  11584. if (!ml->get_tensor_meta(base_name.c_str())) {
  11585. LLAMA_LOG_ERROR("%s: error: tensor '%s' not found in base model\n", __func__, base_name.c_str());
  11586. return 1;
  11587. }
  11588. base_t = ggml_dup_tensor(lora_ctx, ml->get_tensor_meta(base_name.c_str()));
  11589. } else {
  11590. base_t = ggml_dup_tensor(lora_ctx, model_t);
  11591. }
  11592. ggml_set_name(base_t, base_name.c_str());
  11593. // allocate in backend buffer
  11594. ggml_backend_buffer_t lora_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  11595. if (lora_buf == nullptr) {
  11596. LLAMA_LOG_ERROR("%s: error: failed to allocate lora tensors\n", __func__);
  11597. return 1;
  11598. }
  11599. // load tensor data
  11600. auto load_tensor = [&read_buf, &fin](const tensor_meta & tensor_meta, ggml_tensor * tensor) {
  11601. read_buf.resize(ggml_nbytes(tensor));
  11602. fin.seek(tensor_meta.offset, SEEK_SET);
  11603. fin.read_raw(read_buf.data(), ggml_nbytes(tensor));
  11604. ggml_backend_tensor_set(tensor, read_buf.data(), 0, read_buf.size());
  11605. };
  11606. load_tensor(metaA, loraA);
  11607. load_tensor(metaB, loraB);
  11608. // load base model tensor data
  11609. if (ml) {
  11610. ml->load_data_for(base_t);
  11611. } else {
  11612. ggml_backend_tensor_copy(model_t, base_t);
  11613. }
  11614. if (ggml_is_quantized(base_t->type) && !warned) {
  11615. LLAMA_LOG_WARN("%s: warning: using a lora adapter with a quantized model may result in poor quality, "
  11616. "use a f16 or f32 base model with --lora-base\n", __func__);
  11617. warned = true;
  11618. }
  11619. if (base_t->ne[0] != loraA->ne[1] || base_t->ne[1] != loraB->ne[1]) {
  11620. LLAMA_LOG_ERROR("%s: incompatible tensor dimensions (%" PRId64 " and %" PRId64 ");"
  11621. " are you sure that this adapter is for this model?\n", __func__, base_t->ne[0], loraA->ne[1]);
  11622. ggml_free(lora_ctx);
  11623. ggml_backend_buffer_free(lora_buf);
  11624. ggml_backend_free(backend_cpu);
  11625. return 1;
  11626. }
  11627. auto build_lora_graph = [&]() {
  11628. // w = w + BA*s
  11629. ggml_tensor * BA = ggml_mul_mat(lora_ctx, loraA, loraB);
  11630. ggml_set_name(BA, "BA");
  11631. if (scaling != 1.0f) {
  11632. BA = ggml_scale(lora_ctx, BA, scaling);
  11633. ggml_set_name(BA, "BA_scaled");
  11634. }
  11635. ggml_tensor * r;
  11636. r = ggml_add_inplace(lora_ctx, base_t, BA);
  11637. ggml_set_name(r, "r_add");
  11638. if (base_t->type != model_t->type) {
  11639. // convert the result to the model type
  11640. r = ggml_cast(lora_ctx, r, model_t->type);
  11641. ggml_set_name(r, "r_cast");
  11642. }
  11643. return r;
  11644. };
  11645. ggml_cgraph * gf = ggml_new_graph(lora_ctx);
  11646. ggml_tensor * r = build_lora_graph();
  11647. ggml_build_forward_expand(gf, r);
  11648. ggml_backend_buffer_t graph_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  11649. if (graph_buf == nullptr) {
  11650. LLAMA_LOG_ERROR("%s: error: failed to allocate graph tensors\n", __func__);
  11651. ggml_free(lora_ctx);
  11652. ggml_backend_buffer_free(lora_buf);
  11653. ggml_backend_free(backend_cpu);
  11654. return 1;
  11655. }
  11656. ggml_backend_graph_compute(backend_cpu, gf);
  11657. ggml_backend_tensor_set(model_t, r->data, 0, ggml_nbytes(r));
  11658. #if 0
  11659. // TODO: use scheduler with fallback to CPU for less copies between CPU and GPU
  11660. //ggml_backend_sched_t sched = ggml_backend_sched_new(backends.data(), backends.size(), GGML_DEFAULT_GRAPH_SIZE);
  11661. // sched compute
  11662. ggml_build_forward_expand(gf, build_graph());
  11663. ggml_backend_sched_init_measure(sched, gf);
  11664. // create the graph again, since the previous one was destroyed by the measure
  11665. ggml_graph_clear(gf);
  11666. ggml_build_forward_expand(gf, build_graph());
  11667. ggml_backend_sched_graph_compute(sched, gf);
  11668. ggml_backend_sched_free(sched);
  11669. #endif
  11670. ggml_backend_buffer_free(lora_buf);
  11671. ggml_backend_buffer_free(graph_buf);
  11672. ggml_free(lora_ctx);
  11673. n_tensors++;
  11674. if (n_tensors % 4 == 0) {
  11675. LLAMA_LOG_INFO(".");
  11676. }
  11677. }
  11678. ggml_backend_free(backend_cpu);
  11679. const int64_t t_lora_us = ggml_time_us() - t_start_lora_us;
  11680. LLAMA_LOG_INFO(" done (%.2f ms)\n", t_lora_us / 1000.0);
  11681. return 0;
  11682. }
  11683. //
  11684. // interface implementation
  11685. //
  11686. struct llama_model_params llama_model_default_params() {
  11687. struct llama_model_params result = {
  11688. /*.n_gpu_layers =*/ 0,
  11689. /*.split_mode =*/ LLAMA_SPLIT_MODE_LAYER,
  11690. /*.main_gpu =*/ 0,
  11691. /*.tensor_split =*/ nullptr,
  11692. /*.progress_callback =*/ nullptr,
  11693. /*.progress_callback_user_data =*/ nullptr,
  11694. /*.kv_overrides =*/ nullptr,
  11695. /*.vocab_only =*/ false,
  11696. /*.use_mmap =*/ true,
  11697. /*.use_mlock =*/ false,
  11698. };
  11699. #ifdef GGML_USE_METAL
  11700. // note: we usually have plenty of VRAM, so by default offload all layers to the GPU
  11701. result.n_gpu_layers = 999;
  11702. #endif
  11703. return result;
  11704. }
  11705. struct llama_context_params llama_context_default_params() {
  11706. struct llama_context_params result = {
  11707. /*.seed =*/ LLAMA_DEFAULT_SEED,
  11708. /*.n_ctx =*/ 512,
  11709. /*.n_batch =*/ 2048,
  11710. /*.n_ubatch =*/ 512,
  11711. /*.n_seq_max =*/ 1,
  11712. /*.n_threads =*/ GGML_DEFAULT_N_THREADS, // TODO: better default
  11713. /*.n_threads_batch =*/ GGML_DEFAULT_N_THREADS,
  11714. /*.rope_scaling_type =*/ LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED,
  11715. /*.pooling_type =*/ LLAMA_POOLING_TYPE_UNSPECIFIED,
  11716. /*.rope_freq_base =*/ 0.0f,
  11717. /*.rope_freq_scale =*/ 0.0f,
  11718. /*.yarn_ext_factor =*/ -1.0f,
  11719. /*.yarn_attn_factor =*/ 1.0f,
  11720. /*.yarn_beta_fast =*/ 32.0f,
  11721. /*.yarn_beta_slow =*/ 1.0f,
  11722. /*.yarn_orig_ctx =*/ 0,
  11723. /*.defrag_thold =*/ -1.0f,
  11724. /*.cb_eval =*/ nullptr,
  11725. /*.cb_eval_user_data =*/ nullptr,
  11726. /*.type_k =*/ GGML_TYPE_F16,
  11727. /*.type_v =*/ GGML_TYPE_F16,
  11728. /*.logits_all =*/ false,
  11729. /*.embeddings =*/ false,
  11730. /*.offload_kqv =*/ true,
  11731. /*.abort_callback =*/ nullptr,
  11732. /*.abort_callback_data =*/ nullptr,
  11733. };
  11734. return result;
  11735. }
  11736. struct llama_model_quantize_params llama_model_quantize_default_params() {
  11737. struct llama_model_quantize_params result = {
  11738. /*.nthread =*/ 0,
  11739. /*.ftype =*/ LLAMA_FTYPE_MOSTLY_Q5_1,
  11740. /*.output_tensor_type =*/ GGML_TYPE_COUNT,
  11741. /*.token_embedding_type =*/ GGML_TYPE_COUNT,
  11742. /*.allow_requantize =*/ false,
  11743. /*.quantize_output_tensor =*/ true,
  11744. /*.only_copy =*/ false,
  11745. /*.pure =*/ false,
  11746. /*.imatrix =*/ nullptr,
  11747. /*.kv_overrides =*/ nullptr,
  11748. };
  11749. return result;
  11750. }
  11751. size_t llama_max_devices(void) {
  11752. #if defined(GGML_USE_METAL)
  11753. return 1;
  11754. #elif defined(GGML_USE_CUDA)
  11755. return GGML_CUDA_MAX_DEVICES;
  11756. #elif defined(GGML_USE_SYCL)
  11757. return GGML_SYCL_MAX_DEVICES;
  11758. #elif defined(GGML_USE_VULKAN)
  11759. return GGML_VK_MAX_DEVICES;
  11760. #else
  11761. return 1;
  11762. #endif
  11763. }
  11764. bool llama_supports_mmap(void) {
  11765. return llama_mmap::SUPPORTED;
  11766. }
  11767. bool llama_supports_mlock(void) {
  11768. return llama_mlock::SUPPORTED;
  11769. }
  11770. bool llama_supports_gpu_offload(void) {
  11771. #if defined(GGML_USE_CUDA) || defined(GGML_USE_CLBLAST) || defined(GGML_USE_METAL) || defined(GGML_USE_VULKAN) || \
  11772. defined(GGML_USE_SYCL) || defined(GGML_USE_KOMPUTE)
  11773. // Defined when llama.cpp is compiled with support for offloading model layers to GPU.
  11774. return true;
  11775. #else
  11776. return false;
  11777. #endif
  11778. }
  11779. void llama_backend_init(void) {
  11780. ggml_time_init();
  11781. // needed to initialize f16 tables
  11782. {
  11783. struct ggml_init_params params = { 0, NULL, false };
  11784. struct ggml_context * ctx = ggml_init(params);
  11785. ggml_free(ctx);
  11786. }
  11787. #ifdef GGML_USE_MPI
  11788. ggml_mpi_backend_init();
  11789. #endif
  11790. }
  11791. void llama_numa_init(enum ggml_numa_strategy numa) {
  11792. if (numa != GGML_NUMA_STRATEGY_DISABLED) {
  11793. ggml_numa_init(numa);
  11794. }
  11795. }
  11796. void llama_backend_free(void) {
  11797. #ifdef GGML_USE_MPI
  11798. ggml_mpi_backend_free();
  11799. #endif
  11800. ggml_quantize_free();
  11801. }
  11802. int64_t llama_time_us(void) {
  11803. return ggml_time_us();
  11804. }
  11805. struct llama_model * llama_load_model_from_file(
  11806. const char * path_model,
  11807. struct llama_model_params params) {
  11808. ggml_time_init();
  11809. llama_model * model = new llama_model;
  11810. unsigned cur_percentage = 0;
  11811. if (params.progress_callback == NULL) {
  11812. params.progress_callback_user_data = &cur_percentage;
  11813. params.progress_callback = [](float progress, void * ctx) {
  11814. unsigned * cur_percentage_p = (unsigned *) ctx;
  11815. unsigned percentage = (unsigned) (100 * progress);
  11816. while (percentage > *cur_percentage_p) {
  11817. *cur_percentage_p = percentage;
  11818. LLAMA_LOG_INFO(".");
  11819. if (percentage >= 100) {
  11820. LLAMA_LOG_INFO("\n");
  11821. }
  11822. }
  11823. return true;
  11824. };
  11825. }
  11826. int status = llama_model_load(path_model, *model, params);
  11827. GGML_ASSERT(status <= 0);
  11828. if (status < 0) {
  11829. if (status == -1) {
  11830. LLAMA_LOG_ERROR("%s: failed to load model\n", __func__);
  11831. } else if (status == -2) {
  11832. LLAMA_LOG_INFO("%s: cancelled model load\n", __func__);
  11833. }
  11834. delete model;
  11835. return nullptr;
  11836. }
  11837. return model;
  11838. }
  11839. void llama_free_model(struct llama_model * model) {
  11840. delete model;
  11841. }
  11842. struct llama_context * llama_new_context_with_model(
  11843. struct llama_model * model,
  11844. struct llama_context_params params) {
  11845. if (!model) {
  11846. LLAMA_LOG_ERROR("%s: model cannot be NULL\n", __func__);
  11847. return nullptr;
  11848. }
  11849. if (params.n_batch == 0 && params.n_ubatch == 0) {
  11850. LLAMA_LOG_ERROR("%s: n_batch and n_ubatch cannot both be zero\n", __func__);
  11851. return nullptr;
  11852. }
  11853. if (params.n_ctx == 0 && model->hparams.n_ctx_train == 0) {
  11854. LLAMA_LOG_ERROR("%s: n_ctx and model->hparams.n_ctx_train cannot both be zero\n", __func__);
  11855. return nullptr;
  11856. }
  11857. llama_context * ctx = new llama_context(*model);
  11858. const auto & hparams = model->hparams;
  11859. auto & cparams = ctx->cparams;
  11860. cparams.n_seq_max = std::max(1u, params.n_seq_max);
  11861. cparams.n_threads = params.n_threads;
  11862. cparams.n_threads_batch = params.n_threads_batch;
  11863. cparams.yarn_ext_factor = params.yarn_ext_factor;
  11864. cparams.yarn_attn_factor = params.yarn_attn_factor;
  11865. cparams.yarn_beta_fast = params.yarn_beta_fast;
  11866. cparams.yarn_beta_slow = params.yarn_beta_slow;
  11867. cparams.defrag_thold = params.defrag_thold;
  11868. cparams.embeddings = params.embeddings;
  11869. cparams.offload_kqv = params.offload_kqv;
  11870. cparams.pooling_type = params.pooling_type;
  11871. cparams.n_ctx = params.n_ctx == 0 ? hparams.n_ctx_train : params.n_ctx;
  11872. cparams.rope_freq_base = params.rope_freq_base == 0.0f ? hparams.rope_freq_base_train : params.rope_freq_base;
  11873. cparams.rope_freq_scale = params.rope_freq_scale == 0.0f ? hparams.rope_freq_scale_train : params.rope_freq_scale;
  11874. // this is necessary due to kv_self.n being padded later during inference
  11875. cparams.n_ctx = GGML_PAD(cparams.n_ctx, 32);
  11876. // with causal attention, the batch size is limited by the context size
  11877. cparams.n_batch = hparams.causal_attn ? std::min(cparams.n_ctx, params.n_batch) : params.n_batch;
  11878. cparams.n_ubatch = std::min(cparams.n_batch, params.n_ubatch == 0 ? params.n_batch : params.n_ubatch);
  11879. cparams.n_yarn_orig_ctx = params.yarn_orig_ctx != 0 ? params.yarn_orig_ctx :
  11880. hparams.n_yarn_orig_ctx != 0 ? hparams.n_yarn_orig_ctx :
  11881. hparams.n_ctx_train;
  11882. cparams.cb_eval = params.cb_eval;
  11883. cparams.cb_eval_user_data = params.cb_eval_user_data;
  11884. auto rope_scaling_type = params.rope_scaling_type;
  11885. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED) {
  11886. rope_scaling_type = hparams.rope_scaling_type_train;
  11887. }
  11888. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_NONE) {
  11889. cparams.rope_freq_scale = 1.0f; // never scale if scaling type is none
  11890. }
  11891. if (cparams.yarn_ext_factor < 0.0f) { // negative indicates 'not set'
  11892. cparams.yarn_ext_factor = rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_YARN ? 1.0f : 0.0f;
  11893. }
  11894. cparams.causal_attn = hparams.causal_attn;
  11895. if (cparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  11896. if (hparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  11897. cparams.pooling_type = LLAMA_POOLING_TYPE_NONE;
  11898. } else {
  11899. cparams.pooling_type = hparams.pooling_type;
  11900. }
  11901. }
  11902. if (params.seed == LLAMA_DEFAULT_SEED) {
  11903. params.seed = time(NULL);
  11904. }
  11905. LLAMA_LOG_INFO("%s: n_ctx = %u\n", __func__, cparams.n_ctx);
  11906. LLAMA_LOG_INFO("%s: n_batch = %u\n", __func__, cparams.n_batch);
  11907. LLAMA_LOG_INFO("%s: n_ubatch = %u\n", __func__, cparams.n_ubatch);
  11908. LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, cparams.rope_freq_base);
  11909. LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, cparams.rope_freq_scale);
  11910. ctx->abort_callback = params.abort_callback;
  11911. ctx->abort_callback_data = params.abort_callback_data;
  11912. ctx->rng = std::mt19937(params.seed);
  11913. ctx->logits_all = params.logits_all;
  11914. uint32_t kv_size = cparams.n_ctx;
  11915. ggml_type type_k = params.type_k;
  11916. ggml_type type_v = params.type_v;
  11917. // Mamba only needs a constant number of KV cache cells per sequence
  11918. if (model->arch == LLM_ARCH_MAMBA) {
  11919. // Mamba needs at least as many KV cells as there are sequences kept at any time
  11920. kv_size = std::max((uint32_t) 1, params.n_seq_max);
  11921. // it's probably best to keep as much precision as possible for the states
  11922. type_k = GGML_TYPE_F32; // required by ggml_ssm_conv for Mamba's conv_states
  11923. type_v = GGML_TYPE_F32; // required by ggml_ssm_scan for Mamba's ssm_states
  11924. }
  11925. GGML_ASSERT(hparams.n_embd_head_k % ggml_blck_size(type_k) == 0);
  11926. GGML_ASSERT(hparams.n_embd_head_v % ggml_blck_size(type_v) == 0);
  11927. if (!hparams.vocab_only) {
  11928. // initialize backends
  11929. #ifdef GGML_USE_METAL
  11930. if (model->n_gpu_layers > 0) {
  11931. ctx->backend_metal = ggml_backend_metal_init();
  11932. if (ctx->backend_metal == nullptr) {
  11933. LLAMA_LOG_ERROR("%s: failed to initialize Metal backend\n", __func__);
  11934. llama_free(ctx);
  11935. return nullptr;
  11936. }
  11937. ctx->backends.push_back(ctx->backend_metal);
  11938. }
  11939. #elif defined(GGML_USE_CUDA)
  11940. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  11941. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  11942. ggml_backend_t backend = ggml_backend_cuda_init(model->main_gpu);
  11943. if (backend == nullptr) {
  11944. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, model->main_gpu);
  11945. llama_free(ctx);
  11946. return nullptr;
  11947. }
  11948. ctx->backends.push_back(backend);
  11949. } else {
  11950. // LLAMA_SPLIT_MODE_LAYER requires a backend for each GPU
  11951. for (int device = 0; device < ggml_backend_cuda_get_device_count(); ++device) {
  11952. ggml_backend_t backend = ggml_backend_cuda_init(device);
  11953. if (backend == nullptr) {
  11954. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, device);
  11955. llama_free(ctx);
  11956. return nullptr;
  11957. }
  11958. ctx->backends.push_back(backend);
  11959. }
  11960. }
  11961. #elif defined(GGML_USE_VULKAN)
  11962. if (model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  11963. LLAMA_LOG_ERROR("%s: Row split not supported. Failed to initialize Vulkan backend\n", __func__);
  11964. llama_free(ctx);
  11965. return nullptr;
  11966. }
  11967. if (model->split_mode == LLAMA_SPLIT_MODE_NONE) {
  11968. ggml_backend_t backend = ggml_backend_vk_init(0);
  11969. if (backend == nullptr) {
  11970. LLAMA_LOG_ERROR("%s: failed to initialize Vulkan backend\n", __func__);
  11971. llama_free(ctx);
  11972. return nullptr;
  11973. }
  11974. ctx->backends.push_back(backend);
  11975. } else {
  11976. for (int device = 0; device < ggml_backend_vk_get_device_count(); ++device) {
  11977. ggml_backend_t backend = ggml_backend_vk_init(device);
  11978. if (backend == nullptr) {
  11979. LLAMA_LOG_ERROR("%s: failed to initialize Vulkan%d backend\n", __func__, device);
  11980. llama_free(ctx);
  11981. return nullptr;
  11982. }
  11983. ctx->backends.push_back(backend);
  11984. }
  11985. }
  11986. #elif defined(GGML_USE_SYCL)
  11987. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  11988. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  11989. ggml_backend_t backend = ggml_backend_sycl_init(model->main_gpu);
  11990. if (backend == nullptr) {
  11991. int main_gpu_id = ggml_backend_sycl_get_device_id(model->main_gpu);
  11992. LLAMA_LOG_ERROR("%s: failed to initialize SYCL%d (index %d) backend\n", __func__, main_gpu_id, model->main_gpu);
  11993. llama_free(ctx);
  11994. return nullptr;
  11995. }
  11996. ctx->backends.push_back(backend);
  11997. } else {
  11998. // LLAMA_SPLIT_LAYER requires a backend for each GPU
  11999. for (int i = 0; i < ggml_backend_sycl_get_device_count(); ++i) {
  12000. ggml_backend_t backend = ggml_backend_sycl_init(i);
  12001. if (backend == nullptr) {
  12002. int id_list[GGML_SYCL_MAX_DEVICES];
  12003. ggml_sycl_get_gpu_list(id_list, GGML_SYCL_MAX_DEVICES);
  12004. LLAMA_LOG_ERROR("%s: failed to initialize SYCL%d (index %d) backend\n", __func__, id_list[i], i);
  12005. llama_free(ctx);
  12006. return nullptr;
  12007. }
  12008. ctx->backends.push_back(backend);
  12009. }
  12010. }
  12011. #elif defined(GGML_USE_KOMPUTE)
  12012. if (model->n_gpu_layers > 0) {
  12013. auto * backend = ggml_backend_kompute_init(model->main_gpu);
  12014. if (backend == nullptr) {
  12015. LLAMA_LOG_ERROR("%s: failed to initialize Kompute backend\n", __func__);
  12016. llama_free(ctx);
  12017. return nullptr;
  12018. }
  12019. ctx->backends.push_back(backend);
  12020. }
  12021. #endif
  12022. ctx->backend_cpu = ggml_backend_cpu_init();
  12023. if (ctx->backend_cpu == nullptr) {
  12024. LLAMA_LOG_ERROR("%s: failed to initialize CPU backend\n", __func__);
  12025. llama_free(ctx);
  12026. return nullptr;
  12027. }
  12028. ctx->backends.push_back(ctx->backend_cpu);
  12029. if (!llama_kv_cache_init(ctx->kv_self, ctx->model, type_k, type_v, kv_size, cparams.offload_kqv)) {
  12030. LLAMA_LOG_ERROR("%s: llama_kv_cache_init() failed for self-attention cache\n", __func__);
  12031. llama_free(ctx);
  12032. return nullptr;
  12033. }
  12034. {
  12035. size_t memory_size_k = 0;
  12036. size_t memory_size_v = 0;
  12037. for (auto & k : ctx->kv_self.k_l) {
  12038. memory_size_k += ggml_nbytes(k);
  12039. }
  12040. for (auto & v : ctx->kv_self.v_l) {
  12041. memory_size_v += ggml_nbytes(v);
  12042. }
  12043. LLAMA_LOG_INFO("%s: KV self size = %7.2f MiB, K (%s): %7.2f MiB, V (%s): %7.2f MiB\n", __func__,
  12044. (float)(memory_size_k + memory_size_v) / (1024.0f * 1024.0f),
  12045. ggml_type_name(type_k), (float)memory_size_k / (1024.0f * 1024.0f),
  12046. ggml_type_name(type_v), (float)memory_size_v / (1024.0f * 1024.0f));
  12047. }
  12048. // graph outputs buffer
  12049. {
  12050. // resized during inference when a batch uses more outputs
  12051. if (llama_output_reserve(*ctx, params.n_seq_max) < params.n_seq_max) {
  12052. LLAMA_LOG_ERROR("%s: failed to reserve initial output buffer\n", __func__);
  12053. llama_free(ctx);
  12054. return nullptr;
  12055. }
  12056. LLAMA_LOG_INFO("%s: %10s output buffer size = %8.2f MiB\n", __func__,
  12057. ggml_backend_buffer_name(ctx->buf_output),
  12058. ggml_backend_buffer_get_size(ctx->buf_output) / 1024.0 / 1024.0);
  12059. }
  12060. // scheduler and compute buffers
  12061. {
  12062. // buffer types used for the compute buffer of each backend
  12063. std::vector<ggml_backend_buffer_type_t> backend_buft;
  12064. for (auto * backend : ctx->backends) {
  12065. if (ggml_backend_is_cpu(backend)) {
  12066. // use host buffers for the CPU backend compute buffer
  12067. backend_buft.push_back(llama_default_buffer_type_cpu(true));
  12068. } else {
  12069. backend_buft.push_back(ggml_backend_get_default_buffer_type(backend));
  12070. }
  12071. }
  12072. // buffer used to store the computation graph and the tensor meta data
  12073. ctx->buf_compute_meta.resize(ggml_tensor_overhead()*LLAMA_MAX_NODES + ggml_graph_overhead_custom(LLAMA_MAX_NODES, false));
  12074. // enabling pipeline parallelism in the scheduler increases memory usage, so it is only done when necessary
  12075. bool pipeline_parallel = llama_get_device_count() > 1 && model->n_gpu_layers > (int)model->hparams.n_layer && model->split_mode == LLAMA_SPLIT_MODE_LAYER;
  12076. #ifndef GGML_USE_CUDA
  12077. // pipeline parallelism requires support for async compute and events
  12078. // currently this is only implemented in the CUDA backend
  12079. pipeline_parallel = false;
  12080. #endif
  12081. ctx->sched = ggml_backend_sched_new(ctx->backends.data(), backend_buft.data(), ctx->backends.size(), LLAMA_MAX_NODES, pipeline_parallel);
  12082. if (pipeline_parallel) {
  12083. LLAMA_LOG_INFO("%s: pipeline parallelism enabled (n_copies=%d)\n", __func__, ggml_backend_sched_get_n_copies(ctx->sched));
  12084. }
  12085. // build worst-case graph
  12086. int n_tokens = (int)std::min(cparams.n_ctx, cparams.n_ubatch);
  12087. int n_past = cparams.n_ctx - n_tokens;
  12088. 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
  12089. ggml_cgraph * gf = llama_build_graph(*ctx, llama_batch_get_one(&token, n_tokens, n_past, 0), true);
  12090. // initialize scheduler with the worst-case graph
  12091. if (!ggml_backend_sched_reserve(ctx->sched, gf)) {
  12092. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  12093. llama_free(ctx);
  12094. return nullptr;
  12095. }
  12096. for (size_t i = 0; i < ctx->backends.size(); i++) {
  12097. ggml_backend_t backend = ctx->backends[i];
  12098. ggml_backend_buffer_type_t buft = backend_buft[i];
  12099. size_t size = ggml_backend_sched_get_buffer_size(ctx->sched, backend);
  12100. if (size > 1) {
  12101. LLAMA_LOG_INFO("%s: %10s compute buffer size = %8.2f MiB\n", __func__,
  12102. ggml_backend_buft_name(buft),
  12103. size / 1024.0 / 1024.0);
  12104. }
  12105. }
  12106. // note: the number of splits during measure is higher than during inference due to the kv shift
  12107. int n_splits = ggml_backend_sched_get_n_splits(ctx->sched);
  12108. LLAMA_LOG_INFO("%s: graph nodes = %d\n", __func__, gf->n_nodes);
  12109. LLAMA_LOG_INFO("%s: graph splits = %d\n", __func__, n_splits);
  12110. }
  12111. }
  12112. #ifdef GGML_USE_MPI
  12113. ctx->ctx_mpi = ggml_mpi_init();
  12114. if (ggml_mpi_rank(ctx->ctx_mpi) > 0) {
  12115. // Enter a blocking eval loop with dummy input, letting rank=0 drive the process
  12116. // TODO: needs fix after #3228
  12117. GGML_ASSERT(false && "not implemented");
  12118. //const std::vector<llama_token> tmp(ctx->model.hparams.n_ctx, llama_token_bos(ctx));
  12119. //while (!llama_eval(ctx, tmp.data(), tmp.size(), 0, 0)) {};
  12120. llama_backend_free();
  12121. exit(1);
  12122. }
  12123. #endif
  12124. return ctx;
  12125. }
  12126. void llama_free(struct llama_context * ctx) {
  12127. delete ctx;
  12128. }
  12129. const llama_model * llama_get_model(const struct llama_context * ctx) {
  12130. return &ctx->model;
  12131. }
  12132. uint32_t llama_n_ctx(const struct llama_context * ctx) {
  12133. return ctx->cparams.n_ctx;
  12134. }
  12135. uint32_t llama_n_batch(const struct llama_context * ctx) {
  12136. return ctx->cparams.n_batch;
  12137. }
  12138. uint32_t llama_n_ubatch(const struct llama_context * ctx) {
  12139. return ctx->cparams.n_ubatch;
  12140. }
  12141. uint32_t llama_n_seq_max(const struct llama_context * ctx) {
  12142. return ctx->kv_self.size;
  12143. }
  12144. enum llama_vocab_type llama_vocab_type(const struct llama_model * model) {
  12145. return model->vocab.type;
  12146. }
  12147. enum llama_rope_type llama_rope_type(const struct llama_model * model) {
  12148. switch (model->arch) {
  12149. // these models do not use RoPE
  12150. case LLM_ARCH_GPT2:
  12151. case LLM_ARCH_GPTJ:
  12152. case LLM_ARCH_GPTNEOX:
  12153. case LLM_ARCH_MPT:
  12154. case LLM_ARCH_REFACT:
  12155. case LLM_ARCH_BLOOM:
  12156. case LLM_ARCH_MAMBA:
  12157. return LLAMA_ROPE_TYPE_NONE;
  12158. // use what we call a normal RoPE, operating on pairs of consecutive head values
  12159. case LLM_ARCH_LLAMA:
  12160. case LLM_ARCH_BAICHUAN:
  12161. case LLM_ARCH_STARCODER:
  12162. case LLM_ARCH_PLAMO:
  12163. case LLM_ARCH_CODESHELL:
  12164. case LLM_ARCH_ORION:
  12165. case LLM_ARCH_INTERNLM2:
  12166. case LLM_ARCH_MINICPM:
  12167. case LLM_ARCH_XVERSE:
  12168. case LLM_ARCH_COMMAND_R:
  12169. return LLAMA_ROPE_TYPE_NORM;
  12170. // the pairs of head values are offset by n_rot/2
  12171. case LLM_ARCH_FALCON:
  12172. case LLM_ARCH_GROK:
  12173. case LLM_ARCH_PERSIMMON:
  12174. case LLM_ARCH_BERT:
  12175. case LLM_ARCH_NOMIC_BERT:
  12176. case LLM_ARCH_STABLELM:
  12177. case LLM_ARCH_QWEN:
  12178. case LLM_ARCH_QWEN2:
  12179. case LLM_ARCH_PHI2:
  12180. case LLM_ARCH_GEMMA:
  12181. case LLM_ARCH_STARCODER2:
  12182. return LLAMA_ROPE_TYPE_NEOX;
  12183. // all model arches should be listed explicitly here
  12184. case LLM_ARCH_UNKNOWN:
  12185. GGML_ASSERT(false && "unknown architecture");
  12186. break;
  12187. }
  12188. return LLAMA_ROPE_TYPE_NONE;
  12189. }
  12190. int32_t llama_n_vocab(const struct llama_model * model) {
  12191. return model->hparams.n_vocab;
  12192. }
  12193. int32_t llama_n_ctx_train(const struct llama_model * model) {
  12194. return model->hparams.n_ctx_train;
  12195. }
  12196. int32_t llama_n_embd(const struct llama_model * model) {
  12197. return model->hparams.n_embd;
  12198. }
  12199. int32_t llama_n_layer(const struct llama_model * model) {
  12200. return model->hparams.n_layer;
  12201. }
  12202. float llama_rope_freq_scale_train(const struct llama_model * model) {
  12203. return model->hparams.rope_freq_scale_train;
  12204. }
  12205. int32_t llama_model_meta_val_str(const struct llama_model * model, const char * key, char * buf, size_t buf_size) {
  12206. const auto & it = model->gguf_kv.find(key);
  12207. if (it == model->gguf_kv.end()) {
  12208. if (buf_size > 0) {
  12209. buf[0] = '\0';
  12210. }
  12211. return -1;
  12212. }
  12213. return snprintf(buf, buf_size, "%s", it->second.c_str());
  12214. }
  12215. int32_t llama_model_meta_count(const struct llama_model * model) {
  12216. return (int)model->gguf_kv.size();
  12217. }
  12218. int32_t llama_model_meta_key_by_index(const struct llama_model * model, int i, char * buf, size_t buf_size) {
  12219. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  12220. if (buf_size > 0) {
  12221. buf[0] = '\0';
  12222. }
  12223. return -1;
  12224. }
  12225. auto it = model->gguf_kv.begin();
  12226. std::advance(it, i);
  12227. return snprintf(buf, buf_size, "%s", it->first.c_str());
  12228. }
  12229. int32_t llama_model_meta_val_str_by_index(const struct llama_model * model, int32_t i, char * buf, size_t buf_size) {
  12230. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  12231. if (buf_size > 0) {
  12232. buf[0] = '\0';
  12233. }
  12234. return -1;
  12235. }
  12236. auto it = model->gguf_kv.begin();
  12237. std::advance(it, i);
  12238. return snprintf(buf, buf_size, "%s", it->second.c_str());
  12239. }
  12240. int32_t llama_model_desc(const struct llama_model * model, char * buf, size_t buf_size) {
  12241. return snprintf(buf, buf_size, "%s %s %s",
  12242. llama_model_arch_name(model->arch),
  12243. llama_model_type_name(model->type),
  12244. llama_model_ftype_name(model->ftype).c_str());
  12245. }
  12246. uint64_t llama_model_size(const struct llama_model * model) {
  12247. uint64_t size = 0;
  12248. for (const auto & it : model->tensors_by_name) {
  12249. size += ggml_nbytes(it.second);
  12250. }
  12251. return size;
  12252. }
  12253. uint64_t llama_model_n_params(const struct llama_model * model) {
  12254. uint64_t nparams = 0;
  12255. for (const auto & it : model->tensors_by_name) {
  12256. nparams += ggml_nelements(it.second);
  12257. }
  12258. return nparams;
  12259. }
  12260. struct ggml_tensor * llama_get_model_tensor(struct llama_model * model, const char * name) {
  12261. auto it = std::find_if(model->tensors_by_name.begin(), model->tensors_by_name.end(),
  12262. [name](const std::pair<std::string, struct ggml_tensor *> & it) {
  12263. return it.first == name;
  12264. });
  12265. if (it == model->tensors_by_name.end()) {
  12266. return nullptr;
  12267. }
  12268. return it->second;
  12269. }
  12270. uint32_t llama_model_quantize(
  12271. const char * fname_inp,
  12272. const char * fname_out,
  12273. const llama_model_quantize_params * params) {
  12274. try {
  12275. llama_model_quantize_internal(fname_inp, fname_out, params);
  12276. return 0;
  12277. } catch (const std::exception & err) {
  12278. LLAMA_LOG_ERROR("%s: failed to quantize: %s\n", __func__, err.what());
  12279. return 1;
  12280. }
  12281. }
  12282. 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) {
  12283. try {
  12284. return llama_apply_lora_from_file_internal(*model, path_lora, scale, path_base_model, n_threads);
  12285. } catch (const std::exception & err) {
  12286. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  12287. return 1;
  12288. }
  12289. }
  12290. static bool llama_control_vector_init(struct llama_control_vector & cvec, const llama_model & model) {
  12291. GGML_ASSERT(cvec.tensors.empty());
  12292. GGML_ASSERT(cvec.ctxs.empty());
  12293. GGML_ASSERT(cvec.bufs.empty());
  12294. // count layer buffer types
  12295. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  12296. for (int64_t i = 0; i < model.hparams.n_layer; i++) {
  12297. buft_layer_count[model.buft_layer[i].buft]++;
  12298. }
  12299. // allocate contexts
  12300. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  12301. for (auto & it : buft_layer_count) {
  12302. int n_layers = it.second;
  12303. struct ggml_init_params params = {
  12304. /*.mem_size =*/ n_layers * ggml_tensor_overhead(),
  12305. /*.mem_buffer =*/ NULL,
  12306. /*.no_alloc =*/ true,
  12307. };
  12308. ggml_context * ctx = ggml_init(params);
  12309. if (!ctx) {
  12310. LLAMA_LOG_ERROR("%s: failed to allocate context for control vector\n", __func__);
  12311. return 1;
  12312. }
  12313. ctx_map[it.first] = ctx;
  12314. }
  12315. // make tensors
  12316. cvec.tensors.push_back(nullptr); // there's never a tensor for layer 0
  12317. for (size_t il = 1; il < model.hparams.n_layer; il++) {
  12318. struct ggml_context * ctx = ctx_map.at(model.buft_layer[il].buft);
  12319. ggml_tensor * tensor = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, model.hparams.n_embd);
  12320. cvec.tensors.push_back(tensor);
  12321. }
  12322. // allocate tensors / buffers and zero
  12323. for (auto it : ctx_map) {
  12324. ggml_backend_buffer_type_t buft = it.first;
  12325. ggml_context * ctx = it.second;
  12326. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  12327. if (!buf) {
  12328. LLAMA_LOG_ERROR("%s: failed to allocate buffer for control vector\n", __func__);
  12329. return false;
  12330. }
  12331. ggml_backend_buffer_clear(buf, 0);
  12332. cvec.ctxs.push_back(ctx);
  12333. cvec.bufs.push_back(buf);
  12334. }
  12335. return true;
  12336. }
  12337. 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) {
  12338. const llama_model & model = lctx->model;
  12339. llama_control_vector & cvec = lctx->cvec;
  12340. if (data == nullptr) {
  12341. // disable the current control vector (but leave allocated for later)
  12342. cvec.layer_start = -1;
  12343. cvec.layer_end = -1;
  12344. return 0;
  12345. }
  12346. if (n_embd != (int) model.hparams.n_embd) {
  12347. LLAMA_LOG_ERROR("%s: control vector n_embd does not match model\n", __func__);
  12348. return 1;
  12349. }
  12350. if (cvec.tensors.empty()) {
  12351. if (!llama_control_vector_init(cvec, model)) {
  12352. return 1;
  12353. }
  12354. }
  12355. cvec.layer_start = il_start;
  12356. cvec.layer_end = il_end;
  12357. for (size_t il = 1; il < model.hparams.n_layer; il++) {
  12358. assert(cvec.tensors[il] != nullptr);
  12359. const size_t off = n_embd * (il - 1); // buffer doesn't have data for layer 0, since it's never present
  12360. if (off + n_embd <= len) {
  12361. ggml_backend_tensor_set(cvec.tensors[il], data + off, 0, n_embd * ggml_element_size(cvec.tensors[il]));
  12362. }
  12363. }
  12364. return 0;
  12365. }
  12366. struct llama_kv_cache_view llama_kv_cache_view_init(const struct llama_context * ctx, int32_t n_seq_max) {
  12367. struct llama_kv_cache_view result = {
  12368. /*.n_cells = */ 0,
  12369. /*.n_seq_max = */ n_seq_max,
  12370. /*.token_count = */ 0,
  12371. /*.used_cells = */ llama_get_kv_cache_used_cells(ctx),
  12372. /*.max_contiguous = */ 0,
  12373. /*.max_contiguous_idx = */ -1,
  12374. /*.cells = */ nullptr,
  12375. /*.cells_sequences = */ nullptr,
  12376. };
  12377. return result;
  12378. }
  12379. void llama_kv_cache_view_free(struct llama_kv_cache_view * view) {
  12380. if (view->cells != nullptr) {
  12381. free(view->cells);
  12382. view->cells = nullptr;
  12383. }
  12384. if (view->cells_sequences != nullptr) {
  12385. free(view->cells_sequences);
  12386. view->cells_sequences = nullptr;
  12387. }
  12388. }
  12389. void llama_kv_cache_view_update(const struct llama_context * ctx, struct llama_kv_cache_view * view) {
  12390. if (uint32_t(view->n_cells) < ctx->kv_self.size || view->cells == nullptr) {
  12391. view->n_cells = int32_t(ctx->kv_self.size);
  12392. void * p = realloc(view->cells, sizeof(struct llama_kv_cache_view_cell) * view->n_cells);
  12393. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells");
  12394. view->cells = (struct llama_kv_cache_view_cell *)p;
  12395. p = realloc(view->cells_sequences, sizeof(llama_seq_id) * view->n_seq_max * view->n_cells);
  12396. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells sequences");
  12397. view->cells_sequences = (llama_seq_id *)p;
  12398. }
  12399. const std::vector<llama_kv_cell> & kv_cells = ctx->kv_self.cells;
  12400. llama_kv_cache_view_cell * c_curr = view->cells;
  12401. llama_seq_id * cs_curr = view->cells_sequences;
  12402. int32_t used_cells = 0;
  12403. int32_t token_count = 0;
  12404. int32_t curr_contig_idx = -1;
  12405. uint32_t max_contig = 0;
  12406. int32_t max_contig_idx = -1;
  12407. for (int32_t i = 0; i < int32_t(ctx->kv_self.size); i++, c_curr++, cs_curr += view->n_seq_max) {
  12408. const size_t curr_size = kv_cells[i].seq_id.size();
  12409. token_count += curr_size;
  12410. c_curr->pos = kv_cells[i].pos + kv_cells[i].delta;
  12411. if (curr_size > 0) {
  12412. if (curr_contig_idx >= 0 && uint32_t(i - curr_contig_idx) > max_contig) {
  12413. max_contig = i - curr_contig_idx;
  12414. max_contig_idx = curr_contig_idx;
  12415. }
  12416. curr_contig_idx = -1;
  12417. } else if (curr_contig_idx < 0) {
  12418. curr_contig_idx = i;
  12419. }
  12420. int seq_idx = 0;
  12421. for (const llama_seq_id it : kv_cells[i].seq_id) {
  12422. if (seq_idx >= view->n_seq_max) {
  12423. break;
  12424. }
  12425. cs_curr[seq_idx] = it;
  12426. seq_idx++;
  12427. }
  12428. if (seq_idx != 0) {
  12429. used_cells++;
  12430. }
  12431. for (; seq_idx < view->n_seq_max; seq_idx++) {
  12432. cs_curr[seq_idx] = -1;
  12433. }
  12434. }
  12435. if (curr_contig_idx >= 0 && kv_cells.size() - curr_contig_idx > max_contig) {
  12436. max_contig_idx = curr_contig_idx;
  12437. max_contig = kv_cells.size() - curr_contig_idx;
  12438. }
  12439. view->max_contiguous = max_contig;
  12440. view->max_contiguous_idx = max_contig_idx;
  12441. view->token_count = token_count;
  12442. view->used_cells = used_cells;
  12443. if (uint32_t(used_cells) != ctx->kv_self.used) {
  12444. LLAMA_LOG_ERROR("%s: used cells mismatch. kv_cache says %d but we calculated %d\n",
  12445. __func__, ctx->kv_self.used, used_cells);
  12446. }
  12447. }
  12448. int32_t llama_get_kv_cache_token_count(const struct llama_context * ctx) {
  12449. int result = 0;
  12450. for (uint32_t i = 0; i < ctx->kv_self.size; i++) {
  12451. result += ctx->kv_self.cells[i].seq_id.size();
  12452. }
  12453. return result;
  12454. }
  12455. int32_t llama_get_kv_cache_used_cells(const struct llama_context * ctx) {
  12456. return ctx->kv_self.used;
  12457. }
  12458. void llama_kv_cache_clear(struct llama_context * ctx) {
  12459. llama_kv_cache_clear(ctx->kv_self);
  12460. }
  12461. bool llama_kv_cache_seq_rm(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
  12462. return llama_kv_cache_seq_rm(ctx->kv_self, seq_id, p0, p1);
  12463. }
  12464. 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) {
  12465. if (seq_id_src == seq_id_dst) {
  12466. return;
  12467. }
  12468. llama_kv_cache_seq_cp(ctx->kv_self, seq_id_src, seq_id_dst, p0, p1);
  12469. }
  12470. void llama_kv_cache_seq_keep(struct llama_context * ctx, llama_seq_id seq_id) {
  12471. llama_kv_cache_seq_keep(ctx->kv_self, seq_id);
  12472. }
  12473. void llama_kv_cache_seq_add(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos delta) {
  12474. if (delta == 0) {
  12475. return;
  12476. }
  12477. llama_kv_cache_seq_add(ctx->kv_self, seq_id, p0, p1, delta);
  12478. }
  12479. void llama_kv_cache_seq_div(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) {
  12480. if (d == 1) {
  12481. return;
  12482. }
  12483. llama_kv_cache_seq_div(ctx->kv_self, seq_id, p0, p1, d);
  12484. }
  12485. llama_pos llama_kv_cache_seq_pos_max(struct llama_context * ctx, llama_seq_id seq_id) {
  12486. return llama_kv_cache_seq_pos_max(ctx->kv_self, seq_id);
  12487. }
  12488. void llama_kv_cache_defrag(struct llama_context * ctx) {
  12489. llama_kv_cache_defrag(ctx->kv_self);
  12490. }
  12491. void llama_kv_cache_update(struct llama_context * ctx) {
  12492. llama_kv_cache_update_internal(*ctx);
  12493. }
  12494. // deprecated
  12495. size_t llama_get_state_size(const struct llama_context * ctx) {
  12496. return llama_state_get_size(ctx);
  12497. }
  12498. // deprecated
  12499. size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dst) {
  12500. return llama_state_get_data(ctx, dst);
  12501. }
  12502. // deprecated
  12503. size_t llama_set_state_data(struct llama_context * ctx, const uint8_t * src) {
  12504. return llama_state_set_data(ctx, src);
  12505. }
  12506. // deprecated
  12507. 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) {
  12508. return llama_state_load_file(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  12509. }
  12510. // deprecated
  12511. bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  12512. return llama_state_save_file(ctx, path_session, tokens, n_token_count);
  12513. }
  12514. // Returns the *maximum* size of the state
  12515. size_t llama_state_get_size(const struct llama_context * ctx) {
  12516. const auto & cparams = ctx->cparams;
  12517. const auto & hparams = ctx->model.hparams;
  12518. // we don't know size of rng until we actually serialize it. so reserve more than enough memory for its serialized state.
  12519. // for reference, std::mt19937(1337) serializes to 6701 bytes.
  12520. const size_t s_rng_size = sizeof(size_t);
  12521. const size_t s_rng = LLAMA_MAX_RNG_STATE;
  12522. const size_t s_n_outputs = sizeof(size_t);
  12523. // assume worst case for outputs although only currently set ones are serialized
  12524. const size_t s_output_pos = ctx->cparams.n_batch * sizeof(int32_t);
  12525. const size_t s_logits_size = sizeof(size_t);
  12526. const size_t s_logits = ctx->logits_size ? cparams.n_batch * hparams.n_vocab * sizeof(float) : 0;
  12527. const size_t s_embedding_size = sizeof(size_t);
  12528. const size_t s_embedding = ctx->embd_size ? cparams.n_batch * hparams.n_embd * sizeof(float) : 0;
  12529. const size_t s_kv_buf_size = sizeof(size_t);
  12530. const size_t s_kv_head = sizeof(uint32_t);
  12531. const size_t s_kv_size = sizeof(uint32_t);
  12532. const size_t s_kv_used = sizeof(uint32_t);
  12533. const size_t s_kv = ctx->kv_self.total_size();
  12534. const size_t s_kv_cell = sizeof(llama_pos) + sizeof(size_t) + cparams.n_seq_max*sizeof(llama_seq_id);
  12535. const size_t s_kv_cells = ctx->kv_self.size * s_kv_cell;
  12536. const size_t s_total = (
  12537. + s_rng_size
  12538. + s_rng
  12539. + s_n_outputs
  12540. + s_output_pos
  12541. + s_logits_size
  12542. + s_logits
  12543. + s_embedding_size
  12544. + s_embedding
  12545. + s_kv_buf_size
  12546. + s_kv_head
  12547. + s_kv_size
  12548. + s_kv_used
  12549. + s_kv
  12550. + s_kv_cells
  12551. );
  12552. return s_total;
  12553. }
  12554. // llama_context_data
  12555. struct llama_data_context {
  12556. virtual void write(const void * src, size_t size) = 0;
  12557. virtual size_t get_size_written() = 0;
  12558. virtual ~llama_data_context() = default;
  12559. };
  12560. struct llama_data_buffer_context : llama_data_context {
  12561. uint8_t * ptr;
  12562. size_t size_written = 0;
  12563. llama_data_buffer_context(uint8_t * p) : ptr(p) {}
  12564. void write(const void * src, size_t size) override {
  12565. memcpy(ptr, src, size);
  12566. ptr += size;
  12567. size_written += size;
  12568. }
  12569. size_t get_size_written() override {
  12570. return size_written;
  12571. }
  12572. };
  12573. struct llama_data_file_context : llama_data_context {
  12574. llama_file * file;
  12575. size_t size_written = 0;
  12576. llama_data_file_context(llama_file * f) : file(f) {}
  12577. void write(const void * src, size_t size) override {
  12578. file->write_raw(src, size);
  12579. size_written += size;
  12580. }
  12581. size_t get_size_written() override {
  12582. return size_written;
  12583. }
  12584. };
  12585. /** copy state data into either a buffer or file depending on the passed in context
  12586. *
  12587. * file context:
  12588. * llama_file file("/path", "wb");
  12589. * llama_data_file_context data_ctx(&file);
  12590. * llama_state_get_data(ctx, &data_ctx);
  12591. *
  12592. * buffer context:
  12593. * std::vector<uint8_t> buf(max_size, 0);
  12594. * llama_data_buffer_context data_ctx(&buf.data());
  12595. * llama_state_get_data(ctx, &data_ctx);
  12596. *
  12597. */
  12598. static void llama_state_get_data_internal(struct llama_context * ctx, llama_data_context * data_ctx) {
  12599. // copy rng
  12600. {
  12601. std::ostringstream rng_ss;
  12602. rng_ss << ctx->rng;
  12603. const std::string & rng_str = rng_ss.str();
  12604. const size_t rng_size = rng_str.size();
  12605. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  12606. data_ctx->write(&rng_size, sizeof(rng_size));
  12607. data_ctx->write(rng_str.data(), rng_size);
  12608. }
  12609. // copy outputs
  12610. {
  12611. // Can't use ctx->n_outputs because it's not for the
  12612. // entire last batch when n_ubatch is smaller than n_batch
  12613. size_t n_outputs = 0;
  12614. // copy output ids
  12615. {
  12616. std::vector<int32_t> output_pos;
  12617. const size_t n_batch = ctx->cparams.n_batch;
  12618. const auto & output_ids = ctx->output_ids;
  12619. output_pos.resize(ctx->output_size);
  12620. // build a more compact representation of the output ids
  12621. for (size_t i = 0; i < n_batch; ++i) {
  12622. // map an output id to a position in the batch
  12623. int32_t pos = output_ids[i];
  12624. if (pos >= 0) {
  12625. if ((size_t) pos >= n_outputs) {
  12626. n_outputs = pos + 1;
  12627. }
  12628. GGML_ASSERT((size_t) pos < ctx->output_size);
  12629. output_pos[pos] = i;
  12630. }
  12631. }
  12632. data_ctx->write(&n_outputs, sizeof(n_outputs));
  12633. if (n_outputs) {
  12634. data_ctx->write(output_pos.data(), n_outputs * sizeof(int32_t));
  12635. }
  12636. }
  12637. // copy logits
  12638. {
  12639. const size_t logits_size = std::min(ctx->logits_size, n_outputs * ctx->model.hparams.n_vocab);
  12640. data_ctx->write(&logits_size, sizeof(logits_size));
  12641. if (logits_size) {
  12642. data_ctx->write(ctx->logits, logits_size * sizeof(float));
  12643. }
  12644. }
  12645. // copy embeddings
  12646. {
  12647. const size_t embeddings_size = std::min(ctx->embd_size, n_outputs * ctx->model.hparams.n_embd);
  12648. data_ctx->write(&embeddings_size, sizeof(embeddings_size));
  12649. if (embeddings_size) {
  12650. data_ctx->write(ctx->embd, embeddings_size * sizeof(float));
  12651. }
  12652. }
  12653. }
  12654. // copy kv cache
  12655. {
  12656. const auto & kv_self = ctx->kv_self;
  12657. const auto & hparams = ctx->model.hparams;
  12658. const uint32_t n_layer = hparams.n_layer;
  12659. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  12660. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  12661. // NOTE: kv_size and kv_buf_size are mostly used for sanity checks
  12662. const uint32_t kv_head = llama_kv_cache_cell_max(kv_self);
  12663. const uint32_t kv_size = kv_self.size;
  12664. const size_t kv_buf_size = kv_self.total_size() / (kv_size ? kv_size : 1) * kv_head;
  12665. const uint32_t kv_used = kv_self.used;
  12666. data_ctx->write(&kv_buf_size, sizeof(kv_buf_size));
  12667. data_ctx->write(&kv_head, sizeof(kv_head));
  12668. data_ctx->write(&kv_size, sizeof(kv_size));
  12669. data_ctx->write(&kv_used, sizeof(kv_used));
  12670. if (kv_buf_size) {
  12671. const size_t pre_kv_buf_size = data_ctx->get_size_written();
  12672. std::vector<uint8_t> tmp_buf;
  12673. for (int il = 0; il < (int) n_layer; ++il) {
  12674. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_head);
  12675. tmp_buf.resize(k_size);
  12676. ggml_backend_tensor_get(kv_self.k_l[il], tmp_buf.data(), 0, tmp_buf.size());
  12677. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  12678. if (kv_self.recurrent) {
  12679. // v is contiguous for recurrent models
  12680. // TODO: use other tensors for state models than k and v
  12681. const size_t v_size = ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa*kv_head);
  12682. tmp_buf.resize(v_size);
  12683. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), 0, tmp_buf.size());
  12684. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  12685. continue;
  12686. }
  12687. // v is not contiguous, copy row by row
  12688. const size_t v_row_size = ggml_row_size(kv_self.v_l[il]->type, kv_head);
  12689. const size_t v_row_stride = ggml_row_size(kv_self.v_l[il]->type, kv_size);
  12690. tmp_buf.resize(v_row_size);
  12691. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  12692. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), ir*v_row_stride, tmp_buf.size());
  12693. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  12694. }
  12695. }
  12696. GGML_ASSERT(kv_buf_size == data_ctx->get_size_written() - pre_kv_buf_size);
  12697. }
  12698. for (uint32_t i = 0; i < kv_head; ++i) {
  12699. const auto & cell = kv_self.cells[i];
  12700. const llama_pos pos = cell.pos;
  12701. const size_t seq_id_size = cell.seq_id.size();
  12702. data_ctx->write(&pos, sizeof(pos));
  12703. data_ctx->write(&seq_id_size, sizeof(seq_id_size));
  12704. for (auto seq_id : cell.seq_id) {
  12705. data_ctx->write(&seq_id, sizeof(seq_id));
  12706. }
  12707. }
  12708. }
  12709. }
  12710. size_t llama_state_get_data(struct llama_context * ctx, uint8_t * dst) {
  12711. llama_data_buffer_context data_ctx(dst);
  12712. llama_state_get_data_internal(ctx, &data_ctx);
  12713. return data_ctx.get_size_written();
  12714. }
  12715. // Sets the state reading from the specified source address
  12716. size_t llama_state_set_data(struct llama_context * ctx, const uint8_t * src) {
  12717. const uint8_t * inp = src;
  12718. // set rng
  12719. {
  12720. size_t rng_size;
  12721. memcpy(&rng_size, inp, sizeof(rng_size)); inp += sizeof(rng_size);
  12722. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  12723. std::string rng_str((const char *)inp, rng_size); inp += rng_size;
  12724. std::istringstream rng_ss(rng_str);
  12725. rng_ss >> ctx->rng;
  12726. GGML_ASSERT(!rng_ss.fail());
  12727. }
  12728. // set output ids
  12729. {
  12730. size_t n_outputs;
  12731. std::vector<int32_t> output_pos;
  12732. memcpy(&n_outputs, inp, sizeof(n_outputs)); inp += sizeof(n_outputs);
  12733. GGML_ASSERT(n_outputs <= llama_output_reserve(*ctx, n_outputs));
  12734. if (n_outputs) {
  12735. output_pos.resize(n_outputs);
  12736. memcpy(output_pos.data(), inp, n_outputs * sizeof(int32_t));
  12737. inp += n_outputs * sizeof(int32_t);
  12738. for (int32_t i = 0; i < (int32_t) output_pos.size(); ++i) {
  12739. int32_t id = output_pos[i];
  12740. GGML_ASSERT((uint32_t) id < ctx->cparams.n_batch);
  12741. ctx->output_ids[id] = i;
  12742. }
  12743. }
  12744. }
  12745. // set logits
  12746. {
  12747. size_t logits_size;
  12748. memcpy(&logits_size, inp, sizeof(logits_size)); inp += sizeof(logits_size);
  12749. GGML_ASSERT(ctx->logits_size >= logits_size);
  12750. if (logits_size) {
  12751. memcpy(ctx->logits, inp, logits_size * sizeof(float));
  12752. inp += logits_size * sizeof(float);
  12753. }
  12754. }
  12755. // set embeddings
  12756. {
  12757. size_t embeddings_size;
  12758. memcpy(&embeddings_size, inp, sizeof(embeddings_size)); inp += sizeof(embeddings_size);
  12759. GGML_ASSERT(ctx->embd_size >= embeddings_size);
  12760. if (embeddings_size) {
  12761. memcpy(ctx->embd, inp, embeddings_size * sizeof(float));
  12762. inp += embeddings_size * sizeof(float);
  12763. }
  12764. }
  12765. // set kv cache
  12766. {
  12767. const auto & kv_self = ctx->kv_self;
  12768. const auto & hparams = ctx->model.hparams;
  12769. const uint32_t n_layer = hparams.n_layer;
  12770. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  12771. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  12772. size_t kv_buf_size;
  12773. uint32_t kv_head;
  12774. uint32_t kv_size;
  12775. uint32_t kv_used;
  12776. memcpy(&kv_buf_size, inp, sizeof(kv_buf_size)); inp += sizeof(kv_buf_size);
  12777. memcpy(&kv_head, inp, sizeof(kv_head)); inp += sizeof(kv_head);
  12778. memcpy(&kv_size, inp, sizeof(kv_size)); inp += sizeof(kv_size);
  12779. memcpy(&kv_used, inp, sizeof(kv_used)); inp += sizeof(kv_used);
  12780. if (kv_self.size != kv_size) {
  12781. // the KV cache needs to be big enough to load all the KV cells from the saved state
  12782. GGML_ASSERT(kv_self.size >= kv_head);
  12783. 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",
  12784. __func__, kv_head, kv_size, kv_self.size);
  12785. }
  12786. if (kv_buf_size) {
  12787. const size_t pre_kv_buf_size = inp - src;
  12788. GGML_ASSERT(kv_self.total_size() >= kv_buf_size);
  12789. for (int il = 0; il < (int) n_layer; ++il) {
  12790. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_head);
  12791. ggml_backend_tensor_set(kv_self.k_l[il], inp, 0, k_size);
  12792. inp += k_size;
  12793. if (kv_self.recurrent) {
  12794. // v is contiguous for recurrent models
  12795. // TODO: use other tensors for state models than k and v
  12796. const size_t v_size = ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa*kv_head);
  12797. ggml_backend_tensor_set(kv_self.v_l[il], inp, 0, v_size);
  12798. inp += v_size;
  12799. continue;
  12800. }
  12801. // v is not contiguous, copy row by row
  12802. const size_t v_row_size = ggml_row_size(kv_self.v_l[il]->type, kv_head);
  12803. const size_t v_row_stride = ggml_row_size(kv_self.v_l[il]->type, kv_self.size);
  12804. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  12805. ggml_backend_tensor_set(kv_self.v_l[il], inp, ir*v_row_stride, v_row_size);
  12806. inp += v_row_size;
  12807. }
  12808. }
  12809. GGML_ASSERT(kv_buf_size == inp - src - pre_kv_buf_size);
  12810. }
  12811. llama_kv_cache_clear(ctx);
  12812. ctx->kv_self.head = kv_head;
  12813. ctx->kv_self.used = kv_used;
  12814. for (uint32_t i = 0; i < kv_head; ++i) {
  12815. llama_pos pos;
  12816. size_t seq_id_size;
  12817. memcpy(&pos, inp, sizeof(pos)); inp += sizeof(pos);
  12818. memcpy(&seq_id_size, inp, sizeof(seq_id_size)); inp += sizeof(seq_id_size);
  12819. ctx->kv_self.cells[i].pos = pos;
  12820. llama_seq_id seq_id;
  12821. for (size_t j = 0; j < seq_id_size; ++j) {
  12822. memcpy(&seq_id, inp, sizeof(seq_id)); inp += sizeof(seq_id);
  12823. ctx->kv_self.cells[i].seq_id.insert(seq_id);
  12824. }
  12825. }
  12826. }
  12827. const size_t nread = inp - src;
  12828. const size_t max_size = llama_state_get_size(ctx);
  12829. GGML_ASSERT(nread <= max_size);
  12830. return nread;
  12831. }
  12832. 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) {
  12833. llama_file file(path_session, "rb");
  12834. // sanity checks
  12835. {
  12836. const uint32_t magic = file.read_u32();
  12837. const uint32_t version = file.read_u32();
  12838. if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
  12839. LLAMA_LOG_ERROR("%s : unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
  12840. return false;
  12841. }
  12842. llama_hparams session_hparams;
  12843. file.read_raw(&session_hparams, sizeof(llama_hparams));
  12844. if (session_hparams != ctx->model.hparams) {
  12845. LLAMA_LOG_INFO("%s : model hparams didn't match from session file!\n", __func__);
  12846. return false;
  12847. }
  12848. }
  12849. // load the prompt
  12850. {
  12851. const uint32_t n_token_count = file.read_u32();
  12852. if (n_token_count > n_token_capacity) {
  12853. LLAMA_LOG_ERROR("%s : token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  12854. return false;
  12855. }
  12856. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  12857. *n_token_count_out = n_token_count;
  12858. }
  12859. // restore the context state
  12860. {
  12861. const size_t n_state_size_cur = file.size - file.tell();
  12862. const size_t n_state_size_max = llama_state_get_size(ctx);
  12863. if (n_state_size_cur > n_state_size_max) {
  12864. 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);
  12865. return false;
  12866. }
  12867. std::vector<uint8_t> state_data(n_state_size_max);
  12868. file.read_raw(state_data.data(), n_state_size_cur);
  12869. llama_state_set_data(ctx, state_data.data());
  12870. }
  12871. return true;
  12872. }
  12873. 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) {
  12874. try {
  12875. return llama_state_load_file_internal(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  12876. } catch (const std::exception & err) {
  12877. LLAMA_LOG_ERROR("error loading session file: %s\n", err.what());
  12878. return false;
  12879. }
  12880. }
  12881. static bool llama_state_save_file_internal(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  12882. llama_file file(path_session, "wb");
  12883. file.write_u32(LLAMA_SESSION_MAGIC);
  12884. file.write_u32(LLAMA_SESSION_VERSION);
  12885. file.write_raw(&ctx->model.hparams, sizeof(llama_hparams));
  12886. // save the prompt
  12887. file.write_u32((uint32_t) n_token_count);
  12888. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  12889. // save the context state using stream saving
  12890. llama_data_file_context data_ctx(&file);
  12891. llama_state_get_data_internal(ctx, &data_ctx);
  12892. return true;
  12893. }
  12894. bool llama_state_save_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  12895. try {
  12896. return llama_state_save_file_internal(ctx, path_session, tokens, n_token_count);
  12897. } catch (const std::exception & err) {
  12898. LLAMA_LOG_ERROR("error saving session file: %s\n", err.what());
  12899. return false;
  12900. }
  12901. }
  12902. size_t llama_state_seq_get_size(struct llama_context* ctx, llama_seq_id seq_id) {
  12903. // save the size of size_t as a uint32_t for safety check
  12904. const size_t size_t_size_size = sizeof(uint32_t);
  12905. // other values
  12906. const size_t s_cell_count_size = sizeof(uint32_t);
  12907. const size_t s_layer_count_size = sizeof(uint32_t);
  12908. const size_t n_embd_v_gqa_size = sizeof(uint32_t);
  12909. size_t s_cell_count = 0;
  12910. size_t s_cell_data_size = 0;
  12911. const auto & kv_self = ctx->kv_self;
  12912. const auto & hparams = ctx->model.hparams;
  12913. const uint32_t n_layer = hparams.n_layer;
  12914. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  12915. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  12916. for (uint32_t i = 0; i < kv_self.size; ++i) {
  12917. const auto & cell = kv_self.cells[i];
  12918. if (cell.seq_id.count(seq_id) > 0) {
  12919. ++s_cell_count;
  12920. s_cell_data_size += sizeof(llama_pos);
  12921. }
  12922. }
  12923. for (int il = 0; il < (int)n_layer; ++il) {
  12924. // types of keys and values
  12925. s_cell_data_size += sizeof(int32_t) * 2;
  12926. // k_size_row and v_size_el values of layer
  12927. s_cell_data_size += sizeof(size_t) * 2;
  12928. // keys
  12929. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  12930. s_cell_data_size += k_size_row * s_cell_count;
  12931. // values (transposed)
  12932. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  12933. s_cell_data_size += v_size_el * s_cell_count * n_embd_v_gqa;
  12934. }
  12935. const size_t s_total = (
  12936. size_t_size_size +
  12937. s_cell_count_size +
  12938. s_layer_count_size +
  12939. n_embd_v_gqa_size +
  12940. s_cell_data_size
  12941. );
  12942. return s_total;
  12943. }
  12944. static size_t llama_state_seq_get_data_internal(struct llama_context * ctx, llama_data_context & data_ctx, llama_seq_id seq_id) {
  12945. const auto & kv_self = ctx->kv_self;
  12946. GGML_ASSERT(!kv_self.recurrent); // not implemented
  12947. // Save the size of size_t as a uint32_t for safety check
  12948. const uint32_t size_t_size = sizeof(size_t);
  12949. data_ctx.write(&size_t_size, sizeof(size_t_size));
  12950. std::vector<std::pair<uint32_t, uint32_t>> cell_ranges; // ranges, from inclusive, to exclusive
  12951. uint32_t cell_count = 0;
  12952. // Count the number of cells with the specified seq_id
  12953. // Find all the ranges of cells with this seq id
  12954. {
  12955. uint32_t cell_range_begin = kv_self.size;
  12956. for (uint32_t i = 0; i < kv_self.size; ++i) {
  12957. const auto & cell = kv_self.cells[i];
  12958. if (cell.has_seq_id(seq_id)) {
  12959. ++cell_count;
  12960. if (cell_range_begin == kv_self.size) {
  12961. cell_range_begin = i;
  12962. }
  12963. }
  12964. else {
  12965. if (cell_range_begin != kv_self.size) {
  12966. cell_ranges.push_back({ cell_range_begin, i });
  12967. cell_range_begin = kv_self.size;
  12968. }
  12969. }
  12970. }
  12971. if (cell_range_begin != kv_self.size) {
  12972. cell_ranges.push_back({ cell_range_begin, kv_self.size });
  12973. }
  12974. // DEBUG CHECK: Sum of cell counts in ranges should equal the total cell count
  12975. uint32_t cell_count_check = 0;
  12976. for (const auto & range : cell_ranges) {
  12977. cell_count_check += range.second - range.first;
  12978. }
  12979. GGML_ASSERT(cell_count == cell_count_check);
  12980. }
  12981. // Write the cell count
  12982. data_ctx.write(&cell_count, sizeof(cell_count));
  12983. const auto & hparams = ctx->model.hparams;
  12984. const uint32_t n_layer = hparams.n_layer;
  12985. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  12986. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  12987. // Write the layer count
  12988. data_ctx.write(&n_layer, sizeof(n_layer));
  12989. // Write n_embd_v_gqa
  12990. data_ctx.write(&n_embd_v_gqa, sizeof(n_embd_v_gqa));
  12991. // Iterate the ranges and write all the pos (this is the token position in the prompt)
  12992. for (const auto & range : cell_ranges) {
  12993. for (uint32_t i = range.first; i < range.second; ++i) {
  12994. const auto & cell = kv_self.cells[i];
  12995. data_ctx.write(&cell.pos, sizeof(cell.pos));
  12996. }
  12997. }
  12998. // Iterate and write all the keys first, each row is a cell
  12999. // Get whole range at a time
  13000. std::vector<uint8_t> tmp_buf;
  13001. for (int il = 0; il < (int)n_layer; ++il) {
  13002. // Write key type
  13003. const int32_t k_type_i = (int32_t)kv_self.k_l[il]->type;
  13004. data_ctx.write(&k_type_i, sizeof(k_type_i));
  13005. // Write row size of key
  13006. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  13007. data_ctx.write(&k_size_row, sizeof(k_size_row));
  13008. // Read each range of cells of k_size length each into tmp_buf and write out
  13009. for (const auto & range : cell_ranges) {
  13010. const size_t range_size = range.second - range.first;
  13011. tmp_buf.resize(range_size * k_size_row);
  13012. ggml_backend_tensor_get(kv_self.k_l[il], tmp_buf.data(), range.first * k_size_row, range_size * k_size_row);
  13013. data_ctx.write(tmp_buf.data(), tmp_buf.size());
  13014. }
  13015. }
  13016. // For the values, they are transposed, so we also need the element size and get the element ranges from each row
  13017. const uint32_t kv_size = kv_self.size;
  13018. for (int il = 0; il < (int)n_layer; ++il) {
  13019. // Write value type
  13020. const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
  13021. data_ctx.write(&v_type_i, sizeof(v_type_i));
  13022. // Write element size
  13023. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  13024. data_ctx.write(&v_size_el, sizeof(v_size_el));
  13025. // For each row, we get the element values of each cell
  13026. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  13027. // Read each range of cells of v_size_el length each into tmp_buf and write out
  13028. for (const auto & range : cell_ranges) {
  13029. const size_t range_size = range.second - range.first;
  13030. const size_t src_offset = (range.first + j * kv_size) * v_size_el;
  13031. tmp_buf.resize(range_size * v_size_el);
  13032. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), src_offset, tmp_buf.size());
  13033. data_ctx.write(tmp_buf.data(), tmp_buf.size());
  13034. }
  13035. }
  13036. }
  13037. return data_ctx.get_size_written();
  13038. }
  13039. size_t llama_state_seq_get_data(struct llama_context* ctx, uint8_t* dst, llama_seq_id seq_id) {
  13040. llama_data_buffer_context data_ctx(dst);
  13041. return llama_state_seq_get_data_internal(ctx, data_ctx, seq_id);
  13042. }
  13043. size_t llama_state_seq_set_data(struct llama_context * ctx, const uint8_t * src, llama_seq_id dest_seq_id) {
  13044. auto & kv_self = ctx->kv_self;
  13045. GGML_ASSERT(!kv_self.recurrent); // not implemented
  13046. // Wipe the slot
  13047. llama_kv_cache_seq_rm(kv_self, dest_seq_id, -1, -1);
  13048. const uint8_t * inp = src;
  13049. // Read size of size_t
  13050. uint32_t size_t_size;
  13051. memcpy(&size_t_size, inp, sizeof(size_t_size));
  13052. inp += sizeof(size_t_size);
  13053. if (size_t_size != sizeof(size_t)) {
  13054. LLAMA_LOG_ERROR("%s: size_t size mismatch\n", __func__);
  13055. return 0;
  13056. }
  13057. // Read the cell count
  13058. uint32_t cell_count;
  13059. memcpy(&cell_count, inp, sizeof(cell_count));
  13060. inp += sizeof(cell_count);
  13061. // Read the layer count
  13062. uint32_t n_layer_ref;
  13063. memcpy(&n_layer_ref, inp, sizeof(n_layer_ref));
  13064. inp += sizeof(n_layer_ref);
  13065. // Read n_embd_v_gqa
  13066. uint32_t n_embd_v_gqa_ref;
  13067. memcpy(&n_embd_v_gqa_ref, inp, sizeof(n_embd_v_gqa_ref));
  13068. inp += sizeof(n_embd_v_gqa_ref);
  13069. // Sanity check model compatibility
  13070. const auto & hparams = ctx->model.hparams;
  13071. const uint32_t n_layer = hparams.n_layer;
  13072. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  13073. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  13074. if (n_layer != n_layer_ref) {
  13075. LLAMA_LOG_ERROR("%s: mismatched n_layer (%d != %d)\n", __func__, n_layer, n_layer_ref);
  13076. return 0;
  13077. }
  13078. if (n_embd_v_gqa != n_embd_v_gqa_ref) {
  13079. LLAMA_LOG_ERROR("%s: mismatched n_embd_v_gqa (%d != %d)\n", __func__, n_embd_v_gqa, n_embd_v_gqa_ref);
  13080. return 0;
  13081. }
  13082. // Allocate the new cells for the slot
  13083. if (cell_count) {
  13084. llama_batch batch = llama_batch_init(cell_count, 0, 1);
  13085. batch.n_tokens = cell_count;
  13086. for (uint32_t i = 0; i < cell_count; ++i) {
  13087. llama_pos pos;
  13088. memcpy(&pos, inp, sizeof(pos));
  13089. inp += sizeof(pos);
  13090. batch.pos[i] = pos;
  13091. batch.n_seq_id[i] = 1;
  13092. batch.seq_id[i][0] = dest_seq_id;
  13093. }
  13094. if (!llama_kv_cache_find_slot(kv_self, batch)) {
  13095. llama_batch_free(batch);
  13096. LLAMA_LOG_ERROR("%s: failed to find available cells in kv cache\n", __func__);
  13097. return 0;
  13098. }
  13099. // 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)
  13100. // Assume that this is one contiguous block of cells
  13101. GGML_ASSERT(kv_self.head + cell_count <= kv_self.size);
  13102. GGML_ASSERT(kv_self.cells[kv_self.head].pos == batch.pos[0]);
  13103. GGML_ASSERT(kv_self.cells[kv_self.head + cell_count - 1].pos == batch.pos[cell_count - 1]);
  13104. GGML_ASSERT(kv_self.cells[kv_self.head].has_seq_id(dest_seq_id));
  13105. GGML_ASSERT(kv_self.cells[kv_self.head + cell_count - 1].has_seq_id(dest_seq_id));
  13106. // Cleanup
  13107. llama_batch_free(batch);
  13108. }
  13109. const uint32_t kv_size = kv_self.size;
  13110. const uint32_t kv_head = kv_self.head;
  13111. // For each layer, read the keys for each cell, one row is one cell, read as one contiguous blo
  13112. for (int il = 0; il < (int)n_layer; ++il) {
  13113. // Read type of key
  13114. int32_t k_type_i_ref;
  13115. memcpy(&k_type_i_ref, inp, sizeof(k_type_i_ref));
  13116. inp += sizeof(k_type_i_ref);
  13117. const int32_t k_type_i = (int32_t)kv_self.k_l[il]->type;
  13118. if (k_type_i != k_type_i_ref) {
  13119. llama_kv_cache_seq_rm(kv_self, dest_seq_id, -1, -1);
  13120. LLAMA_LOG_ERROR("%s: mismatched key type (%d != %d, layer %d)\n", __func__, k_type_i, k_type_i_ref, il);
  13121. return 0;
  13122. }
  13123. // Read row size of key
  13124. size_t k_size_row_ref;
  13125. memcpy(&k_size_row_ref, inp, sizeof(k_size_row_ref));
  13126. inp += sizeof(k_size_row_ref);
  13127. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  13128. if (k_size_row != k_size_row_ref) {
  13129. llama_kv_cache_seq_rm(kv_self, dest_seq_id, -1, -1);
  13130. LLAMA_LOG_ERROR("%s: mismatched key row size (%zu != %zu, layer %d)\n", __func__, k_size_row, k_size_row_ref, il);
  13131. return 0;
  13132. }
  13133. if (cell_count) {
  13134. // Read and set the keys for the whole cell range
  13135. ggml_backend_tensor_set(kv_self.k_l[il], inp, kv_head * k_size_row, cell_count * k_size_row);
  13136. inp += cell_count * k_size_row;
  13137. }
  13138. }
  13139. // For each layer, read the values for each cell (transposed)
  13140. for (int il = 0; il < (int)n_layer; ++il) {
  13141. // Read type of value
  13142. int32_t v_type_i_ref;
  13143. memcpy(&v_type_i_ref, inp, sizeof(v_type_i_ref));
  13144. inp += sizeof(v_type_i_ref);
  13145. const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
  13146. if (v_type_i != v_type_i_ref) {
  13147. llama_kv_cache_seq_rm(kv_self, dest_seq_id, -1, -1);
  13148. LLAMA_LOG_ERROR("%s: mismatched value type (%d != %d, layer %d)\n", __func__, v_type_i, v_type_i_ref, il);
  13149. return 0;
  13150. }
  13151. // Read element size of value
  13152. size_t v_size_el_ref;
  13153. memcpy(&v_size_el_ref, inp, sizeof(v_size_el_ref));
  13154. inp += sizeof(v_size_el_ref);
  13155. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  13156. if (v_size_el != v_size_el_ref) {
  13157. llama_kv_cache_seq_rm(kv_self, dest_seq_id, -1, -1);
  13158. LLAMA_LOG_ERROR("%s: mismatched value element size (%zu != %zu, layer %d)\n", __func__, v_size_el, v_size_el_ref, il);
  13159. return 0;
  13160. }
  13161. if (cell_count) {
  13162. // For each row in the transposed matrix, read the values for the whole cell range
  13163. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  13164. const size_t dst_offset = (kv_head + j * kv_size) * v_size_el;
  13165. ggml_backend_tensor_set(kv_self.v_l[il], inp, dst_offset, cell_count * v_size_el);
  13166. inp += cell_count * v_size_el;
  13167. }
  13168. }
  13169. }
  13170. const size_t nread = inp - src;
  13171. return nread;
  13172. }
  13173. 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) {
  13174. llama_file file(filepath, "wb");
  13175. file.write_u32(LLAMA_STATE_SEQ_MAGIC);
  13176. file.write_u32(LLAMA_STATE_SEQ_VERSION);
  13177. // save the prompt
  13178. file.write_u32((uint32_t)n_token_count);
  13179. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  13180. // save the context state using stream saving
  13181. llama_data_file_context data_ctx(&file);
  13182. llama_state_seq_get_data_internal(ctx, data_ctx, seq_id);
  13183. const size_t res = file.tell();
  13184. GGML_ASSERT(res == sizeof(uint32_t) * 3 + sizeof(llama_token) * n_token_count + data_ctx.get_size_written());
  13185. return res;
  13186. }
  13187. 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) {
  13188. llama_file file(filepath, "rb");
  13189. // version checks
  13190. {
  13191. const uint32_t magic = file.read_u32();
  13192. const uint32_t version = file.read_u32();
  13193. if (magic != LLAMA_STATE_SEQ_MAGIC || version != LLAMA_STATE_SEQ_VERSION) {
  13194. LLAMA_LOG_ERROR("%s: unknown (magic, version) for sequence state file: %08x, %08x\n", __func__, magic, version);
  13195. return 0;
  13196. }
  13197. }
  13198. // load the prompt
  13199. {
  13200. const uint32_t n_token_count = file.read_u32();
  13201. if (n_token_count > n_token_capacity) {
  13202. LLAMA_LOG_ERROR("%s: token count in sequence state file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  13203. return 0;
  13204. }
  13205. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  13206. *n_token_count_out = n_token_count;
  13207. }
  13208. // restore the context state
  13209. {
  13210. const size_t state_size = file.size - file.tell();
  13211. std::vector<uint8_t> state_data(state_size);
  13212. file.read_raw(state_data.data(), state_size);
  13213. const size_t nread = llama_state_seq_set_data(ctx, state_data.data(), dest_seq_id);
  13214. if (!nread) {
  13215. LLAMA_LOG_ERROR("%s: failed to restore sequence state\n", __func__);
  13216. return 0;
  13217. }
  13218. GGML_ASSERT(nread <= state_size);
  13219. GGML_ASSERT(nread + sizeof(uint32_t) * 3 + sizeof(llama_token) * *n_token_count_out == file.tell());
  13220. }
  13221. return file.tell();
  13222. }
  13223. 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) {
  13224. try {
  13225. return llama_state_seq_save_file_internal(ctx, filepath, seq_id, tokens, n_token_count);
  13226. } catch (const std::exception & err) {
  13227. LLAMA_LOG_ERROR("error saving sequence state file: %s\n", err.what());
  13228. return 0;
  13229. }
  13230. }
  13231. 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) {
  13232. try {
  13233. return llama_state_seq_load_file_internal(ctx, filepath, dest_seq_id, tokens_out, n_token_capacity, n_token_count_out);
  13234. } catch (const std::exception & err) {
  13235. LLAMA_LOG_ERROR("error loading sequence state file: %s\n", err.what());
  13236. return 0;
  13237. }
  13238. }
  13239. void llama_set_n_threads(struct llama_context * ctx, uint32_t n_threads, uint32_t n_threads_batch) {
  13240. ctx->cparams.n_threads = n_threads;
  13241. ctx->cparams.n_threads_batch = n_threads_batch;
  13242. }
  13243. void llama_set_abort_callback(struct llama_context * ctx, bool (*abort_callback)(void * data), void * abort_callback_data) {
  13244. ctx->abort_callback = abort_callback;
  13245. ctx->abort_callback_data = abort_callback_data;
  13246. }
  13247. void llama_set_causal_attn(struct llama_context * ctx, bool causal_attn) {
  13248. ctx->cparams.causal_attn = causal_attn;
  13249. }
  13250. struct llama_batch llama_batch_get_one(
  13251. llama_token * tokens,
  13252. int32_t n_tokens,
  13253. llama_pos pos_0,
  13254. llama_seq_id seq_id) {
  13255. return {
  13256. /*n_tokens =*/ n_tokens,
  13257. /*tokens =*/ tokens,
  13258. /*embd =*/ nullptr,
  13259. /*pos =*/ nullptr,
  13260. /*n_seq_id =*/ nullptr,
  13261. /*seq_id =*/ nullptr,
  13262. /*logits =*/ nullptr,
  13263. /*all_pos_0 =*/ pos_0,
  13264. /*all_pos_1 =*/ 1,
  13265. /*all_seq_id =*/ seq_id,
  13266. };
  13267. }
  13268. struct llama_batch llama_batch_init(int32_t n_tokens_alloc, int32_t embd, int32_t n_seq_max) {
  13269. llama_batch batch = { 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, 0, 0, 0, };
  13270. if (embd) {
  13271. batch.embd = (float *) malloc(sizeof(float) * n_tokens_alloc * embd);
  13272. } else {
  13273. batch.token = (llama_token *) malloc(sizeof(llama_token) * n_tokens_alloc);
  13274. }
  13275. batch.pos = (llama_pos *) malloc(sizeof(llama_pos) * n_tokens_alloc);
  13276. batch.n_seq_id = (int32_t *) malloc(sizeof(int32_t) * n_tokens_alloc);
  13277. batch.seq_id = (llama_seq_id **) malloc(sizeof(llama_seq_id *) * (n_tokens_alloc + 1));
  13278. for (int i = 0; i < n_tokens_alloc; ++i) {
  13279. batch.seq_id[i] = (llama_seq_id *) malloc(sizeof(llama_seq_id) * n_seq_max);
  13280. }
  13281. batch.seq_id[n_tokens_alloc] = nullptr;
  13282. batch.logits = (int8_t *) malloc(sizeof(int8_t) * n_tokens_alloc);
  13283. return batch;
  13284. }
  13285. void llama_batch_free(struct llama_batch batch) {
  13286. if (batch.token) free(batch.token);
  13287. if (batch.embd) free(batch.embd);
  13288. if (batch.pos) free(batch.pos);
  13289. if (batch.n_seq_id) free(batch.n_seq_id);
  13290. if (batch.seq_id) {
  13291. for (int i = 0; batch.seq_id[i] != nullptr; ++i) {
  13292. free(batch.seq_id[i]);
  13293. }
  13294. free(batch.seq_id);
  13295. }
  13296. if (batch.logits) free(batch.logits);
  13297. }
  13298. int32_t llama_decode(
  13299. struct llama_context * ctx,
  13300. struct llama_batch batch) {
  13301. const int ret = llama_decode_internal(*ctx, batch);
  13302. if (ret < 0) {
  13303. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  13304. }
  13305. return ret;
  13306. }
  13307. void llama_synchronize(struct llama_context * ctx) {
  13308. ggml_backend_sched_synchronize(ctx->sched);
  13309. // FIXME: if multiple single tokens are evaluated without a synchronization,
  13310. // the stats will be added to the prompt evaluation stats
  13311. // this should only happen when using batch size 1 to evaluate a batch
  13312. // add the evaluation to the stats
  13313. if (ctx->n_queued_tokens == 1) {
  13314. ctx->t_eval_us += ggml_time_us() - ctx->t_compute_start_us;
  13315. ctx->n_eval++;
  13316. } else if (ctx->n_queued_tokens > 1) {
  13317. ctx->t_p_eval_us += ggml_time_us() - ctx->t_compute_start_us;
  13318. ctx->n_p_eval += ctx->n_queued_tokens;
  13319. }
  13320. // get a more accurate load time, upon first eval
  13321. if (ctx->n_queued_tokens > 0 && !ctx->has_evaluated_once) {
  13322. ctx->t_load_us = ggml_time_us() - ctx->t_start_us;
  13323. ctx->has_evaluated_once = true;
  13324. }
  13325. ctx->n_queued_tokens = 0;
  13326. ctx->t_compute_start_us = 0;
  13327. }
  13328. float * llama_get_logits(struct llama_context * ctx) {
  13329. llama_synchronize(ctx);
  13330. return ctx->logits;
  13331. }
  13332. float * llama_get_logits_ith(struct llama_context * ctx, int32_t i) {
  13333. int32_t j = -1;
  13334. llama_synchronize(ctx);
  13335. try {
  13336. if (ctx->logits == nullptr) {
  13337. throw std::runtime_error("no logits");
  13338. }
  13339. if (i < 0) {
  13340. j = ctx->n_outputs + i;
  13341. if (j < 0) {
  13342. throw std::runtime_error(format("negative index out of range [0, %d)", ctx->n_outputs));
  13343. }
  13344. } else if ((size_t) i >= ctx->output_ids.size()) {
  13345. throw std::runtime_error(format("out of range [0, %lu)", ctx->output_ids.size()));
  13346. } else {
  13347. j = ctx->output_ids[i];
  13348. }
  13349. if (j < 0) {
  13350. throw std::runtime_error(format("batch.logits[%d] != true", i));
  13351. }
  13352. if (j >= ctx->n_outputs) {
  13353. // This should not happen
  13354. throw std::runtime_error(format("corrupt output buffer (j=%d, n_outputs=%d)", j, ctx->n_outputs));
  13355. }
  13356. return ctx->logits + j*ctx->model.hparams.n_vocab;
  13357. } catch (const std::exception & err) {
  13358. LLAMA_LOG_ERROR("%s: invalid logits id %d, reason: %s\n", __func__, i, err.what());
  13359. #ifndef NDEBUG
  13360. GGML_ASSERT(false);
  13361. #endif
  13362. return nullptr;
  13363. }
  13364. }
  13365. float * llama_get_embeddings(struct llama_context * ctx) {
  13366. llama_synchronize(ctx);
  13367. return ctx->embd;
  13368. }
  13369. float * llama_get_embeddings_ith(struct llama_context * ctx, int32_t i) {
  13370. int32_t j = -1;
  13371. llama_synchronize(ctx);
  13372. try {
  13373. if (ctx->embd == nullptr) {
  13374. throw std::runtime_error("no embeddings");
  13375. }
  13376. if (i < 0) {
  13377. j = ctx->n_outputs + i;
  13378. if (j < 0) {
  13379. throw std::runtime_error(format("negative index out of range [0, %d)", ctx->n_outputs));
  13380. }
  13381. } else if ((size_t) i >= ctx->output_ids.size()) {
  13382. throw std::runtime_error(format("out of range [0, %lu)", ctx->output_ids.size()));
  13383. } else {
  13384. j = ctx->output_ids[i];
  13385. }
  13386. if (j < 0) {
  13387. throw std::runtime_error(format("batch.logits[%d] != true", i));
  13388. }
  13389. if (j >= ctx->n_outputs) {
  13390. // This should not happen
  13391. throw std::runtime_error(format("corrupt output buffer (j=%d, n_outputs=%d)", j, ctx->n_outputs));
  13392. }
  13393. return ctx->embd + j*ctx->model.hparams.n_embd;
  13394. } catch (const std::exception & err) {
  13395. LLAMA_LOG_ERROR("%s: invalid embeddings id %d, reason: %s\n", __func__, i, err.what());
  13396. #ifndef NDEBUG
  13397. GGML_ASSERT(false);
  13398. #endif
  13399. return nullptr;
  13400. }
  13401. }
  13402. float * llama_get_embeddings_seq(struct llama_context * ctx, llama_seq_id seq_id) {
  13403. llama_synchronize(ctx);
  13404. auto it = ctx->embd_seq.find(seq_id);
  13405. if (it == ctx->embd_seq.end()) {
  13406. return nullptr;
  13407. }
  13408. return it->second.data();
  13409. }
  13410. const char * llama_token_get_text(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].text.c_str();
  13413. }
  13414. float llama_token_get_score(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].score;
  13417. }
  13418. llama_token_type llama_token_get_type(const struct llama_model * model, llama_token token) {
  13419. GGML_ASSERT(model->vocab.type != LLAMA_VOCAB_TYPE_NONE);
  13420. return model->vocab.id_to_token[token].type;
  13421. }
  13422. llama_token llama_token_bos(const struct llama_model * model) {
  13423. return model->vocab.special_bos_id;
  13424. }
  13425. llama_token llama_token_eos(const struct llama_model * model) {
  13426. return model->vocab.special_eos_id;
  13427. }
  13428. llama_token llama_token_cls(const struct llama_model * model) {
  13429. return model->vocab.special_cls_id;
  13430. }
  13431. llama_token llama_token_sep(const struct llama_model * model) {
  13432. return model->vocab.special_sep_id;
  13433. }
  13434. llama_token llama_token_nl(const struct llama_model * model) {
  13435. return model->vocab.linefeed_id;
  13436. }
  13437. int32_t llama_add_bos_token(const struct llama_model * model) {
  13438. return model->vocab.special_add_bos;
  13439. }
  13440. int32_t llama_add_eos_token(const struct llama_model * model) {
  13441. return model->vocab.special_add_eos;
  13442. }
  13443. llama_token llama_token_prefix(const struct llama_model * model) {
  13444. return model->vocab.special_prefix_id;
  13445. }
  13446. llama_token llama_token_middle(const struct llama_model * model) {
  13447. return model->vocab.special_middle_id;
  13448. }
  13449. llama_token llama_token_suffix(const struct llama_model * model) {
  13450. return model->vocab.special_suffix_id;
  13451. }
  13452. llama_token llama_token_eot(const struct llama_model * model) {
  13453. return model->vocab.special_eot_id;
  13454. }
  13455. int32_t llama_tokenize(
  13456. const struct llama_model * model,
  13457. const char * text,
  13458. int32_t text_len,
  13459. llama_token * tokens,
  13460. int32_t n_tokens_max,
  13461. bool add_special,
  13462. bool parse_special) {
  13463. auto res = llama_tokenize_internal(model->vocab, std::string(text, text_len), add_special, parse_special);
  13464. if (n_tokens_max < (int) res.size()) {
  13465. // LLAMA_LOG_ERROR("%s: too many tokens\n", __func__);
  13466. return -((int) res.size());
  13467. }
  13468. for (size_t i = 0; i < res.size(); i++) {
  13469. tokens[i] = res[i];
  13470. }
  13471. return res.size();
  13472. }
  13473. static std::string llama_decode_text(const std::string & text) {
  13474. std::string decoded_text;
  13475. auto unicode_sequences = unicode_cpts_from_utf8(text);
  13476. for (auto & unicode_sequence : unicode_sequences) {
  13477. decoded_text += unicode_utf8_to_byte(unicode_cpt_to_utf8(unicode_sequence));
  13478. }
  13479. return decoded_text;
  13480. }
  13481. // does not write null-terminator to buf
  13482. int32_t llama_token_to_piece(const struct llama_model * model, llama_token token, char * buf, int32_t length) {
  13483. if (0 <= token && token < llama_n_vocab(model)) {
  13484. switch (llama_vocab_get_type(model->vocab)) {
  13485. case LLAMA_VOCAB_TYPE_WPM:
  13486. case LLAMA_VOCAB_TYPE_SPM: {
  13487. // NOTE: we accept all unsupported token types,
  13488. // suppressing them like CONTROL tokens.
  13489. if (llama_is_normal_token(model->vocab, token)) {
  13490. std::string result = model->vocab.id_to_token[token].text;
  13491. llama_unescape_whitespace(result);
  13492. if (length < (int) result.length()) {
  13493. return -(int) result.length();
  13494. }
  13495. memcpy(buf, result.c_str(), result.length());
  13496. return result.length();
  13497. } else if (llama_is_user_defined_token(model->vocab, token)) {
  13498. std::string result = model->vocab.id_to_token[token].text;
  13499. if (length < (int) result.length()) {
  13500. return -(int) result.length();
  13501. }
  13502. memcpy(buf, result.c_str(), result.length());
  13503. return result.length();
  13504. } else if (llama_is_unknown_token(model->vocab, token)) { // NOLINT
  13505. if (length < 3) {
  13506. return -3;
  13507. }
  13508. memcpy(buf, "\xe2\x96\x85", 3);
  13509. return 3;
  13510. } else if (llama_is_control_token(model->vocab, token)) {
  13511. ;
  13512. } else if (llama_is_byte_token(model->vocab, token)) {
  13513. if (length < 1) {
  13514. return -1;
  13515. }
  13516. buf[0] = llama_token_to_byte(model->vocab, token);
  13517. return 1;
  13518. }
  13519. break;
  13520. }
  13521. case LLAMA_VOCAB_TYPE_BPE: {
  13522. // NOTE: we accept all unsupported token types,
  13523. // suppressing them like CONTROL tokens.
  13524. if (llama_is_normal_token(model->vocab, token)) {
  13525. std::string result = model->vocab.id_to_token[token].text;
  13526. result = llama_decode_text(result);
  13527. if (length < (int) result.length()) {
  13528. return -(int) result.length();
  13529. }
  13530. memcpy(buf, result.c_str(), result.length());
  13531. return result.length();
  13532. } else if (llama_is_user_defined_token(model->vocab, token)) {
  13533. std::string result = model->vocab.id_to_token[token].text;
  13534. if (length < (int) result.length()) {
  13535. return -(int) result.length();
  13536. }
  13537. memcpy(buf, result.c_str(), result.length());
  13538. return result.length();
  13539. } else if (llama_is_control_token(model->vocab, token)) {
  13540. ;
  13541. }
  13542. break;
  13543. }
  13544. default:
  13545. GGML_ASSERT(false);
  13546. }
  13547. }
  13548. return 0;
  13549. }
  13550. // trim whitespace from the beginning and end of a string
  13551. static std::string trim(const std::string & str) {
  13552. size_t start = 0;
  13553. size_t end = str.size();
  13554. while (start < end && isspace(str[start])) {
  13555. start += 1;
  13556. }
  13557. while (end > start && isspace(str[end - 1])) {
  13558. end -= 1;
  13559. }
  13560. return str.substr(start, end - start);
  13561. }
  13562. // Simple version of "llama_apply_chat_template" that only works with strings
  13563. // This function uses heuristic checks to determine commonly used template. It is not a jinja parser.
  13564. static int32_t llama_chat_apply_template_internal(
  13565. const std::string & tmpl,
  13566. const std::vector<const llama_chat_message *> & chat,
  13567. std::string & dest, bool add_ass) {
  13568. // Taken from the research: https://github.com/ggerganov/llama.cpp/issues/5527
  13569. std::stringstream ss;
  13570. if (tmpl == "chatml" || tmpl.find("<|im_start|>") != std::string::npos) {
  13571. // chatml template
  13572. for (auto message : chat) {
  13573. ss << "<|im_start|>" << message->role << "\n" << message->content << "<|im_end|>\n";
  13574. }
  13575. if (add_ass) {
  13576. ss << "<|im_start|>assistant\n";
  13577. }
  13578. } else if (tmpl == "llama2" || tmpl.find("[INST]") != std::string::npos) {
  13579. // llama2 template and its variants
  13580. // [variant] support system message
  13581. bool support_system_message = tmpl.find("<<SYS>>") != std::string::npos;
  13582. // [variant] space before + after response
  13583. bool space_around_response = tmpl.find("' ' + eos_token") != std::string::npos;
  13584. // [variant] add BOS inside history
  13585. bool add_bos_inside_history = tmpl.find("bos_token + '[INST]") != std::string::npos;
  13586. // [variant] trim spaces from the input message
  13587. bool strip_message = tmpl.find("content.strip()") != std::string::npos;
  13588. // construct the prompt
  13589. bool is_inside_turn = true; // skip BOS at the beginning
  13590. ss << "[INST] ";
  13591. for (auto message : chat) {
  13592. std::string content = strip_message ? trim(message->content) : message->content;
  13593. std::string role(message->role);
  13594. if (!is_inside_turn) {
  13595. is_inside_turn = true;
  13596. ss << (add_bos_inside_history ? "<s>[INST] " : "[INST] ");
  13597. }
  13598. if (role == "system") {
  13599. if (support_system_message) {
  13600. ss << "<<SYS>>\n" << content << "\n<</SYS>>\n\n";
  13601. } else {
  13602. // if the model does not support system message, we still include it in the first message, but without <<SYS>>
  13603. ss << content << "\n";
  13604. }
  13605. } else if (role == "user") {
  13606. ss << content << " [/INST]";
  13607. } else {
  13608. ss << (space_around_response ? " " : "") << content << (space_around_response ? " " : "") << "</s>";
  13609. is_inside_turn = false;
  13610. }
  13611. }
  13612. // llama2 templates seem to not care about "add_generation_prompt"
  13613. } else if (tmpl == "zephyr" || tmpl.find("<|user|>") != std::string::npos) {
  13614. // zephyr template
  13615. for (auto message : chat) {
  13616. ss << "<|" << message->role << "|>" << "\n" << message->content << "<|endoftext|>\n";
  13617. }
  13618. if (add_ass) {
  13619. ss << "<|assistant|>\n";
  13620. }
  13621. } else if (tmpl == "monarch" || tmpl.find("bos_token + message['role']") != std::string::npos) {
  13622. // mlabonne/AlphaMonarch-7B template (the <s> is included inside history)
  13623. for (auto message : chat) {
  13624. std::string bos = (message == chat.front()) ? "" : "<s>"; // skip BOS for first message
  13625. ss << bos << message->role << "\n" << message->content << "</s>\n";
  13626. }
  13627. if (add_ass) {
  13628. ss << "<s>assistant\n";
  13629. }
  13630. } else if (tmpl == "gemma" || tmpl.find("<start_of_turn>") != std::string::npos) {
  13631. // google/gemma-7b-it
  13632. std::string system_prompt = "";
  13633. for (auto message : chat) {
  13634. std::string role(message->role);
  13635. if (role == "system") {
  13636. // there is no system message for gemma, but we will merge it with user prompt, so nothing is broken
  13637. system_prompt = trim(message->content);
  13638. continue;
  13639. }
  13640. // in gemma, "assistant" is "model"
  13641. role = role == "assistant" ? "model" : message->role;
  13642. ss << "<start_of_turn>" << role << "\n";
  13643. if (!system_prompt.empty() && role != "model") {
  13644. ss << system_prompt << "\n\n";
  13645. system_prompt = "";
  13646. }
  13647. ss << trim(message->content) << "<end_of_turn>\n";
  13648. }
  13649. if (add_ass) {
  13650. ss << "<start_of_turn>model\n";
  13651. }
  13652. } else if (tmpl == "orion" || tmpl.find("'\\n\\nAssistant: ' + eos_token") != std::string::npos) {
  13653. // OrionStarAI/Orion-14B-Chat
  13654. std::string system_prompt = "";
  13655. for (auto message : chat) {
  13656. std::string role(message->role);
  13657. if (role == "system") {
  13658. // there is no system message support, we will merge it with user prompt
  13659. system_prompt = message->content;
  13660. continue;
  13661. } else if (role == "user") {
  13662. ss << "Human: ";
  13663. if (!system_prompt.empty()) {
  13664. ss << system_prompt << "\n\n";
  13665. system_prompt = "";
  13666. }
  13667. ss << message->content << "\n\nAssistant: </s>";
  13668. } else {
  13669. ss << message->content << "</s>";
  13670. }
  13671. }
  13672. } else if (tmpl == "openchat" || tmpl.find("GPT4 Correct ") != std::string::npos) {
  13673. // openchat/openchat-3.5-0106,
  13674. for (auto message : chat) {
  13675. std::string role(message->role);
  13676. if (role == "system") {
  13677. ss << message->content << "<|end_of_turn|>";
  13678. } else {
  13679. role[0] = toupper(role[0]);
  13680. ss << "GPT4 Correct " << role << ": " << message->content << "<|end_of_turn|>";
  13681. }
  13682. }
  13683. if (add_ass) {
  13684. ss << "GPT4 Correct Assistant:";
  13685. }
  13686. } else if (tmpl == "vicuna" || tmpl == "vicuna-orca" || (tmpl.find("USER: ") != std::string::npos && tmpl.find("ASSISTANT: ") != std::string::npos)) {
  13687. // eachadea/vicuna-13b-1.1 (and Orca variant)
  13688. for (auto message : chat) {
  13689. std::string role(message->role);
  13690. if (role == "system") {
  13691. // Orca-Vicuna variant uses a system prefix
  13692. if (tmpl == "vicuna-orca" || tmpl.find("SYSTEM: ") != std::string::npos) {
  13693. ss << "SYSTEM: " << message->content << "\n";
  13694. } else {
  13695. ss << message->content << "\n\n";
  13696. }
  13697. } else if (role == "user") {
  13698. ss << "USER: " << message->content << "\n";
  13699. } else if (role == "assistant") {
  13700. ss << "ASSISTANT: " << message->content << "</s>\n";
  13701. }
  13702. }
  13703. if (add_ass) {
  13704. ss << "ASSISTANT:";
  13705. }
  13706. } else if (tmpl == "deepseek" || (tmpl.find("### Instruction:") != std::string::npos && tmpl.find("<|EOT|>") != std::string::npos)) {
  13707. // deepseek-ai/deepseek-coder-33b-instruct
  13708. for (auto message : chat) {
  13709. std::string role(message->role);
  13710. if (role == "system") {
  13711. ss << message->content;
  13712. } else if (role == "user") {
  13713. ss << "### Instruction:\n" << message->content << "\n";
  13714. } else if (role == "assistant") {
  13715. ss << "### Response:\n" << message->content << "\n<|EOT|>\n";
  13716. }
  13717. }
  13718. if (add_ass) {
  13719. ss << "### Response:\n";
  13720. }
  13721. } else {
  13722. // template not supported
  13723. return -1;
  13724. }
  13725. dest = ss.str();
  13726. return dest.size();
  13727. }
  13728. LLAMA_API int32_t llama_chat_apply_template(
  13729. const struct llama_model * model,
  13730. const char * tmpl,
  13731. const struct llama_chat_message * chat,
  13732. size_t n_msg,
  13733. bool add_ass,
  13734. char * buf,
  13735. int32_t length) {
  13736. std::string curr_tmpl(tmpl == nullptr ? "" : tmpl);
  13737. if (tmpl == nullptr) {
  13738. GGML_ASSERT(model != nullptr);
  13739. // load template from model
  13740. std::vector<char> model_template(2048, 0); // longest known template is about 1200 bytes
  13741. std::string template_key = "tokenizer.chat_template";
  13742. int32_t res = llama_model_meta_val_str(model, template_key.c_str(), model_template.data(), model_template.size());
  13743. if (res < 0) {
  13744. // worst case: there is no information about template, we will use chatml by default
  13745. curr_tmpl = "chatml"; // see llama_chat_apply_template_internal
  13746. } else {
  13747. curr_tmpl = std::string(model_template.data(), model_template.size());
  13748. }
  13749. }
  13750. // format the chat to string
  13751. std::vector<const llama_chat_message *> chat_vec;
  13752. chat_vec.resize(n_msg);
  13753. for (size_t i = 0; i < n_msg; i++) {
  13754. chat_vec[i] = &chat[i];
  13755. }
  13756. std::string formatted_chat;
  13757. int32_t res = llama_chat_apply_template_internal(curr_tmpl, chat_vec, formatted_chat, add_ass);
  13758. if (res < 0) {
  13759. return res;
  13760. }
  13761. if (buf && length > 0) {
  13762. strncpy(buf, formatted_chat.c_str(), length);
  13763. }
  13764. return res;
  13765. }
  13766. LLAMA_API int llama_split_path(char * split_path, size_t maxlen, const char * path_prefix, int split_no, int split_count) {
  13767. static const char * const SPLIT_PATH_FORMAT = "%s-%05d-of-%05d.gguf";
  13768. if (snprintf(split_path, maxlen, SPLIT_PATH_FORMAT, path_prefix, split_no + 1, split_count)) {
  13769. return strlen(split_path);
  13770. }
  13771. return 0;
  13772. }
  13773. int llama_split_prefix(char * dest, size_t maxlen, const char * split_path, int split_no, int split_count) {
  13774. std::string str_split_path(split_path);
  13775. char postfix[32];
  13776. snprintf(postfix, 32, "-%05d-of-%05d.gguf", split_no + 1, split_count);
  13777. std::string str_postfix(postfix);
  13778. // check if dest ends with postfix
  13779. int size_prefix = str_split_path.size() - str_postfix.size();
  13780. if (size_prefix > 0 && str_split_path.find(str_postfix, size_prefix) != std::string::npos) {
  13781. snprintf(dest, std::min((size_t) size_prefix + 1, maxlen), "%s", split_path);
  13782. return size_prefix;
  13783. }
  13784. return 0;
  13785. }
  13786. struct llama_timings llama_get_timings(struct llama_context * ctx) {
  13787. struct llama_timings result = {
  13788. /*.t_start_ms =*/ 1e-3 * ctx->t_start_us,
  13789. /*.t_end_ms =*/ 1.00 * ggml_time_ms(),
  13790. /*.t_load_ms =*/ 1e-3 * ctx->t_load_us,
  13791. /*.t_sample_ms =*/ 1e-3 * ctx->t_sample_us,
  13792. /*.t_p_eval_ms =*/ 1e-3 * ctx->t_p_eval_us,
  13793. /*.t_eval_ms =*/ 1e-3 * ctx->t_eval_us,
  13794. /*.n_sample =*/ std::max(1, ctx->n_sample),
  13795. /*.n_p_eval =*/ std::max(1, ctx->n_p_eval),
  13796. /*.n_eval =*/ std::max(1, ctx->n_eval),
  13797. };
  13798. return result;
  13799. }
  13800. void llama_print_timings(struct llama_context * ctx) {
  13801. const llama_timings timings = llama_get_timings(ctx);
  13802. LLAMA_LOG_INFO("\n");
  13803. LLAMA_LOG_INFO("%s: load time = %10.2f ms\n", __func__, timings.t_load_ms);
  13804. LLAMA_LOG_INFO("%s: sample time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  13805. __func__, timings.t_sample_ms, timings.n_sample, timings.t_sample_ms / timings.n_sample, 1e3 / timings.t_sample_ms * timings.n_sample);
  13806. LLAMA_LOG_INFO("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  13807. __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);
  13808. LLAMA_LOG_INFO("%s: eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  13809. __func__, timings.t_eval_ms, timings.n_eval, timings.t_eval_ms / timings.n_eval, 1e3 / timings.t_eval_ms * timings.n_eval);
  13810. 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));
  13811. }
  13812. void llama_reset_timings(struct llama_context * ctx) {
  13813. ctx->t_start_us = ggml_time_us();
  13814. ctx->t_sample_us = ctx->n_sample = 0;
  13815. ctx->t_eval_us = ctx->n_eval = 0;
  13816. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  13817. }
  13818. const char * llama_print_system_info(void) {
  13819. static std::string s;
  13820. s = "";
  13821. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  13822. s += "AVX_VNNI = " + std::to_string(ggml_cpu_has_avx_vnni()) + " | ";
  13823. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  13824. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  13825. s += "AVX512_VBMI = " + std::to_string(ggml_cpu_has_avx512_vbmi()) + " | ";
  13826. s += "AVX512_VNNI = " + std::to_string(ggml_cpu_has_avx512_vnni()) + " | ";
  13827. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  13828. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  13829. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  13830. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  13831. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  13832. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  13833. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  13834. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  13835. s += "SSSE3 = " + std::to_string(ggml_cpu_has_ssse3()) + " | ";
  13836. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  13837. s += "MATMUL_INT8 = " + std::to_string(ggml_cpu_has_matmul_int8()) + " | ";
  13838. return s.c_str();
  13839. }
  13840. void llama_dump_timing_info_yaml(FILE * stream, const llama_context * ctx) {
  13841. fprintf(stream, "\n");
  13842. fprintf(stream, "###########\n");
  13843. fprintf(stream, "# Timings #\n");
  13844. fprintf(stream, "###########\n");
  13845. fprintf(stream, "\n");
  13846. fprintf(stream, "mst_eval: %.2f # ms / token during generation\n",
  13847. 1.0e-3 * ctx->t_eval_us / ctx->n_eval);
  13848. fprintf(stream, "mst_p_eval: %.2f # ms / token during prompt processing\n",
  13849. 1.0e-3 * ctx->t_p_eval_us / ctx->n_p_eval);
  13850. fprintf(stream, "mst_sample: %.2f # ms / token during sampling\n",
  13851. 1.0e-3 * ctx->t_sample_us / ctx->n_sample);
  13852. fprintf(stream, "n_eval: %d # number of tokens generated (excluding the first one)\n", ctx->n_eval);
  13853. fprintf(stream, "n_p_eval: %d # number of tokens processed in batches at the beginning\n", ctx->n_p_eval);
  13854. fprintf(stream, "n_sample: %d # number of sampled tokens\n", ctx->n_sample);
  13855. fprintf(stream, "t_eval_us: %" PRId64 " # total microseconds spent generating tokens\n", ctx->t_eval_us);
  13856. fprintf(stream, "t_load_us: %" PRId64 " # total microseconds spent loading the model\n", ctx->t_load_us);
  13857. fprintf(stream, "t_p_eval_us: %" PRId64 " # total microseconds spent prompt processing\n", ctx->t_p_eval_us);
  13858. fprintf(stream, "t_sample_us: %" PRId64 " # total microseconds spent sampling\n", ctx->t_sample_us);
  13859. fprintf(stream, "ts_eval: %.2f # tokens / second during generation\n",
  13860. 1.0e6 * ctx->n_eval / ctx->t_eval_us);
  13861. fprintf(stream, "ts_p_eval: %.2f # tokens / second during prompt processing\n",
  13862. 1.0e6 * ctx->n_p_eval / ctx->t_p_eval_us);
  13863. fprintf(stream, "ts_sample: %.2f # tokens / second during sampling\n",
  13864. 1.0e6 * ctx->n_sample / ctx->t_sample_us);
  13865. }
  13866. // For internal test use
  13867. const std::vector<std::pair<std::string, struct ggml_tensor *>> & llama_internal_get_tensor_map(
  13868. struct llama_context * ctx
  13869. ) {
  13870. return ctx->model.tensors_by_name;
  13871. }
  13872. void llama_log_set(ggml_log_callback log_callback, void * user_data) {
  13873. g_state.log_callback = log_callback ? log_callback : llama_log_callback_default;
  13874. g_state.log_callback_user_data = user_data;
  13875. #ifdef GGML_USE_METAL
  13876. ggml_backend_metal_log_set_callback(g_state.log_callback, g_state.log_callback_user_data);
  13877. #endif
  13878. }
  13879. static void llama_log_internal_v(ggml_log_level level, const char * format, va_list args) {
  13880. va_list args_copy;
  13881. va_copy(args_copy, args);
  13882. char buffer[128];
  13883. int len = vsnprintf(buffer, 128, format, args);
  13884. if (len < 128) {
  13885. g_state.log_callback(level, buffer, g_state.log_callback_user_data);
  13886. } else {
  13887. char* buffer2 = new char[len+1];
  13888. vsnprintf(buffer2, len+1, format, args_copy);
  13889. buffer2[len] = 0;
  13890. g_state.log_callback(level, buffer2, g_state.log_callback_user_data);
  13891. delete[] buffer2;
  13892. }
  13893. va_end(args_copy);
  13894. }
  13895. static void llama_log_internal(ggml_log_level level, const char * format, ...) {
  13896. va_list args;
  13897. va_start(args, format);
  13898. llama_log_internal_v(level, format, args);
  13899. va_end(args);
  13900. }
  13901. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data) {
  13902. (void) level;
  13903. (void) user_data;
  13904. fputs(text, stderr);
  13905. fflush(stderr);
  13906. }