llama.cpp 654 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617
  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_ADD_BOS,
  289. LLM_KV_TOKENIZER_ADD_EOS,
  290. LLM_KV_TOKENIZER_ADD_PREFIX,
  291. LLM_KV_TOKENIZER_HF_JSON,
  292. LLM_KV_TOKENIZER_RWKV,
  293. };
  294. static const std::map<llm_kv, const char *> LLM_KV_NAMES = {
  295. { LLM_KV_GENERAL_ARCHITECTURE, "general.architecture" },
  296. { LLM_KV_GENERAL_QUANTIZATION_VERSION, "general.quantization_version" },
  297. { LLM_KV_GENERAL_ALIGNMENT, "general.alignment" },
  298. { LLM_KV_GENERAL_NAME, "general.name" },
  299. { LLM_KV_GENERAL_AUTHOR, "general.author" },
  300. { LLM_KV_GENERAL_VERSION, "general.version" },
  301. { LLM_KV_GENERAL_URL, "general.url" },
  302. { LLM_KV_GENERAL_DESCRIPTION, "general.description" },
  303. { LLM_KV_GENERAL_LICENSE, "general.license" },
  304. { LLM_KV_GENERAL_SOURCE_URL, "general.source.url" },
  305. { LLM_KV_GENERAL_SOURCE_HF_REPO, "general.source.huggingface.repository" },
  306. { LLM_KV_VOCAB_SIZE, "%s.vocab_size" },
  307. { LLM_KV_CONTEXT_LENGTH, "%s.context_length" },
  308. { LLM_KV_EMBEDDING_LENGTH, "%s.embedding_length" },
  309. { LLM_KV_BLOCK_COUNT, "%s.block_count" },
  310. { LLM_KV_FEED_FORWARD_LENGTH, "%s.feed_forward_length" },
  311. { LLM_KV_USE_PARALLEL_RESIDUAL, "%s.use_parallel_residual" },
  312. { LLM_KV_TENSOR_DATA_LAYOUT, "%s.tensor_data_layout" },
  313. { LLM_KV_EXPERT_COUNT, "%s.expert_count" },
  314. { LLM_KV_EXPERT_USED_COUNT, "%s.expert_used_count" },
  315. { LLM_KV_POOLING_TYPE , "%s.pooling_type" },
  316. { LLM_KV_LOGIT_SCALE, "%s.logit_scale" },
  317. { LLM_KV_ATTENTION_HEAD_COUNT, "%s.attention.head_count" },
  318. { LLM_KV_ATTENTION_HEAD_COUNT_KV, "%s.attention.head_count_kv" },
  319. { LLM_KV_ATTENTION_MAX_ALIBI_BIAS, "%s.attention.max_alibi_bias" },
  320. { LLM_KV_ATTENTION_CLAMP_KQV, "%s.attention.clamp_kqv" },
  321. { LLM_KV_ATTENTION_KEY_LENGTH, "%s.attention.key_length" },
  322. { LLM_KV_ATTENTION_VALUE_LENGTH, "%s.attention.value_length" },
  323. { LLM_KV_ATTENTION_LAYERNORM_EPS, "%s.attention.layer_norm_epsilon" },
  324. { LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, "%s.attention.layer_norm_rms_epsilon" },
  325. { LLM_KV_ATTENTION_CAUSAL, "%s.attention.causal" },
  326. { LLM_KV_ROPE_DIMENSION_COUNT, "%s.rope.dimension_count" },
  327. { LLM_KV_ROPE_FREQ_BASE, "%s.rope.freq_base" },
  328. { LLM_KV_ROPE_SCALE_LINEAR, "%s.rope.scale_linear" },
  329. { LLM_KV_ROPE_SCALING_TYPE, "%s.rope.scaling.type" },
  330. { LLM_KV_ROPE_SCALING_FACTOR, "%s.rope.scaling.factor" },
  331. { LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, "%s.rope.scaling.original_context_length" },
  332. { LLM_KV_ROPE_SCALING_FINETUNED, "%s.rope.scaling.finetuned" },
  333. { LLM_KV_SPLIT_NO, "split.no" },
  334. { LLM_KV_SPLIT_COUNT, "split.count" },
  335. { LLM_KV_SPLIT_TENSORS_COUNT, "split.tensors.count" },
  336. { LLM_KV_SSM_CONV_KERNEL, "%s.ssm.conv_kernel" },
  337. { LLM_KV_SSM_INNER_SIZE, "%s.ssm.inner_size" },
  338. { LLM_KV_SSM_STATE_SIZE, "%s.ssm.state_size" },
  339. { LLM_KV_SSM_TIME_STEP_RANK, "%s.ssm.time_step_rank" },
  340. { LLM_KV_TOKENIZER_MODEL, "tokenizer.ggml.model" },
  341. { LLM_KV_TOKENIZER_LIST, "tokenizer.ggml.tokens" },
  342. { LLM_KV_TOKENIZER_TOKEN_TYPE, "tokenizer.ggml.token_type" },
  343. { LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, "tokenizer.ggml.token_type_count" },
  344. { LLM_KV_TOKENIZER_SCORES, "tokenizer.ggml.scores" },
  345. { LLM_KV_TOKENIZER_MERGES, "tokenizer.ggml.merges" },
  346. { LLM_KV_TOKENIZER_BOS_ID, "tokenizer.ggml.bos_token_id" },
  347. { LLM_KV_TOKENIZER_EOS_ID, "tokenizer.ggml.eos_token_id" },
  348. { LLM_KV_TOKENIZER_UNK_ID, "tokenizer.ggml.unknown_token_id" },
  349. { LLM_KV_TOKENIZER_SEP_ID, "tokenizer.ggml.seperator_token_id" },
  350. { LLM_KV_TOKENIZER_PAD_ID, "tokenizer.ggml.padding_token_id" },
  351. { LLM_KV_TOKENIZER_ADD_BOS, "tokenizer.ggml.add_bos_token" },
  352. { LLM_KV_TOKENIZER_ADD_EOS, "tokenizer.ggml.add_eos_token" },
  353. { LLM_KV_TOKENIZER_ADD_PREFIX, "tokenizer.ggml.add_space_prefix" },
  354. { LLM_KV_TOKENIZER_HF_JSON, "tokenizer.huggingface.json" },
  355. { LLM_KV_TOKENIZER_RWKV, "tokenizer.rwkv.world" },
  356. };
  357. struct LLM_KV {
  358. LLM_KV(llm_arch arch) : arch(arch) {}
  359. llm_arch arch;
  360. std::string operator()(llm_kv kv) const {
  361. return ::format(LLM_KV_NAMES.at(kv), LLM_ARCH_NAMES.at(arch));
  362. }
  363. };
  364. enum llm_tensor {
  365. LLM_TENSOR_TOKEN_EMBD,
  366. LLM_TENSOR_TOKEN_EMBD_NORM,
  367. LLM_TENSOR_TOKEN_TYPES,
  368. LLM_TENSOR_POS_EMBD,
  369. LLM_TENSOR_OUTPUT,
  370. LLM_TENSOR_OUTPUT_NORM,
  371. LLM_TENSOR_ROPE_FREQS,
  372. LLM_TENSOR_ATTN_Q,
  373. LLM_TENSOR_ATTN_K,
  374. LLM_TENSOR_ATTN_V,
  375. LLM_TENSOR_ATTN_QKV,
  376. LLM_TENSOR_ATTN_OUT,
  377. LLM_TENSOR_ATTN_NORM,
  378. LLM_TENSOR_ATTN_NORM_2,
  379. LLM_TENSOR_ATTN_OUT_NORM,
  380. LLM_TENSOR_ATTN_ROT_EMBD,
  381. LLM_TENSOR_FFN_GATE_INP,
  382. LLM_TENSOR_FFN_NORM,
  383. LLM_TENSOR_FFN_GATE,
  384. LLM_TENSOR_FFN_DOWN,
  385. LLM_TENSOR_FFN_UP,
  386. LLM_TENSOR_FFN_ACT,
  387. LLM_TENSOR_FFN_DOWN_EXP, // split experts for backward compatibility
  388. LLM_TENSOR_FFN_GATE_EXP,
  389. LLM_TENSOR_FFN_UP_EXP,
  390. LLM_TENSOR_FFN_DOWN_EXPS, // merged experts
  391. LLM_TENSOR_FFN_GATE_EXPS,
  392. LLM_TENSOR_FFN_UP_EXPS,
  393. LLM_TENSOR_ATTN_Q_NORM,
  394. LLM_TENSOR_ATTN_K_NORM,
  395. LLM_TENSOR_LAYER_OUT_NORM,
  396. LLM_TENSOR_SSM_IN,
  397. LLM_TENSOR_SSM_CONV1D,
  398. LLM_TENSOR_SSM_X,
  399. LLM_TENSOR_SSM_DT,
  400. LLM_TENSOR_SSM_A,
  401. LLM_TENSOR_SSM_D,
  402. LLM_TENSOR_SSM_OUT,
  403. };
  404. static const std::map<llm_arch, std::map<llm_tensor, std::string>> LLM_TENSOR_NAMES = {
  405. {
  406. LLM_ARCH_LLAMA,
  407. {
  408. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  409. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  410. { LLM_TENSOR_OUTPUT, "output" },
  411. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  412. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  413. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  414. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  415. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  416. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  417. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  418. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  419. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  420. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  421. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  422. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  423. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  424. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  425. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  426. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  427. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  428. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  429. },
  430. },
  431. {
  432. LLM_ARCH_BAICHUAN,
  433. {
  434. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  435. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  436. { LLM_TENSOR_OUTPUT, "output" },
  437. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  438. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  439. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  440. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  441. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  442. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  443. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  444. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  445. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  446. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  447. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  448. },
  449. },
  450. {
  451. LLM_ARCH_FALCON,
  452. {
  453. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  454. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  455. { LLM_TENSOR_OUTPUT, "output" },
  456. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  457. { LLM_TENSOR_ATTN_NORM_2, "blk.%d.attn_norm_2" },
  458. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  459. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  460. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  461. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  462. },
  463. },
  464. {
  465. LLM_ARCH_GROK,
  466. {
  467. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  468. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  469. { LLM_TENSOR_OUTPUT, "output" },
  470. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  471. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  472. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  473. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  474. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  475. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  476. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  477. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  478. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  479. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  480. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  481. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  482. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  483. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  484. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  485. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  486. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  487. },
  488. },
  489. {
  490. LLM_ARCH_GPT2,
  491. {
  492. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  493. { LLM_TENSOR_POS_EMBD, "position_embd" },
  494. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  495. { LLM_TENSOR_OUTPUT, "output" },
  496. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  497. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  498. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  499. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  500. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  501. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  502. },
  503. },
  504. {
  505. LLM_ARCH_GPTJ,
  506. {
  507. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  508. },
  509. },
  510. {
  511. LLM_ARCH_GPTNEOX,
  512. {
  513. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  514. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  515. { LLM_TENSOR_OUTPUT, "output" },
  516. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  517. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  518. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  519. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  520. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  521. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  522. },
  523. },
  524. {
  525. LLM_ARCH_PERSIMMON,
  526. {
  527. { LLM_TENSOR_TOKEN_EMBD, "token_embd"},
  528. { LLM_TENSOR_OUTPUT_NORM, "output_norm"},
  529. { LLM_TENSOR_OUTPUT, "output"},
  530. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm"},
  531. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv"},
  532. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output"},
  533. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm"},
  534. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm"},
  535. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm"},
  536. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down"},
  537. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up"},
  538. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd"},
  539. },
  540. },
  541. {
  542. LLM_ARCH_MPT,
  543. {
  544. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  545. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  546. { LLM_TENSOR_OUTPUT, "output"},
  547. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  548. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  549. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  550. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  551. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  552. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  553. { LLM_TENSOR_FFN_ACT, "blk.%d.ffn.act" },
  554. { LLM_TENSOR_POS_EMBD, "position_embd" },
  555. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm"},
  556. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm"},
  557. },
  558. },
  559. {
  560. LLM_ARCH_STARCODER,
  561. {
  562. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  563. { LLM_TENSOR_POS_EMBD, "position_embd" },
  564. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  565. { LLM_TENSOR_OUTPUT, "output" },
  566. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  567. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  568. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  569. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  570. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  571. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  572. },
  573. },
  574. {
  575. LLM_ARCH_REFACT,
  576. {
  577. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  578. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  579. { LLM_TENSOR_OUTPUT, "output" },
  580. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  581. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  582. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  583. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  584. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  585. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  586. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  587. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  588. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  589. },
  590. },
  591. {
  592. LLM_ARCH_BERT,
  593. {
  594. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  595. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  596. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  597. { LLM_TENSOR_POS_EMBD, "position_embd" },
  598. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  599. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  600. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  601. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  602. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  603. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  604. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  605. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  606. },
  607. },
  608. {
  609. LLM_ARCH_NOMIC_BERT,
  610. {
  611. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  612. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  613. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  614. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  615. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  616. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  617. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  618. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  619. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  620. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  621. },
  622. },
  623. {
  624. LLM_ARCH_BLOOM,
  625. {
  626. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  627. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  628. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  629. { LLM_TENSOR_OUTPUT, "output" },
  630. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  631. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  632. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  633. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  634. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  635. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  636. },
  637. },
  638. {
  639. LLM_ARCH_STABLELM,
  640. {
  641. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  642. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  643. { LLM_TENSOR_OUTPUT, "output" },
  644. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  645. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  646. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  647. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  648. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  649. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  650. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  651. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  652. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  653. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  654. },
  655. },
  656. {
  657. LLM_ARCH_QWEN,
  658. {
  659. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  660. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  661. { LLM_TENSOR_OUTPUT, "output" },
  662. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  663. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  664. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  665. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  666. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  667. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  668. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  669. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  670. },
  671. },
  672. {
  673. LLM_ARCH_QWEN2,
  674. {
  675. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  676. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  677. { LLM_TENSOR_OUTPUT, "output" },
  678. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  679. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  680. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  681. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  682. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  683. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  684. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  685. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  686. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  687. },
  688. },
  689. {
  690. LLM_ARCH_PHI2,
  691. {
  692. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  693. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  694. { LLM_TENSOR_OUTPUT, "output" },
  695. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  696. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  697. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  698. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  699. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  700. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  701. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  702. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  703. },
  704. },
  705. {
  706. LLM_ARCH_PLAMO,
  707. {
  708. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  709. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  710. { LLM_TENSOR_OUTPUT, "output" },
  711. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  712. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  713. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  714. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  715. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  716. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  717. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  718. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  719. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  720. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  721. },
  722. },
  723. {
  724. LLM_ARCH_CODESHELL,
  725. {
  726. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  727. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  728. { LLM_TENSOR_OUTPUT, "output" },
  729. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  730. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  731. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  732. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  733. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  734. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  735. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  736. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  737. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  738. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  739. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  740. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  741. },
  742. },
  743. {
  744. LLM_ARCH_ORION,
  745. {
  746. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  747. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  748. { LLM_TENSOR_OUTPUT, "output" },
  749. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  750. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  751. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  752. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  753. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  754. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  755. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  756. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  757. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  758. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  759. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  760. },
  761. },
  762. {
  763. LLM_ARCH_INTERNLM2,
  764. {
  765. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  766. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  767. { LLM_TENSOR_OUTPUT, "output" },
  768. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  769. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  770. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  771. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  772. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  773. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  774. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  775. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  776. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  777. },
  778. },
  779. {
  780. LLM_ARCH_MINICPM,
  781. {
  782. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  783. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  784. { LLM_TENSOR_OUTPUT, "output" },
  785. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  786. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  787. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  788. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  789. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  790. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  791. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  792. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  793. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  794. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  795. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  796. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  797. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  798. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  799. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  800. },
  801. },
  802. {
  803. LLM_ARCH_GEMMA,
  804. {
  805. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  806. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  807. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  808. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  809. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  810. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  811. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  812. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  813. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  814. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  815. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  816. },
  817. },
  818. {
  819. LLM_ARCH_STARCODER2,
  820. {
  821. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  822. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  823. { LLM_TENSOR_OUTPUT, "output" },
  824. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  825. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  826. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  827. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  828. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  829. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  830. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  831. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  832. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  833. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  834. },
  835. },
  836. {
  837. LLM_ARCH_MAMBA,
  838. {
  839. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  840. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  841. { LLM_TENSOR_OUTPUT, "output" },
  842. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  843. { LLM_TENSOR_SSM_IN, "blk.%d.ssm_in" },
  844. { LLM_TENSOR_SSM_CONV1D, "blk.%d.ssm_conv1d" },
  845. { LLM_TENSOR_SSM_X, "blk.%d.ssm_x" },
  846. { LLM_TENSOR_SSM_DT, "blk.%d.ssm_dt" },
  847. { LLM_TENSOR_SSM_A, "blk.%d.ssm_a" },
  848. { LLM_TENSOR_SSM_D, "blk.%d.ssm_d" },
  849. { LLM_TENSOR_SSM_OUT, "blk.%d.ssm_out" },
  850. },
  851. },
  852. {
  853. LLM_ARCH_XVERSE,
  854. {
  855. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  856. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  857. { LLM_TENSOR_OUTPUT, "output" },
  858. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  859. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  860. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  861. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  862. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  863. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  864. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  865. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  866. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  867. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  868. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  869. },
  870. },
  871. {
  872. LLM_ARCH_COMMAND_R,
  873. {
  874. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  875. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  876. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  877. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  878. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  879. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  880. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  881. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  882. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  883. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  884. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm" },
  885. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
  886. },
  887. },
  888. {
  889. LLM_ARCH_UNKNOWN,
  890. {
  891. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  892. },
  893. },
  894. };
  895. static llm_arch llm_arch_from_string(const std::string & name) {
  896. for (const auto & kv : LLM_ARCH_NAMES) { // NOLINT
  897. if (kv.second == name) {
  898. return kv.first;
  899. }
  900. }
  901. return LLM_ARCH_UNKNOWN;
  902. }
  903. // helper to handle gguf constants
  904. // usage:
  905. //
  906. // const auto tn = LLM_TN(LLM_ARCH_LLAMA);
  907. //
  908. // std::string name = tn(LLM_TENSOR_OUTPUT); -> "output"
  909. // std::string name = tn(LLM_TENSOR_TOKEN_EMBD, "bias"); -> "token_embd.bias"
  910. // std::string name = tn(LLM_TENSOR_ATTN_NORM, "weight", 3); -> "blk.3.attn_norm.weight"
  911. //
  912. struct LLM_TN {
  913. LLM_TN(llm_arch arch) : arch(arch) {}
  914. llm_arch arch;
  915. std::string operator()(llm_tensor tensor) const {
  916. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  917. return "__missing__";
  918. }
  919. return LLM_TENSOR_NAMES.at(arch).at(tensor);
  920. }
  921. std::string operator()(llm_tensor tensor, const std::string & suffix) const {
  922. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  923. return "__missing__";
  924. }
  925. return LLM_TENSOR_NAMES.at(arch).at(tensor) + "." + suffix;
  926. }
  927. std::string operator()(llm_tensor tensor, int bid) const {
  928. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  929. return "__missing__";
  930. }
  931. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid);
  932. }
  933. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid) const {
  934. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  935. return "__missing__";
  936. }
  937. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid) + "." + suffix;
  938. }
  939. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid, int xid) const {
  940. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  941. return "__missing__";
  942. }
  943. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid, xid) + "." + suffix;
  944. }
  945. };
  946. //
  947. // gguf helpers
  948. //
  949. static const std::map<llama_rope_scaling_type, const char *> LLAMA_ROPE_SCALING_TYPES = {
  950. { LLAMA_ROPE_SCALING_TYPE_NONE, "none" },
  951. { LLAMA_ROPE_SCALING_TYPE_LINEAR, "linear" },
  952. { LLAMA_ROPE_SCALING_TYPE_YARN, "yarn" },
  953. };
  954. static llama_rope_scaling_type llama_rope_scaling_type_from_string(const std::string & name) {
  955. for (const auto & kv : LLAMA_ROPE_SCALING_TYPES) {
  956. if (kv.second == name) {
  957. return (llama_rope_scaling_type) kv.first;
  958. }
  959. }
  960. return LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED;
  961. }
  962. static std::string gguf_data_to_str(enum gguf_type type, const void * data, int i) {
  963. switch (type) {
  964. case GGUF_TYPE_UINT8: return std::to_string(((const uint8_t *)data)[i]);
  965. case GGUF_TYPE_INT8: return std::to_string(((const int8_t *)data)[i]);
  966. case GGUF_TYPE_UINT16: return std::to_string(((const uint16_t *)data)[i]);
  967. case GGUF_TYPE_INT16: return std::to_string(((const int16_t *)data)[i]);
  968. case GGUF_TYPE_UINT32: return std::to_string(((const uint32_t *)data)[i]);
  969. case GGUF_TYPE_INT32: return std::to_string(((const int32_t *)data)[i]);
  970. case GGUF_TYPE_UINT64: return std::to_string(((const uint64_t *)data)[i]);
  971. case GGUF_TYPE_INT64: return std::to_string(((const int64_t *)data)[i]);
  972. case GGUF_TYPE_FLOAT32: return std::to_string(((const float *)data)[i]);
  973. case GGUF_TYPE_FLOAT64: return std::to_string(((const double *)data)[i]);
  974. case GGUF_TYPE_BOOL: return ((const bool *)data)[i] ? "true" : "false";
  975. default: return format("unknown type %d", type);
  976. }
  977. }
  978. static std::string gguf_kv_to_str(const struct gguf_context * ctx_gguf, int i) {
  979. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  980. switch (type) {
  981. case GGUF_TYPE_STRING:
  982. return gguf_get_val_str(ctx_gguf, i);
  983. case GGUF_TYPE_ARRAY:
  984. {
  985. const enum gguf_type arr_type = gguf_get_arr_type(ctx_gguf, i);
  986. int arr_n = gguf_get_arr_n(ctx_gguf, i);
  987. const void * data = gguf_get_arr_data(ctx_gguf, i);
  988. std::stringstream ss;
  989. ss << "[";
  990. for (int j = 0; j < arr_n; j++) {
  991. if (arr_type == GGUF_TYPE_STRING) {
  992. std::string val = gguf_get_arr_str(ctx_gguf, i, j);
  993. // escape quotes
  994. replace_all(val, "\\", "\\\\");
  995. replace_all(val, "\"", "\\\"");
  996. ss << '"' << val << '"';
  997. } else if (arr_type == GGUF_TYPE_ARRAY) {
  998. ss << "???";
  999. } else {
  1000. ss << gguf_data_to_str(arr_type, data, j);
  1001. }
  1002. if (j < arr_n - 1) {
  1003. ss << ", ";
  1004. }
  1005. }
  1006. ss << "]";
  1007. return ss.str();
  1008. }
  1009. default:
  1010. return gguf_data_to_str(type, gguf_get_val_data(ctx_gguf, i), 0);
  1011. }
  1012. }
  1013. //
  1014. // llama helpers
  1015. //
  1016. #if defined(_WIN32)
  1017. static std::string llama_format_win_err(DWORD err) {
  1018. LPSTR buf;
  1019. size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  1020. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, NULL);
  1021. if (!size) {
  1022. return "FormatMessageA failed";
  1023. }
  1024. std::string ret(buf, size);
  1025. LocalFree(buf);
  1026. return ret;
  1027. }
  1028. #endif
  1029. template <typename T>
  1030. struct no_init {
  1031. T value;
  1032. no_init() { /* do nothing */ }
  1033. };
  1034. struct llama_file {
  1035. // use FILE * so we don't have to re-open the file to mmap
  1036. FILE * fp;
  1037. size_t size;
  1038. llama_file(const char * fname, const char * mode) {
  1039. fp = ggml_fopen(fname, mode);
  1040. if (fp == NULL) {
  1041. throw std::runtime_error(format("failed to open %s: %s", fname, strerror(errno)));
  1042. }
  1043. seek(0, SEEK_END);
  1044. size = tell();
  1045. seek(0, SEEK_SET);
  1046. }
  1047. size_t tell() const {
  1048. #ifdef _WIN32
  1049. __int64 ret = _ftelli64(fp);
  1050. #else
  1051. long ret = std::ftell(fp);
  1052. #endif
  1053. GGML_ASSERT(ret != -1); // this really shouldn't fail
  1054. return (size_t) ret;
  1055. }
  1056. void seek(size_t offset, int whence) const {
  1057. #ifdef _WIN32
  1058. int ret = _fseeki64(fp, (__int64) offset, whence);
  1059. #else
  1060. int ret = std::fseek(fp, (long) offset, whence);
  1061. #endif
  1062. GGML_ASSERT(ret == 0); // same
  1063. }
  1064. void read_raw(void * ptr, size_t len) const {
  1065. if (len == 0) {
  1066. return;
  1067. }
  1068. errno = 0;
  1069. std::size_t ret = std::fread(ptr, len, 1, fp);
  1070. if (ferror(fp)) {
  1071. throw std::runtime_error(format("read error: %s", strerror(errno)));
  1072. }
  1073. if (ret != 1) {
  1074. throw std::runtime_error("unexpectedly reached end of file");
  1075. }
  1076. }
  1077. uint32_t read_u32() const {
  1078. uint32_t ret;
  1079. read_raw(&ret, sizeof(ret));
  1080. return ret;
  1081. }
  1082. void write_raw(const void * ptr, size_t len) const {
  1083. if (len == 0) {
  1084. return;
  1085. }
  1086. errno = 0;
  1087. size_t ret = std::fwrite(ptr, len, 1, fp);
  1088. if (ret != 1) {
  1089. throw std::runtime_error(format("write error: %s", strerror(errno)));
  1090. }
  1091. }
  1092. void write_u32(std::uint32_t val) const {
  1093. write_raw(&val, sizeof(val));
  1094. }
  1095. ~llama_file() {
  1096. if (fp) {
  1097. std::fclose(fp);
  1098. }
  1099. }
  1100. };
  1101. using llama_files = std::vector<std::unique_ptr<llama_file>>;
  1102. struct llama_mmap {
  1103. void * addr;
  1104. size_t size;
  1105. llama_mmap(const llama_mmap &) = delete;
  1106. #ifdef _POSIX_MAPPED_FILES
  1107. static constexpr bool SUPPORTED = true;
  1108. // list of mapped fragments (first_offset, last_offset)
  1109. std::vector<std::pair<size_t, size_t>> mapped_fragments;
  1110. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1 /* -1 = max value */, bool numa = false) {
  1111. size = file->size;
  1112. int fd = fileno(file->fp);
  1113. int flags = MAP_SHARED;
  1114. // prefetch/readahead impairs performance on NUMA systems
  1115. if (numa) { prefetch = 0; }
  1116. #ifdef __linux__
  1117. // advise the kernel to read the file sequentially (increases readahead)
  1118. if (posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL)) {
  1119. LLAMA_LOG_WARN("warning: posix_fadvise(.., POSIX_FADV_SEQUENTIAL) failed: %s\n",
  1120. strerror(errno));
  1121. }
  1122. if (prefetch) { flags |= MAP_POPULATE; }
  1123. #endif
  1124. addr = mmap(NULL, file->size, PROT_READ, flags, fd, 0);
  1125. if (addr == MAP_FAILED) { // NOLINT
  1126. throw std::runtime_error(format("mmap failed: %s", strerror(errno)));
  1127. }
  1128. if (prefetch > 0) {
  1129. // advise the kernel to preload the mapped memory
  1130. if (posix_madvise(addr, std::min(file->size, prefetch), POSIX_MADV_WILLNEED)) {
  1131. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_WILLNEED) failed: %s\n",
  1132. strerror(errno));
  1133. }
  1134. }
  1135. if (numa) {
  1136. // advise the kernel not to use readahead
  1137. // (because the next page might not belong on the same node)
  1138. if (posix_madvise(addr, file->size, POSIX_MADV_RANDOM)) {
  1139. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_RANDOM) failed: %s\n",
  1140. strerror(errno));
  1141. }
  1142. }
  1143. // initialize list of mapped_fragments
  1144. mapped_fragments.emplace_back(0, file->size);
  1145. }
  1146. static void align_range(size_t * first, size_t * last, size_t page_size) {
  1147. // align first to the next page
  1148. size_t offset_in_page = *first & (page_size - 1);
  1149. size_t offset_to_page = offset_in_page == 0 ? 0 : page_size - offset_in_page;
  1150. *first += offset_to_page;
  1151. // align last to the previous page
  1152. *last = *last & ~(page_size - 1);
  1153. if (*last <= *first) {
  1154. *last = *first;
  1155. }
  1156. }
  1157. // partially unmap the file in the range [first, last)
  1158. void unmap_fragment(size_t first, size_t last) {
  1159. // note: this function must not be called multiple times with overlapping ranges
  1160. // otherwise, there is a risk of invalidating addresses that have been repurposed for other mappings
  1161. int page_size = sysconf(_SC_PAGESIZE);
  1162. align_range(&first, &last, page_size);
  1163. size_t len = last - first;
  1164. if (len == 0) {
  1165. return;
  1166. }
  1167. GGML_ASSERT(first % page_size == 0);
  1168. GGML_ASSERT(last % page_size == 0);
  1169. GGML_ASSERT(last > first);
  1170. void * next_page_start = (uint8_t *) addr + first;
  1171. // unmap the range
  1172. if (munmap(next_page_start, len)) {
  1173. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  1174. }
  1175. // update the list of mapped fragments to avoid unmapping the same range again in the destructor
  1176. std::vector<std::pair<size_t, size_t>> new_mapped_fragments;
  1177. for (const auto & frag : mapped_fragments) {
  1178. if (frag.first < first && frag.second > last) {
  1179. // the range is in the middle of the fragment, split it
  1180. new_mapped_fragments.emplace_back(frag.first, first);
  1181. new_mapped_fragments.emplace_back(last, frag.second);
  1182. } else if (frag.first < first && frag.second > first) {
  1183. // the range starts in the middle of the fragment
  1184. new_mapped_fragments.emplace_back(frag.first, first);
  1185. } else if (frag.first < last && frag.second > last) {
  1186. // the range ends in the middle of the fragment
  1187. new_mapped_fragments.emplace_back(last, frag.second);
  1188. } else if (frag.first >= first && frag.second <= last) {
  1189. // the range covers the entire fragment
  1190. } else {
  1191. // the range is outside the fragment
  1192. new_mapped_fragments.push_back(frag);
  1193. }
  1194. }
  1195. mapped_fragments = std::move(new_mapped_fragments);
  1196. }
  1197. ~llama_mmap() {
  1198. for (const auto & frag : mapped_fragments) {
  1199. if (munmap((char *) addr + frag.first, frag.second - frag.first)) {
  1200. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  1201. }
  1202. }
  1203. }
  1204. #elif defined(_WIN32)
  1205. static constexpr bool SUPPORTED = true;
  1206. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1, bool numa = false) {
  1207. GGML_UNUSED(numa);
  1208. size = file->size;
  1209. HANDLE hFile = (HANDLE) _get_osfhandle(_fileno(file->fp));
  1210. HANDLE hMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
  1211. if (hMapping == NULL) {
  1212. DWORD error = GetLastError();
  1213. throw std::runtime_error(format("CreateFileMappingA failed: %s", llama_format_win_err(error).c_str()));
  1214. }
  1215. addr = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
  1216. DWORD error = GetLastError();
  1217. CloseHandle(hMapping);
  1218. if (addr == NULL) {
  1219. throw std::runtime_error(format("MapViewOfFile failed: %s", llama_format_win_err(error).c_str()));
  1220. }
  1221. if (prefetch > 0) {
  1222. #if _WIN32_WINNT >= 0x602
  1223. // PrefetchVirtualMemory is only present on Windows 8 and above, so we dynamically load it
  1224. BOOL (WINAPI *pPrefetchVirtualMemory) (HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG);
  1225. HMODULE hKernel32 = GetModuleHandleW(L"kernel32.dll");
  1226. // may fail on pre-Windows 8 systems
  1227. pPrefetchVirtualMemory = reinterpret_cast<decltype(pPrefetchVirtualMemory)> (GetProcAddress(hKernel32, "PrefetchVirtualMemory"));
  1228. if (pPrefetchVirtualMemory) {
  1229. // advise the kernel to preload the mapped memory
  1230. WIN32_MEMORY_RANGE_ENTRY range;
  1231. range.VirtualAddress = addr;
  1232. range.NumberOfBytes = (SIZE_T) std::min(size, prefetch);
  1233. if (!pPrefetchVirtualMemory(GetCurrentProcess(), 1, &range, 0)) {
  1234. LLAMA_LOG_WARN("warning: PrefetchVirtualMemory failed: %s\n",
  1235. llama_format_win_err(GetLastError()).c_str());
  1236. }
  1237. }
  1238. #else
  1239. throw std::runtime_error("PrefetchVirtualMemory unavailable");
  1240. #endif
  1241. }
  1242. }
  1243. void unmap_fragment(size_t first, size_t last) {
  1244. // not supported
  1245. GGML_UNUSED(first);
  1246. GGML_UNUSED(last);
  1247. }
  1248. ~llama_mmap() {
  1249. if (!UnmapViewOfFile(addr)) {
  1250. LLAMA_LOG_WARN("warning: UnmapViewOfFile failed: %s\n",
  1251. llama_format_win_err(GetLastError()).c_str());
  1252. }
  1253. }
  1254. #else
  1255. static constexpr bool SUPPORTED = false;
  1256. llama_mmap(struct llama_file * file, size_t prefetch = -1, bool numa = false) {
  1257. GGML_UNUSED(file);
  1258. GGML_UNUSED(prefetch);
  1259. GGML_UNUSED(numa);
  1260. throw std::runtime_error("mmap not supported");
  1261. }
  1262. void unmap_fragment(size_t first, size_t last) {
  1263. GGML_UNUSED(first);
  1264. GGML_UNUSED(last);
  1265. throw std::runtime_error("mmap not supported");
  1266. }
  1267. #endif
  1268. };
  1269. using llama_mmaps = std::vector<std::unique_ptr<llama_mmap>>;
  1270. // Represents some region of memory being locked using mlock or VirtualLock;
  1271. // will automatically unlock on destruction.
  1272. struct llama_mlock {
  1273. void * addr = NULL;
  1274. size_t size = 0;
  1275. bool failed_already = false;
  1276. llama_mlock() {}
  1277. llama_mlock(const llama_mlock &) = delete;
  1278. ~llama_mlock() {
  1279. if (size) {
  1280. raw_unlock(addr, size);
  1281. }
  1282. }
  1283. void init(void * ptr) {
  1284. GGML_ASSERT(addr == NULL && size == 0); // NOLINT
  1285. addr = ptr;
  1286. }
  1287. void grow_to(size_t target_size) {
  1288. GGML_ASSERT(addr);
  1289. if (failed_already) {
  1290. return;
  1291. }
  1292. size_t granularity = lock_granularity();
  1293. target_size = (target_size + granularity - 1) & ~(granularity - 1);
  1294. if (target_size > size) {
  1295. if (raw_lock((uint8_t *) addr + size, target_size - size)) {
  1296. size = target_size;
  1297. } else {
  1298. failed_already = true;
  1299. }
  1300. }
  1301. }
  1302. #ifdef _POSIX_MEMLOCK_RANGE
  1303. static constexpr bool SUPPORTED = true;
  1304. static size_t lock_granularity() {
  1305. return (size_t) sysconf(_SC_PAGESIZE);
  1306. }
  1307. #ifdef __APPLE__
  1308. #define MLOCK_SUGGESTION \
  1309. "Try increasing the sysctl values 'vm.user_wire_limit' and 'vm.global_user_wire_limit' and/or " \
  1310. "decreasing 'vm.global_no_user_wire_amount'. Also try increasing RLIMIT_MEMLOCK (ulimit -l).\n"
  1311. #else
  1312. #define MLOCK_SUGGESTION \
  1313. "Try increasing RLIMIT_MEMLOCK ('ulimit -l' as root).\n"
  1314. #endif
  1315. bool raw_lock(const void * addr, size_t size) const {
  1316. if (!mlock(addr, size)) {
  1317. return true;
  1318. }
  1319. char* errmsg = std::strerror(errno);
  1320. bool suggest = (errno == ENOMEM);
  1321. // Check if the resource limit is fine after all
  1322. struct rlimit lock_limit;
  1323. if (suggest && getrlimit(RLIMIT_MEMLOCK, &lock_limit)) {
  1324. suggest = false;
  1325. }
  1326. if (suggest && (lock_limit.rlim_max > lock_limit.rlim_cur + size)) {
  1327. suggest = false;
  1328. }
  1329. LLAMA_LOG_WARN("warning: failed to mlock %zu-byte buffer (after previously locking %zu bytes): %s\n%s",
  1330. size, this->size, errmsg, suggest ? MLOCK_SUGGESTION : "");
  1331. return false;
  1332. }
  1333. #undef MLOCK_SUGGESTION
  1334. static void raw_unlock(void * addr, size_t size) {
  1335. if (munlock(addr, size)) {
  1336. LLAMA_LOG_WARN("warning: failed to munlock buffer: %s\n", std::strerror(errno));
  1337. }
  1338. }
  1339. #elif defined(_WIN32)
  1340. static constexpr bool SUPPORTED = true;
  1341. static size_t lock_granularity() {
  1342. SYSTEM_INFO si;
  1343. GetSystemInfo(&si);
  1344. return (size_t) si.dwPageSize;
  1345. }
  1346. bool raw_lock(void * ptr, size_t len) const {
  1347. for (int tries = 1; ; tries++) {
  1348. if (VirtualLock(ptr, len)) {
  1349. return true;
  1350. }
  1351. if (tries == 2) {
  1352. LLAMA_LOG_WARN("warning: failed to VirtualLock %zu-byte buffer (after previously locking %zu bytes): %s\n",
  1353. len, size, llama_format_win_err(GetLastError()).c_str());
  1354. return false;
  1355. }
  1356. // It failed but this was only the first try; increase the working
  1357. // set size and try again.
  1358. SIZE_T min_ws_size, max_ws_size;
  1359. if (!GetProcessWorkingSetSize(GetCurrentProcess(), &min_ws_size, &max_ws_size)) {
  1360. LLAMA_LOG_WARN("warning: GetProcessWorkingSetSize failed: %s\n",
  1361. llama_format_win_err(GetLastError()).c_str());
  1362. return false;
  1363. }
  1364. // Per MSDN: "The maximum number of pages that a process can lock
  1365. // is equal to the number of pages in its minimum working set minus
  1366. // a small overhead."
  1367. // Hopefully a megabyte is enough overhead:
  1368. size_t increment = len + 1048576;
  1369. // The minimum must be <= the maximum, so we need to increase both:
  1370. min_ws_size += increment;
  1371. max_ws_size += increment;
  1372. if (!SetProcessWorkingSetSize(GetCurrentProcess(), min_ws_size, max_ws_size)) {
  1373. LLAMA_LOG_WARN("warning: SetProcessWorkingSetSize failed: %s\n",
  1374. llama_format_win_err(GetLastError()).c_str());
  1375. return false;
  1376. }
  1377. }
  1378. }
  1379. static void raw_unlock(void * ptr, size_t len) {
  1380. if (!VirtualUnlock(ptr, len)) {
  1381. LLAMA_LOG_WARN("warning: failed to VirtualUnlock buffer: %s\n",
  1382. llama_format_win_err(GetLastError()).c_str());
  1383. }
  1384. }
  1385. #else
  1386. static constexpr bool SUPPORTED = false;
  1387. static size_t lock_granularity() {
  1388. return (size_t) 65536;
  1389. }
  1390. bool raw_lock(const void * addr, size_t len) const {
  1391. LLAMA_LOG_WARN("warning: mlock not supported on this system\n");
  1392. return false;
  1393. }
  1394. static void raw_unlock(const void * addr, size_t len) {}
  1395. #endif
  1396. };
  1397. using llama_mlocks = std::vector<std::unique_ptr<llama_mlock>>;
  1398. static std::string llama_token_to_piece(const struct llama_context * ctx, llama_token token) {
  1399. std::vector<char> result(8, 0);
  1400. const int n_tokens = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1401. if (n_tokens < 0) {
  1402. result.resize(-n_tokens);
  1403. int check = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1404. GGML_ASSERT(check == -n_tokens);
  1405. }
  1406. else {
  1407. result.resize(n_tokens);
  1408. }
  1409. return std::string(result.data(), result.size());
  1410. }
  1411. static ggml_backend_buffer_type_t llama_default_buffer_type_cpu(bool host_buffer) {
  1412. ggml_backend_buffer_type_t buft = nullptr;
  1413. #if defined(GGML_USE_CUDA)
  1414. // host buffers should only be used when data is expected to be copied to/from the GPU
  1415. if (host_buffer) {
  1416. buft = ggml_backend_cuda_host_buffer_type();
  1417. }
  1418. #elif defined(GGML_USE_SYCL)
  1419. if (host_buffer) {
  1420. buft = ggml_backend_sycl_host_buffer_type();
  1421. }
  1422. #elif defined(GGML_USE_CPU_HBM)
  1423. buft = ggml_backend_cpu_hbm_buffer_type();
  1424. #elif defined(GGML_USE_VULKAN)
  1425. if (host_buffer) {
  1426. buft = ggml_backend_vk_host_buffer_type();
  1427. }
  1428. #endif
  1429. if (buft == nullptr) {
  1430. buft = ggml_backend_cpu_buffer_type();
  1431. }
  1432. return buft;
  1433. GGML_UNUSED(host_buffer);
  1434. }
  1435. static ggml_backend_buffer_type_t llama_default_buffer_type_offload(int gpu) {
  1436. ggml_backend_buffer_type_t buft = nullptr;
  1437. #ifdef GGML_USE_METAL
  1438. buft = ggml_backend_metal_buffer_type();
  1439. #elif defined(GGML_USE_CUDA)
  1440. buft = ggml_backend_cuda_buffer_type(gpu);
  1441. #elif defined(GGML_USE_VULKAN)
  1442. buft = ggml_backend_vk_buffer_type(gpu);
  1443. #elif defined(GGML_USE_SYCL)
  1444. buft = ggml_backend_sycl_buffer_type(gpu);
  1445. #elif defined(GGML_USE_CLBLAST)
  1446. buft = ggml_backend_opencl_buffer_type();
  1447. #elif defined(GGML_USE_KOMPUTE)
  1448. buft = ggml_backend_kompute_buffer_type(gpu);
  1449. if (buft == nullptr) {
  1450. LLAMA_LOG_WARN("%s: cannot use GPU %d, check `vulkaninfo --summary`\n", __func__, gpu);
  1451. }
  1452. #endif
  1453. if (buft == nullptr) {
  1454. buft = llama_default_buffer_type_cpu(true);
  1455. }
  1456. return buft;
  1457. GGML_UNUSED(gpu);
  1458. }
  1459. static ggml_backend_buffer_type_t llama_default_buffer_type_split(int fallback_gpu, const float * tensor_split) {
  1460. ggml_backend_buffer_type_t buft = nullptr;
  1461. #ifdef GGML_USE_CUDA
  1462. if (ggml_backend_cuda_get_device_count() > 1) {
  1463. buft = ggml_backend_cuda_split_buffer_type(tensor_split);
  1464. }
  1465. #endif
  1466. #ifdef GGML_USE_SYCL
  1467. if (ggml_backend_sycl_get_device_count() > 1) {
  1468. buft = ggml_backend_sycl_split_buffer_type(tensor_split);
  1469. }
  1470. #endif
  1471. if (buft == nullptr) {
  1472. buft = llama_default_buffer_type_offload(fallback_gpu);
  1473. }
  1474. return buft;
  1475. GGML_UNUSED(tensor_split);
  1476. }
  1477. static size_t llama_get_device_count() {
  1478. #if defined(GGML_USE_CUDA)
  1479. return ggml_backend_cuda_get_device_count();
  1480. #elif defined(GGML_USE_SYCL)
  1481. return ggml_backend_sycl_get_device_count();
  1482. #elif defined(GGML_USE_VULKAN)
  1483. return ggml_backend_vk_get_device_count();
  1484. #else
  1485. return 1;
  1486. #endif
  1487. }
  1488. static size_t llama_get_device_memory(int device) {
  1489. #if defined(GGML_USE_CUDA)
  1490. size_t total;
  1491. size_t free;
  1492. ggml_backend_cuda_get_device_memory(device, &total, &free);
  1493. return free;
  1494. #elif defined(GGML_USE_SYCL)
  1495. size_t total;
  1496. size_t free;
  1497. ggml_backend_sycl_get_device_memory(device, &total, &free);
  1498. return free;
  1499. #elif defined(GGML_USE_VULKAN)
  1500. size_t total;
  1501. size_t free;
  1502. ggml_backend_vk_get_device_memory(device, &total, &free);
  1503. return free;
  1504. #else
  1505. return 1;
  1506. GGML_UNUSED(device);
  1507. #endif
  1508. }
  1509. //
  1510. // globals
  1511. //
  1512. struct llama_state {
  1513. llama_state() {
  1514. #ifdef GGML_USE_METAL
  1515. ggml_backend_metal_log_set_callback(log_callback, log_callback_user_data);
  1516. #endif
  1517. }
  1518. // We save the log callback globally
  1519. ggml_log_callback log_callback = llama_log_callback_default;
  1520. void * log_callback_user_data = nullptr;
  1521. };
  1522. static llama_state g_state;
  1523. // available llama models
  1524. enum e_model {
  1525. MODEL_UNKNOWN,
  1526. MODEL_17M,
  1527. MODEL_22M,
  1528. MODEL_33M,
  1529. MODEL_109M,
  1530. MODEL_137M,
  1531. MODEL_335M,
  1532. MODEL_0_5B,
  1533. MODEL_1B,
  1534. MODEL_2B,
  1535. MODEL_3B,
  1536. MODEL_4B,
  1537. MODEL_7B,
  1538. MODEL_8B,
  1539. MODEL_13B,
  1540. MODEL_14B,
  1541. MODEL_15B,
  1542. MODEL_20B,
  1543. MODEL_30B,
  1544. MODEL_34B,
  1545. MODEL_35B,
  1546. MODEL_40B,
  1547. MODEL_65B,
  1548. MODEL_70B,
  1549. MODEL_314B,
  1550. MODEL_SMALL,
  1551. MODEL_MEDIUM,
  1552. MODEL_LARGE,
  1553. MODEL_XL,
  1554. };
  1555. static const size_t kiB = 1024;
  1556. static const size_t MiB = 1024*kiB;
  1557. static const size_t GiB = 1024*MiB;
  1558. struct llama_hparams {
  1559. bool vocab_only;
  1560. bool rope_finetuned;
  1561. uint32_t n_vocab;
  1562. uint32_t n_ctx_train; // context size the model was trained on
  1563. uint32_t n_embd;
  1564. uint32_t n_head;
  1565. uint32_t n_head_kv;
  1566. uint32_t n_layer;
  1567. uint32_t n_rot;
  1568. 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
  1569. uint32_t n_embd_head_v; // dimension of values (d_v) aka n_embd_head
  1570. uint32_t n_ff;
  1571. uint32_t n_expert = 0;
  1572. uint32_t n_expert_used = 0;
  1573. uint32_t n_vocab_type = 0; // for BERT-style token types
  1574. float f_norm_eps;
  1575. float f_norm_rms_eps;
  1576. float rope_freq_base_train;
  1577. float rope_freq_scale_train;
  1578. uint32_t n_yarn_orig_ctx;
  1579. // for State Space Models
  1580. uint32_t ssm_d_conv = 0;
  1581. uint32_t ssm_d_inner = 0;
  1582. uint32_t ssm_d_state = 0;
  1583. uint32_t ssm_dt_rank = 0;
  1584. float f_clamp_kqv = 0.0f;
  1585. float f_max_alibi_bias = 0.0f;
  1586. float f_logit_scale = 0.0f;
  1587. bool causal_attn = true;
  1588. bool need_kq_pos = false;
  1589. enum llama_pooling_type pooling_type = LLAMA_POOLING_TYPE_NONE;
  1590. enum llama_rope_type rope_type = LLAMA_ROPE_TYPE_NONE;
  1591. enum llama_rope_scaling_type rope_scaling_type_train = LLAMA_ROPE_SCALING_TYPE_NONE;
  1592. bool operator!=(const llama_hparams & other) const {
  1593. if (this->vocab_only != other.vocab_only) return true;
  1594. if (this->n_vocab != other.n_vocab) return true;
  1595. if (this->n_ctx_train != other.n_ctx_train) return true;
  1596. if (this->n_embd != other.n_embd) return true;
  1597. if (this->n_head != other.n_head) return true;
  1598. if (this->n_head_kv != other.n_head_kv) return true;
  1599. if (this->n_layer != other.n_layer) return true;
  1600. if (this->n_rot != other.n_rot) return true;
  1601. if (this->n_embd_head_k != other.n_embd_head_k) return true;
  1602. if (this->n_embd_head_v != other.n_embd_head_v) return true;
  1603. if (this->n_ff != other.n_ff) return true;
  1604. if (this->n_expert != other.n_expert) return true;
  1605. if (this->n_expert_used != other.n_expert_used) return true;
  1606. if (this->rope_finetuned != other.rope_finetuned) return true;
  1607. if (this->n_yarn_orig_ctx != other.n_yarn_orig_ctx) return true;
  1608. if (this->ssm_d_conv != other.ssm_d_conv) return true;
  1609. if (this->ssm_d_inner != other.ssm_d_inner) return true;
  1610. if (this->ssm_d_state != other.ssm_d_state) return true;
  1611. if (this->ssm_dt_rank != other.ssm_dt_rank) return true;
  1612. const float EPSILON = 1e-9f;
  1613. if (!is_float_close(this->f_norm_eps, other.f_norm_eps, EPSILON)) return true;
  1614. if (!is_float_close(this->f_norm_rms_eps, other.f_norm_rms_eps, EPSILON)) return true;
  1615. if (!is_float_close(this->rope_freq_base_train, other.rope_freq_base_train, EPSILON)) return true;
  1616. if (!is_float_close(this->rope_freq_scale_train, other.rope_freq_scale_train, EPSILON)) return true;
  1617. return false;
  1618. }
  1619. uint32_t n_gqa() const {
  1620. if (n_head_kv == 0) {
  1621. return 0;
  1622. }
  1623. return n_head/n_head_kv;
  1624. }
  1625. uint32_t n_embd_k_gqa() const { // dimension of key embeddings across all k-v heads
  1626. return n_embd_head_k * n_head_kv;
  1627. }
  1628. uint32_t n_embd_v_gqa() const { // dimension of value embeddings across all k-v heads
  1629. return n_embd_head_v * n_head_kv;
  1630. }
  1631. uint32_t n_embd_k_s() const { // dimension of the rolling state embeddings
  1632. // corresponds to Mamba's conv_states size
  1633. // TODO: maybe support other convolution strides than 1
  1634. // NOTE: since the first column of the conv_state is shifted out each time, it's not actually needed
  1635. return (ssm_d_conv > 0 ? ssm_d_conv - 1 : 0) * ssm_d_inner;
  1636. }
  1637. uint32_t n_embd_v_s() const { // dimension of the recurrent state embeddings
  1638. // corresponds to Mamba's ssm_states size
  1639. return ssm_d_state * ssm_d_inner;
  1640. }
  1641. };
  1642. struct llama_cparams {
  1643. uint32_t n_ctx; // context size used during inference
  1644. uint32_t n_batch;
  1645. uint32_t n_ubatch;
  1646. uint32_t n_seq_max;
  1647. uint32_t n_threads; // number of threads to use for generation
  1648. uint32_t n_threads_batch; // number of threads to use for batch processing
  1649. float rope_freq_base;
  1650. float rope_freq_scale;
  1651. uint32_t n_yarn_orig_ctx;
  1652. // These hyperparameters are not exposed in GGUF, because all
  1653. // existing YaRN models use the same values for them.
  1654. float yarn_ext_factor;
  1655. float yarn_attn_factor;
  1656. float yarn_beta_fast;
  1657. float yarn_beta_slow;
  1658. float defrag_thold;
  1659. bool embeddings;
  1660. bool causal_attn;
  1661. bool offload_kqv;
  1662. enum llama_pooling_type pooling_type;
  1663. ggml_backend_sched_eval_callback cb_eval;
  1664. void * cb_eval_user_data;
  1665. };
  1666. struct llama_layer {
  1667. // normalization
  1668. struct ggml_tensor * attn_norm;
  1669. struct ggml_tensor * attn_norm_b;
  1670. struct ggml_tensor * attn_norm_2;
  1671. struct ggml_tensor * attn_norm_2_b;
  1672. struct ggml_tensor * attn_q_norm;
  1673. struct ggml_tensor * attn_q_norm_b;
  1674. struct ggml_tensor * attn_k_norm;
  1675. struct ggml_tensor * attn_k_norm_b;
  1676. struct ggml_tensor * attn_out_norm;
  1677. struct ggml_tensor * attn_out_norm_b;
  1678. // attention
  1679. struct ggml_tensor * wq;
  1680. struct ggml_tensor * wk;
  1681. struct ggml_tensor * wv;
  1682. struct ggml_tensor * wo;
  1683. struct ggml_tensor * wqkv;
  1684. // attention bias
  1685. struct ggml_tensor * bq;
  1686. struct ggml_tensor * bk;
  1687. struct ggml_tensor * bv;
  1688. struct ggml_tensor * bo;
  1689. struct ggml_tensor * bqkv;
  1690. // normalization
  1691. struct ggml_tensor * ffn_norm;
  1692. struct ggml_tensor * ffn_norm_b;
  1693. struct ggml_tensor * layer_out_norm;
  1694. struct ggml_tensor * layer_out_norm_b;
  1695. // ff
  1696. struct ggml_tensor * ffn_gate; // w1
  1697. struct ggml_tensor * ffn_down; // w2
  1698. struct ggml_tensor * ffn_up; // w3
  1699. // ff MoE
  1700. struct ggml_tensor * ffn_gate_inp;
  1701. struct ggml_tensor * ffn_gate_exps;
  1702. struct ggml_tensor * ffn_down_exps;
  1703. struct ggml_tensor * ffn_up_exps ;
  1704. // ff bias
  1705. struct ggml_tensor * ffn_down_b; // b2
  1706. struct ggml_tensor * ffn_up_b; // b3
  1707. struct ggml_tensor * ffn_act;
  1708. // mamba proj
  1709. struct ggml_tensor * ssm_in;
  1710. struct ggml_tensor * ssm_x;
  1711. struct ggml_tensor * ssm_dt;
  1712. struct ggml_tensor * ssm_out;
  1713. // mamba
  1714. struct ggml_tensor * ssm_conv1d;
  1715. struct ggml_tensor * ssm_a;
  1716. struct ggml_tensor * ssm_d;
  1717. // mamba bias
  1718. struct ggml_tensor * ssm_conv1d_b;
  1719. struct ggml_tensor * ssm_dt_b;
  1720. };
  1721. struct llama_kv_cell {
  1722. llama_pos pos = -1;
  1723. llama_pos delta = 0;
  1724. int32_t src = 0; // used by recurrent state models to copy states
  1725. std::set<llama_seq_id> seq_id;
  1726. bool has_seq_id(const llama_seq_id & id) const {
  1727. return seq_id.find(id) != seq_id.end();
  1728. }
  1729. bool is_empty() const {
  1730. return seq_id.empty();
  1731. }
  1732. bool is_same_seq(const llama_kv_cell & other) const {
  1733. return seq_id == other.seq_id;
  1734. }
  1735. };
  1736. // ring-buffer of cached KV data
  1737. struct llama_kv_cache {
  1738. bool has_shift = false;
  1739. bool do_defrag = false;
  1740. bool do_copy = false;
  1741. // with recurrent state models, a cell can hold the state for more than one past token
  1742. bool recurrent = false;
  1743. // Note: The value of head isn't only used to optimize searching
  1744. // for a free KV slot. llama_decode_internal also uses it, so it
  1745. // cannot be freely changed after a slot has been allocated.
  1746. uint32_t head = 0;
  1747. uint32_t size = 0;
  1748. uint32_t used = 0; // used cells (i.e. at least one seq_id)
  1749. // computed before each graph build
  1750. uint32_t n = 0;
  1751. ggml_type type_k = GGML_TYPE_F16;
  1752. ggml_type type_v = GGML_TYPE_F16;
  1753. std::vector<llama_kv_cell> cells;
  1754. std::vector<struct ggml_tensor *> k_l; // per layer
  1755. std::vector<struct ggml_tensor *> v_l;
  1756. std::vector<struct ggml_context *> ctxs;
  1757. std::vector<ggml_backend_buffer_t> bufs;
  1758. size_t total_size() const {
  1759. size_t size = 0;
  1760. for (ggml_backend_buffer_t buf : bufs) {
  1761. size += ggml_backend_buffer_get_size(buf);
  1762. }
  1763. return size;
  1764. }
  1765. ~llama_kv_cache() {
  1766. for (struct ggml_context * ctx : ctxs) {
  1767. ggml_free(ctx);
  1768. }
  1769. for (ggml_backend_buffer_t buf : bufs) {
  1770. ggml_backend_buffer_free(buf);
  1771. }
  1772. }
  1773. };
  1774. struct llama_control_vector {
  1775. std::vector<struct ggml_tensor *> tensors; // per layer
  1776. std::vector<struct ggml_context *> ctxs;
  1777. std::vector<ggml_backend_buffer_t> bufs;
  1778. int32_t layer_start = -1;
  1779. int32_t layer_end = -1;
  1780. ggml_tensor * tensor_for(int il) const {
  1781. if (il < 0 || il < layer_start || il > layer_end || (size_t) il >= tensors.size()) {
  1782. return nullptr;
  1783. }
  1784. return tensors[il];
  1785. }
  1786. ~llama_control_vector() {
  1787. for (struct ggml_context * ctx : ctxs) {
  1788. ggml_free(ctx);
  1789. }
  1790. for (ggml_backend_buffer_t buf : bufs) {
  1791. ggml_backend_buffer_free(buf);
  1792. }
  1793. }
  1794. };
  1795. struct llama_vocab {
  1796. using id = int32_t;
  1797. using token = std::string;
  1798. using ttype = llama_token_type;
  1799. struct token_data {
  1800. token text;
  1801. float score;
  1802. ttype type;
  1803. };
  1804. enum llama_vocab_type type = LLAMA_VOCAB_TYPE_SPM;
  1805. std::unordered_map<token, id> token_to_id;
  1806. std::vector<token_data> id_to_token;
  1807. std::unordered_map<token, id> special_tokens_cache;
  1808. std::map<std::pair<std::string, std::string>, int> bpe_ranks;
  1809. // default LLaMA special tokens
  1810. id special_bos_id = 1;
  1811. id special_eos_id = 2;
  1812. id special_unk_id = 0;
  1813. id special_sep_id = -1;
  1814. id special_pad_id = -1;
  1815. int special_add_bos = -1; // -1 unknown, 1 add, 0 don't add.
  1816. int special_add_eos = -1; // -1 unknown, 1 add, 0 don't add.
  1817. id linefeed_id = 13;
  1818. id special_prefix_id = 32007;
  1819. id special_middle_id = 32009;
  1820. id special_suffix_id = 32008;
  1821. id special_eot_id = 32010;
  1822. bool add_space_prefix = true;
  1823. int find_bpe_rank(const std::string & token_left, const std::string & token_right) const {
  1824. GGML_ASSERT(token_left.find(' ') == std::string::npos);
  1825. GGML_ASSERT(token_left.find('\n') == std::string::npos);
  1826. GGML_ASSERT(token_right.find(' ') == std::string::npos);
  1827. GGML_ASSERT(token_right.find('\n') == std::string::npos);
  1828. auto it = bpe_ranks.find(std::make_pair(token_left, token_right));
  1829. if (it == bpe_ranks.end()) {
  1830. return -1;
  1831. }
  1832. return it->second;
  1833. }
  1834. };
  1835. struct llama_model {
  1836. e_model type = MODEL_UNKNOWN;
  1837. llm_arch arch = LLM_ARCH_UNKNOWN;
  1838. llama_ftype ftype = LLAMA_FTYPE_ALL_F32;
  1839. std::string name = "n/a";
  1840. llama_hparams hparams = {};
  1841. llama_vocab vocab;
  1842. struct ggml_tensor * tok_embd;
  1843. struct ggml_tensor * type_embd;
  1844. struct ggml_tensor * pos_embd;
  1845. struct ggml_tensor * tok_norm;
  1846. struct ggml_tensor * tok_norm_b;
  1847. struct ggml_tensor * output_norm;
  1848. struct ggml_tensor * output_norm_b;
  1849. struct ggml_tensor * output;
  1850. struct ggml_tensor * output_b;
  1851. std::vector<llama_layer> layers;
  1852. llama_split_mode split_mode;
  1853. int main_gpu;
  1854. int n_gpu_layers;
  1855. // gguf metadata
  1856. std::unordered_map<std::string, std::string> gguf_kv;
  1857. // layer -> buffer type mapping
  1858. struct layer_buft {
  1859. layer_buft() : buft_matrix(nullptr), buft(nullptr) {}
  1860. layer_buft(ggml_backend_buffer_type_t matrix) : buft_matrix(matrix), buft(matrix) {}
  1861. layer_buft(ggml_backend_buffer_type_t matrix, ggml_backend_buffer_type_t other) : buft_matrix(matrix), buft(other) {}
  1862. ggml_backend_buffer_type_t buft_matrix; // matrices only - used by split buffers and backends that support only matrix multiplication
  1863. ggml_backend_buffer_type_t buft; // everything else
  1864. };
  1865. layer_buft buft_input;
  1866. layer_buft buft_output;
  1867. std::vector<layer_buft> buft_layer;
  1868. // contexts where the model tensors metadata is stored
  1869. std::vector<struct ggml_context *> ctxs;
  1870. // the model memory buffers for the tensor data
  1871. std::vector<ggml_backend_buffer_t> bufs;
  1872. // model memory mapped files
  1873. llama_mmaps mappings;
  1874. // objects representing data potentially being locked in memory
  1875. llama_mlocks mlock_bufs;
  1876. llama_mlocks mlock_mmaps;
  1877. // for quantize-stats only
  1878. std::vector<std::pair<std::string, struct ggml_tensor *>> tensors_by_name;
  1879. int64_t t_load_us = 0;
  1880. int64_t t_start_us = 0;
  1881. ~llama_model() {
  1882. for (struct ggml_context * ctx : ctxs) {
  1883. ggml_free(ctx);
  1884. }
  1885. for (ggml_backend_buffer_t buf : bufs) {
  1886. #ifdef GGML_USE_CUDA
  1887. if (ggml_backend_buffer_get_type(buf) == ggml_backend_cpu_buffer_type()) {
  1888. ggml_backend_cuda_unregister_host_buffer(ggml_backend_buffer_get_base(buf));
  1889. }
  1890. #endif
  1891. ggml_backend_buffer_free(buf);
  1892. }
  1893. }
  1894. };
  1895. struct llama_context {
  1896. llama_context(const llama_model & model) : model(model), t_start_us(model.t_start_us), t_load_us(model.t_load_us) {}
  1897. ~llama_context() {
  1898. ggml_backend_sched_free(sched);
  1899. for (ggml_backend_t backend : backends) {
  1900. ggml_backend_free(backend);
  1901. }
  1902. ggml_backend_buffer_free(buf_output);
  1903. }
  1904. llama_cparams cparams;
  1905. std::vector<ggml_backend_t> backends;
  1906. #ifdef GGML_USE_METAL
  1907. ggml_backend_t backend_metal = nullptr;
  1908. #endif
  1909. ggml_backend_t backend_cpu = nullptr;
  1910. const llama_model & model;
  1911. // key + value cache for the self attention
  1912. struct llama_kv_cache kv_self;
  1913. std::mt19937 rng;
  1914. bool has_evaluated_once = false;
  1915. int64_t t_start_us;
  1916. int64_t t_load_us;
  1917. int64_t t_sample_us = 0;
  1918. int64_t t_p_eval_us = 0;
  1919. int64_t t_eval_us = 0;
  1920. int64_t t_compute_start_us = 0;
  1921. int64_t n_queued_tokens = 0;
  1922. int32_t n_sample = 0; // number of tokens sampled
  1923. int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1)
  1924. int32_t n_eval = 0; // number of eval calls
  1925. // host buffer for the model output (logits and embeddings)
  1926. ggml_backend_buffer_t buf_output = nullptr;
  1927. // decode output (2-dimensional array: [n_outputs][n_vocab])
  1928. size_t logits_size = 0; // capacity (of floats) for logits
  1929. float * logits = nullptr;
  1930. std::vector<int32_t> output_ids; // map batch token positions to ids of the logits and embd buffers
  1931. size_t output_size = 0; // capacity (of tokens positions) for the output buffers
  1932. int32_t n_outputs = 0; // number of actually-used outputs in the current ubatch or last logical batch
  1933. bool logits_all = false;
  1934. // embeddings output (2-dimensional array: [n_outputs][n_embd])
  1935. // populated only when pooling_type == LLAMA_POOLING_TYPE_NONE
  1936. size_t embd_size = 0; // capacity (of floats) for embeddings
  1937. float * embd = nullptr;
  1938. // sequence embeddings output (map of [n_embd] vectors)
  1939. // populated only when pooling_type != LLAMA_POOLING_TYPE_NONE
  1940. std::map<llama_seq_id, std::vector<float>> embd_seq;
  1941. // memory buffers used to evaluate the model
  1942. std::vector<uint8_t> buf_compute_meta;
  1943. ggml_backend_sched_t sched = nullptr;
  1944. ggml_abort_callback abort_callback = nullptr;
  1945. void * abort_callback_data = nullptr;
  1946. // input tensors
  1947. struct ggml_tensor * inp_tokens; // I32 [n_batch]
  1948. struct ggml_tensor * inp_embd; // F32 [n_embd, n_batch]
  1949. struct ggml_tensor * inp_pos; // I32 [n_batch]
  1950. struct ggml_tensor * inp_out_ids; // I32 [n_outputs]
  1951. struct ggml_tensor * inp_KQ_mask; // F32 [kv_size, n_batch]
  1952. struct ggml_tensor * inp_KQ_pos; // F32 [n_kv]
  1953. struct ggml_tensor * inp_K_shift; // I32 [kv_size]
  1954. struct ggml_tensor * inp_mean; // F32 [n_batch, n_batch]
  1955. struct ggml_tensor * inp_cls; // I32 [n_batch]
  1956. struct ggml_tensor * inp_s_copy; // I32 [kv_size]
  1957. struct ggml_tensor * inp_s_mask; // F32 [1, n_kv]
  1958. struct ggml_tensor * inp_s_seq; // I32 [n_kv, n_batch]
  1959. // control vectors
  1960. struct llama_control_vector cvec;
  1961. #ifdef GGML_USE_MPI
  1962. ggml_mpi_context * ctx_mpi = NULL;
  1963. #endif
  1964. };
  1965. //
  1966. // kv cache helpers
  1967. //
  1968. static bool llama_kv_cache_init(
  1969. struct llama_kv_cache & cache,
  1970. const llama_model & model,
  1971. ggml_type type_k,
  1972. ggml_type type_v,
  1973. uint32_t kv_size,
  1974. bool offload) {
  1975. const struct llama_hparams & hparams = model.hparams;
  1976. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  1977. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  1978. const int64_t n_layer = hparams.n_layer;
  1979. cache.has_shift = false;
  1980. // TODO: find a nicer way to add other recurrent model architectures
  1981. cache.recurrent = model.arch == LLM_ARCH_MAMBA;
  1982. // TODO: support mixed reccurent Transformer architectues
  1983. // NOTE: (!a || b) is a logical implication (a -> b)
  1984. GGML_ASSERT(!cache.recurrent || n_embd_k_gqa == hparams.n_embd_k_s());
  1985. GGML_ASSERT(!cache.recurrent || n_embd_v_gqa == hparams.n_embd_v_s());
  1986. GGML_ASSERT( cache.recurrent || n_embd_k_gqa == hparams.n_embd_k_gqa());
  1987. GGML_ASSERT( cache.recurrent || n_embd_v_gqa == hparams.n_embd_v_gqa());
  1988. cache.head = 0;
  1989. cache.size = kv_size;
  1990. cache.used = 0;
  1991. cache.type_k = type_k;
  1992. cache.type_v = type_v;
  1993. cache.cells.clear();
  1994. cache.cells.resize(kv_size);
  1995. if (cache.recurrent) {
  1996. // init state copy sources
  1997. for (uint32_t i = 0; i < cache.size; ++i) {
  1998. cache.cells[i].src = i;
  1999. }
  2000. }
  2001. #ifdef GGML_USE_CLBLAST
  2002. offload = false;
  2003. #endif
  2004. // count used buffer types
  2005. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  2006. if (offload) {
  2007. for (int64_t i = 0; i < n_layer; ++i) {
  2008. buft_layer_count[model.buft_layer[i].buft]++;
  2009. }
  2010. } else {
  2011. buft_layer_count[llama_default_buffer_type_cpu(true)] = n_layer;
  2012. }
  2013. // create a context for each buffer type
  2014. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  2015. for (auto & it : buft_layer_count) {
  2016. int n_layers = it.second;
  2017. struct ggml_init_params params = {
  2018. /*.mem_size =*/ 2u*n_layers*ggml_tensor_overhead(),
  2019. /*.mem_buffer =*/ NULL,
  2020. /*.no_alloc =*/ true,
  2021. };
  2022. ggml_context * ctx = ggml_init(params);
  2023. if (!ctx) {
  2024. LLAMA_LOG_ERROR("%s: failed to allocate context for kv cache\n", __func__);
  2025. return false;
  2026. }
  2027. ctx_map[it.first] = ctx;
  2028. cache.ctxs.push_back(ctx);
  2029. }
  2030. cache.k_l.reserve(n_layer);
  2031. cache.v_l.reserve(n_layer);
  2032. for (int i = 0; i < (int) n_layer; i++) {
  2033. struct ggml_context * ctx = offload ? ctx_map.at(model.buft_layer[i].buft) : cache.ctxs.front();
  2034. ggml_tensor * k = ggml_new_tensor_1d(ctx, type_k, n_embd_k_gqa*kv_size);
  2035. ggml_tensor * v = ggml_new_tensor_1d(ctx, type_v, n_embd_v_gqa*kv_size);
  2036. ggml_format_name(k, "cache_k_l%d", i);
  2037. ggml_format_name(v, "cache_v_l%d", i);
  2038. cache.k_l.push_back(k);
  2039. cache.v_l.push_back(v);
  2040. }
  2041. // allocate tensors and initialize the buffers to avoid NaNs in the padding
  2042. for (auto it : ctx_map) {
  2043. ggml_backend_buffer_type_t buft = it.first;
  2044. ggml_context * ctx = it.second;
  2045. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  2046. if (!buf) {
  2047. LLAMA_LOG_ERROR("%s: failed to allocate buffer for kv cache\n", __func__);
  2048. return false;
  2049. }
  2050. ggml_backend_buffer_clear(buf, 0);
  2051. 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);
  2052. cache.bufs.push_back(buf);
  2053. }
  2054. return true;
  2055. }
  2056. // find an empty slot of size "n_tokens" in the cache
  2057. // updates the cache head
  2058. // Note: On success, it's important that cache.head points
  2059. // to the first cell of the slot.
  2060. static bool llama_kv_cache_find_slot(
  2061. struct llama_kv_cache & cache,
  2062. const struct llama_batch & batch) {
  2063. const uint32_t n_ctx = cache.size;
  2064. const uint32_t n_tokens = batch.n_tokens;
  2065. if (cache.recurrent) {
  2066. // For recurrent state architectures (like Mamba),
  2067. // each KV cache cell can store the state for a whole sequence.
  2068. llama_seq_id min = cache.size - 1;
  2069. llama_seq_id max = 0;
  2070. for (uint32_t i = 0; i < n_tokens; ++i) {
  2071. for (int32_t j = 0; j < batch.n_seq_id[i]; ++j) {
  2072. llama_seq_id seq_id = batch.seq_id[i][j];
  2073. // make sure it's a valid seq_id
  2074. if ((uint32_t) seq_id < cache.size) {
  2075. if (seq_id > max) {
  2076. max = seq_id;
  2077. }
  2078. if (seq_id < min) {
  2079. min = seq_id;
  2080. }
  2081. // Assuming the tokens are in-order
  2082. if (batch.pos[i] != cache.cells[seq_id].pos + 1) {
  2083. // What should happen when the pos backtracks or skips a value?
  2084. // Clearing the state mid-batch would require special-casing which isn't done.
  2085. LLAMA_LOG_WARN("%s: non-consecutive token position %d after %d for sequence %d\n",
  2086. __func__, batch.pos[i], cache.cells[seq_id].pos, seq_id);
  2087. }
  2088. if (cache.cells[seq_id].pos < 0 && 0 <= batch.pos[i]) {
  2089. cache.used += 1;
  2090. }
  2091. cache.cells[seq_id].pos = batch.pos[i];
  2092. // NOTE: seq_ids are not inserted here; they are handled when the input tensors are set
  2093. } else {
  2094. // too big seq_id
  2095. // TODO: would it be possible to resize the KV cache size instead?
  2096. LLAMA_LOG_ERROR("%s: seq_id=%d >= kv_size=%d Try using a bigger --parallel value\n", __func__, seq_id, cache.size);
  2097. return false;
  2098. }
  2099. }
  2100. }
  2101. // allow getting the range of used cells, from head to head + n
  2102. cache.head = min;
  2103. cache.n = max - min + 1;
  2104. // sanity check
  2105. return max >= min;
  2106. }
  2107. // otherwise, one cell per token.
  2108. if (n_tokens > n_ctx) {
  2109. LLAMA_LOG_ERROR("%s: n_tokens=%d > n_ctx=%d\n", __func__, n_tokens, n_ctx);
  2110. return false;
  2111. }
  2112. uint32_t n_tested = 0;
  2113. while (true) {
  2114. if (cache.head + n_tokens > n_ctx) {
  2115. n_tested += n_ctx - cache.head;
  2116. cache.head = 0;
  2117. continue;
  2118. }
  2119. bool found = true;
  2120. for (uint32_t i = 0; i < n_tokens; i++) {
  2121. if (cache.cells[cache.head + i].pos >= 0) {
  2122. found = false;
  2123. cache.head += i + 1;
  2124. n_tested += i + 1;
  2125. break;
  2126. }
  2127. }
  2128. if (found) {
  2129. break;
  2130. }
  2131. if (n_tested >= n_ctx) {
  2132. //LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens);
  2133. return false;
  2134. }
  2135. }
  2136. for (uint32_t i = 0; i < n_tokens; i++) {
  2137. cache.cells[cache.head + i].pos = batch.pos[i];
  2138. for (int32_t j = 0; j < batch.n_seq_id[i]; j++) {
  2139. cache.cells[cache.head + i].seq_id.insert(batch.seq_id[i][j]);
  2140. }
  2141. }
  2142. cache.used += n_tokens;
  2143. return true;
  2144. }
  2145. // find how many cells are currently in use
  2146. static uint32_t llama_kv_cache_cell_max(const struct llama_kv_cache & cache) {
  2147. for (uint32_t i = cache.size; i > 0; --i) {
  2148. const llama_kv_cell & cell = cache.cells[i - 1];
  2149. if (cell.pos >= 0 && !cell.is_empty()) {
  2150. return i;
  2151. }
  2152. }
  2153. return 0;
  2154. }
  2155. static void llama_kv_cache_clear(struct llama_kv_cache & cache) {
  2156. for (int32_t i = 0; i < (int32_t) cache.size; ++i) {
  2157. cache.cells[i].pos = -1;
  2158. cache.cells[i].seq_id.clear();
  2159. }
  2160. cache.head = 0;
  2161. cache.used = 0;
  2162. }
  2163. static bool llama_kv_cache_seq_rm(
  2164. struct llama_kv_cache & cache,
  2165. llama_seq_id seq_id,
  2166. llama_pos p0,
  2167. llama_pos p1) {
  2168. uint32_t new_head = cache.size;
  2169. if (p0 < 0) p0 = 0;
  2170. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2171. // models like Mamba can't have a state partially erased
  2172. if (cache.recurrent) {
  2173. if (seq_id >= (int64_t) cache.size) {
  2174. // could be fatal
  2175. return false;
  2176. }
  2177. if (0 <= seq_id) {
  2178. // partial intersection is invalid
  2179. if ((0 < p0 && p0 <= cache.cells[seq_id].pos) || (0 < p1 && p1 <= cache.cells[seq_id].pos)) {
  2180. return false;
  2181. }
  2182. } else {
  2183. // seq_id is negative, then the range should include everything or nothing
  2184. if (p0 != p1 && (p0 != 0 || p1 != std::numeric_limits<llama_pos>::max())) {
  2185. return false;
  2186. }
  2187. }
  2188. }
  2189. for (uint32_t i = 0; i < cache.size; ++i) {
  2190. if (cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2191. if (seq_id < 0) {
  2192. cache.cells[i].seq_id.clear();
  2193. } else if (cache.cells[i].has_seq_id(seq_id)) {
  2194. cache.cells[i].seq_id.erase(seq_id);
  2195. } else {
  2196. continue;
  2197. }
  2198. if (cache.cells[i].is_empty()) {
  2199. // keep count of the number of used cells
  2200. if (cache.cells[i].pos >= 0) cache.used--;
  2201. cache.cells[i].pos = -1;
  2202. if (new_head == cache.size) new_head = i;
  2203. }
  2204. }
  2205. }
  2206. // If we freed up a slot, set head to it so searching can start there.
  2207. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  2208. return true;
  2209. }
  2210. static void llama_kv_cache_seq_cp(
  2211. struct llama_kv_cache & cache,
  2212. llama_seq_id seq_id_src,
  2213. llama_seq_id seq_id_dst,
  2214. llama_pos p0,
  2215. llama_pos p1) {
  2216. if (p0 < 0) p0 = 0;
  2217. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2218. if (cache.recurrent) {
  2219. if ((uint32_t) seq_id_dst < cache.size && (uint32_t) seq_id_src < cache.size) {
  2220. seq_id_src = cache.cells[seq_id_src].src;
  2221. GGML_ASSERT((uint32_t) seq_id_src < cache.size);
  2222. // intent to "copy from"
  2223. // supports copy chains thanks to taking the source of the source
  2224. cache.cells[seq_id_dst].src = seq_id_src;
  2225. // preserve the "keep or clear" status of the copied sequence
  2226. if (cache.cells[seq_id_src].has_seq_id(seq_id_src)) {
  2227. cache.cells[seq_id_dst].seq_id.insert(seq_id_dst);
  2228. } else {
  2229. cache.cells[seq_id_dst].seq_id.erase(seq_id_dst);
  2230. }
  2231. cache.do_copy = true;
  2232. cache.cells[seq_id_dst].pos = cache.cells[seq_id_src].pos;
  2233. }
  2234. return;
  2235. }
  2236. // otherwise, this is the KV cache of a Transformer-like model
  2237. cache.head = 0;
  2238. for (uint32_t i = 0; i < cache.size; ++i) {
  2239. if (cache.cells[i].has_seq_id(seq_id_src) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2240. cache.cells[i].seq_id.insert(seq_id_dst);
  2241. }
  2242. }
  2243. }
  2244. static void llama_kv_cache_seq_keep(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  2245. uint32_t new_head = cache.size;
  2246. for (uint32_t i = 0; i < cache.size; ++i) {
  2247. if (!cache.cells[i].has_seq_id(seq_id)) {
  2248. if (cache.cells[i].pos >= 0) cache.used--;
  2249. cache.cells[i].pos = -1;
  2250. cache.cells[i].seq_id.clear();
  2251. if (new_head == cache.size) new_head = i;
  2252. } else {
  2253. cache.cells[i].seq_id.clear();
  2254. cache.cells[i].seq_id.insert(seq_id);
  2255. }
  2256. }
  2257. // If we freed up a slot, set head to it so searching can start there.
  2258. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  2259. }
  2260. static void llama_kv_cache_seq_add(
  2261. struct llama_kv_cache & cache,
  2262. llama_seq_id seq_id,
  2263. llama_pos p0,
  2264. llama_pos p1,
  2265. llama_pos delta) {
  2266. uint32_t new_head = cache.size;
  2267. if (p0 < 0) p0 = 0;
  2268. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2269. if (cache.recurrent) {
  2270. // for Mamba-like models, only the pos needs to be shifted
  2271. if (0 <= seq_id && seq_id < (int64_t) cache.size) {
  2272. llama_kv_cell & cell = cache.cells[seq_id];
  2273. if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
  2274. cell.pos += delta;
  2275. }
  2276. }
  2277. return;
  2278. }
  2279. for (uint32_t i = 0; i < cache.size; ++i) {
  2280. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2281. cache.has_shift = true;
  2282. cache.cells[i].pos += delta;
  2283. cache.cells[i].delta += delta;
  2284. if (cache.cells[i].pos < 0) {
  2285. if (!cache.cells[i].is_empty()) {
  2286. cache.used--;
  2287. }
  2288. cache.cells[i].pos = -1;
  2289. cache.cells[i].seq_id.clear();
  2290. if (new_head == cache.size) {
  2291. new_head = i;
  2292. }
  2293. }
  2294. }
  2295. }
  2296. // If we freed up a slot, set head to it so searching can start there.
  2297. // Otherwise we just start the next search from the beginning.
  2298. cache.head = new_head != cache.size ? new_head : 0;
  2299. }
  2300. static void llama_kv_cache_seq_div(
  2301. struct llama_kv_cache & cache,
  2302. llama_seq_id seq_id,
  2303. llama_pos p0,
  2304. llama_pos p1,
  2305. int d) {
  2306. if (p0 < 0) p0 = 0;
  2307. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2308. if (cache.recurrent) {
  2309. // for Mamba-like models, only the pos needs to be changed
  2310. if (0 <= seq_id && seq_id < (int64_t) cache.size) {
  2311. llama_kv_cell & cell = cache.cells[seq_id];
  2312. if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
  2313. cell.pos /= d;
  2314. }
  2315. }
  2316. return;
  2317. }
  2318. for (uint32_t i = 0; i < cache.size; ++i) {
  2319. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2320. cache.has_shift = true;
  2321. {
  2322. llama_pos p_old = cache.cells[i].pos;
  2323. cache.cells[i].pos /= d;
  2324. cache.cells[i].delta += cache.cells[i].pos - p_old;
  2325. }
  2326. }
  2327. }
  2328. }
  2329. static llama_pos llama_kv_cache_seq_pos_max(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  2330. llama_pos result = 0;
  2331. for (uint32_t i = 0; i < cache.size; ++i) {
  2332. if (cache.cells[i].has_seq_id(seq_id)) {
  2333. result = std::max(result, cache.cells[i].pos);
  2334. }
  2335. }
  2336. return result;
  2337. }
  2338. static void llama_kv_cache_defrag(struct llama_kv_cache & cache) {
  2339. cache.do_defrag = true;
  2340. }
  2341. //
  2342. // model loading and saving
  2343. //
  2344. enum llama_fver {
  2345. GGUF_FILE_VERSION_V1 = 1,
  2346. GGUF_FILE_VERSION_V2 = 2,
  2347. GGUF_FILE_VERSION_V3 = 3,
  2348. };
  2349. static const char * llama_file_version_name(llama_fver version) {
  2350. switch (version) {
  2351. case GGUF_FILE_VERSION_V1: return "GGUF V1 (support until nov 2023)";
  2352. case GGUF_FILE_VERSION_V2: return "GGUF V2";
  2353. case GGUF_FILE_VERSION_V3: return "GGUF V3 (latest)";
  2354. }
  2355. return "unknown";
  2356. }
  2357. static std::string llama_format_tensor_shape(const std::vector<int64_t> & ne) {
  2358. char buf[256];
  2359. snprintf(buf, sizeof(buf), "%5" PRId64, ne.at(0));
  2360. for (size_t i = 1; i < ne.size(); i++) {
  2361. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, ne.at(i));
  2362. }
  2363. return buf;
  2364. }
  2365. static std::string llama_format_tensor_shape(const struct ggml_tensor * t) {
  2366. char buf[256];
  2367. snprintf(buf, sizeof(buf), "%5" PRId64, t->ne[0]);
  2368. for (int i = 1; i < GGML_MAX_DIMS; i++) {
  2369. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, t->ne[i]);
  2370. }
  2371. return buf;
  2372. }
  2373. namespace GGUFMeta {
  2374. template <typename T, gguf_type gt_, T (*gfun)(const gguf_context *, const int)>
  2375. struct GKV_Base_Type {
  2376. static constexpr gguf_type gt = gt_;
  2377. static T getter(const gguf_context * ctx, const int kid) {
  2378. return gfun(ctx, kid);
  2379. }
  2380. };
  2381. template<typename T> struct GKV_Base;
  2382. template<> struct GKV_Base<bool >: GKV_Base_Type<bool, GGUF_TYPE_BOOL, gguf_get_val_bool> {};
  2383. template<> struct GKV_Base<uint8_t >: GKV_Base_Type<uint8_t, GGUF_TYPE_UINT8, gguf_get_val_u8 > {};
  2384. template<> struct GKV_Base<uint16_t >: GKV_Base_Type<uint16_t, GGUF_TYPE_UINT16, gguf_get_val_u16 > {};
  2385. template<> struct GKV_Base<uint32_t >: GKV_Base_Type<uint32_t, GGUF_TYPE_UINT32, gguf_get_val_u32 > {};
  2386. template<> struct GKV_Base<uint64_t >: GKV_Base_Type<uint64_t, GGUF_TYPE_UINT64, gguf_get_val_u64 > {};
  2387. template<> struct GKV_Base<int8_t >: GKV_Base_Type<int8_t, GGUF_TYPE_INT8, gguf_get_val_i8 > {};
  2388. template<> struct GKV_Base<int16_t >: GKV_Base_Type<int16_t, GGUF_TYPE_INT16, gguf_get_val_i16 > {};
  2389. template<> struct GKV_Base<int32_t >: GKV_Base_Type<int32_t, GGUF_TYPE_INT32, gguf_get_val_i32 > {};
  2390. template<> struct GKV_Base<int64_t >: GKV_Base_Type<int64_t, GGUF_TYPE_INT64, gguf_get_val_i64 > {};
  2391. template<> struct GKV_Base<float >: GKV_Base_Type<float, GGUF_TYPE_FLOAT32, gguf_get_val_f32 > {};
  2392. template<> struct GKV_Base<double >: GKV_Base_Type<double, GGUF_TYPE_FLOAT64, gguf_get_val_f64 > {};
  2393. template<> struct GKV_Base<const char *>: GKV_Base_Type<const char *, GGUF_TYPE_STRING, gguf_get_val_str > {};
  2394. template<> struct GKV_Base<std::string> {
  2395. static constexpr gguf_type gt = GGUF_TYPE_STRING;
  2396. static std::string getter(const gguf_context * ctx, const int kid) {
  2397. return gguf_get_val_str(ctx, kid);
  2398. }
  2399. };
  2400. struct ArrayInfo {
  2401. const gguf_type gt;
  2402. const size_t length;
  2403. const void * data;
  2404. };
  2405. template<> struct GKV_Base<ArrayInfo> {
  2406. public:
  2407. static constexpr gguf_type gt = GGUF_TYPE_ARRAY;
  2408. static ArrayInfo getter(const gguf_context *ctx, const int k) {
  2409. return ArrayInfo {
  2410. gguf_get_arr_type(ctx, k),
  2411. size_t(gguf_get_arr_n(ctx, k)),
  2412. gguf_get_arr_data(ctx, k),
  2413. };
  2414. }
  2415. };
  2416. template<typename T>
  2417. class GKV : public GKV_Base<T> {
  2418. GKV() = delete;
  2419. public:
  2420. static T get_kv(const gguf_context * ctx, const int k) {
  2421. const enum gguf_type kt = gguf_get_kv_type(ctx, k);
  2422. if (kt != GKV::gt) {
  2423. throw std::runtime_error(format("key %s has wrong type %s but expected type %s",
  2424. gguf_get_key(ctx, k), gguf_type_name(kt), gguf_type_name(GKV::gt)));
  2425. }
  2426. return GKV::getter(ctx, k);
  2427. }
  2428. static const char * override_type_to_str(const llama_model_kv_override_type ty) {
  2429. switch (ty) {
  2430. case LLAMA_KV_OVERRIDE_TYPE_BOOL: return "bool";
  2431. case LLAMA_KV_OVERRIDE_TYPE_INT: return "int";
  2432. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: return "float";
  2433. }
  2434. return "unknown";
  2435. }
  2436. static bool validate_override(const llama_model_kv_override_type expected_type, const struct llama_model_kv_override * ovrd) {
  2437. if (!ovrd) { return false; }
  2438. if (ovrd->tag == expected_type) {
  2439. LLAMA_LOG_INFO("%s: Using metadata override (%5s) '%s' = ",
  2440. __func__, override_type_to_str(ovrd->tag), ovrd->key);
  2441. switch (ovrd->tag) {
  2442. case LLAMA_KV_OVERRIDE_TYPE_BOOL: {
  2443. LLAMA_LOG_INFO("%s\n", ovrd->bool_value ? "true" : "false");
  2444. } break;
  2445. case LLAMA_KV_OVERRIDE_TYPE_INT: {
  2446. LLAMA_LOG_INFO("%" PRId64 "\n", ovrd->int_value);
  2447. } break;
  2448. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: {
  2449. LLAMA_LOG_INFO("%.6f\n", ovrd->float_value);
  2450. } break;
  2451. default:
  2452. // Shouldn't be possible to end up here, but just in case...
  2453. throw std::runtime_error(
  2454. format("Unsupported attempt to override %s type for metadata key %s\n",
  2455. override_type_to_str(ovrd->tag), ovrd->key));
  2456. }
  2457. return true;
  2458. }
  2459. LLAMA_LOG_WARN("%s: Warning: Bad metadata override type for key '%s', expected %s but got %s\n",
  2460. __func__, ovrd->key, override_type_to_str(expected_type), override_type_to_str(ovrd->tag));
  2461. return false;
  2462. }
  2463. template<typename OT>
  2464. static typename std::enable_if<std::is_same<OT, bool>::value, bool>::type
  2465. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  2466. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_BOOL, ovrd)) {
  2467. target = ovrd->bool_value;
  2468. return true;
  2469. }
  2470. return false;
  2471. }
  2472. template<typename OT>
  2473. static typename std::enable_if<!std::is_same<OT, bool>::value && std::is_integral<OT>::value, bool>::type
  2474. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  2475. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_INT, ovrd)) {
  2476. target = ovrd->int_value;
  2477. return true;
  2478. }
  2479. return false;
  2480. }
  2481. template<typename OT>
  2482. static typename std::enable_if<std::is_floating_point<OT>::value, bool>::type
  2483. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  2484. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_FLOAT, ovrd)) {
  2485. target = ovrd->float_value;
  2486. return true;
  2487. }
  2488. return false;
  2489. }
  2490. template<typename OT>
  2491. static typename std::enable_if<std::is_same<OT, std::string>::value, bool>::type
  2492. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  2493. (void)target;
  2494. (void)ovrd;
  2495. if (!ovrd) { return false; }
  2496. // Currently, we should never end up here so it would be a bug if we do.
  2497. throw std::runtime_error(format("Unsupported attempt to override string type for metadata key %s\n",
  2498. ovrd ? ovrd->key : "NULL"));
  2499. }
  2500. static bool set(const gguf_context * ctx, const int k, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  2501. if (try_override<T>(target, ovrd)) {
  2502. return true;
  2503. }
  2504. if (k < 0) { return false; }
  2505. target = get_kv(ctx, k);
  2506. return true;
  2507. }
  2508. static bool set(const gguf_context * ctx, const char * key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  2509. return set(ctx, gguf_find_key(ctx, key), target, ovrd);
  2510. }
  2511. static bool set(const gguf_context * ctx, const std::string & key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  2512. return set(ctx, key.c_str(), target, ovrd);
  2513. }
  2514. };
  2515. }
  2516. using llama_buf_map = std::unordered_map<uint32_t, ggml_backend_buffer_t>;
  2517. struct llama_model_loader {
  2518. int n_kv = 0;
  2519. int n_tensors = 0;
  2520. int n_created = 0;
  2521. int64_t n_elements = 0;
  2522. size_t n_bytes = 0;
  2523. bool use_mmap = false;
  2524. llama_files files;
  2525. llama_ftype ftype;
  2526. llama_fver fver;
  2527. llama_mmaps mappings;
  2528. // Holds information on a model weight
  2529. struct llama_tensor_weight {
  2530. uint16_t idx; // source file index
  2531. size_t offs; // tensor data offset in the original file
  2532. ggml_tensor * tensor;
  2533. llama_tensor_weight(uint16_t idx, const char * name, const struct gguf_context * gguf_ctx, ggml_tensor * tensor) : idx(idx), tensor(tensor) {
  2534. const int tensor_idx = gguf_find_tensor(gguf_ctx, name);
  2535. offs = gguf_get_data_offset(gguf_ctx) + gguf_get_tensor_offset(gguf_ctx, tensor_idx);
  2536. }
  2537. };
  2538. std::vector<llama_tensor_weight> weights;
  2539. std::unordered_map<std::string, struct llama_model_kv_override> kv_overrides;
  2540. struct gguf_context * meta = NULL;
  2541. std::vector<ggml_context *> contexts;
  2542. std::string arch_name;
  2543. LLM_KV llm_kv = LLM_KV(LLM_ARCH_UNKNOWN);
  2544. llama_model_loader(const std::string & fname, bool use_mmap, const struct llama_model_kv_override * param_overrides_p) {
  2545. int trace = 0;
  2546. if (getenv("LLAMA_TRACE")) {
  2547. trace = atoi(getenv("LLAMA_TRACE"));
  2548. }
  2549. if (param_overrides_p != nullptr) {
  2550. for (const struct llama_model_kv_override *p = param_overrides_p; p->key[0] != 0; p++) {
  2551. kv_overrides.insert({std::string(p->key), *p});
  2552. }
  2553. }
  2554. struct ggml_context * ctx = NULL;
  2555. struct gguf_init_params params = {
  2556. /*.no_alloc = */ true,
  2557. /*.ctx = */ &ctx,
  2558. };
  2559. meta = gguf_init_from_file(fname.c_str(), params);
  2560. if (!meta) {
  2561. throw std::runtime_error(format("%s: failed to load model from %s\n", __func__, fname.c_str()));
  2562. }
  2563. get_key(llm_kv(LLM_KV_GENERAL_ARCHITECTURE), arch_name, false);
  2564. llm_kv = LLM_KV(llm_arch_from_string(arch_name));
  2565. // Save tensors data offset of the main file.
  2566. // For subsidiary files, `meta` tensor data offset must not be used,
  2567. // so we build a unified tensors index for weights.
  2568. for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  2569. weights.emplace_back(0, cur->name, meta, cur);
  2570. }
  2571. files.emplace_back(new llama_file(fname.c_str(), "rb"));
  2572. contexts.emplace_back(ctx);
  2573. uint16_t n_split = 0;
  2574. get_key(llm_kv(LLM_KV_SPLIT_COUNT), n_split, false);
  2575. // Load additional GGML contexts
  2576. if (n_split > 1) {
  2577. uint16_t idx = 0;
  2578. get_key(llm_kv(LLM_KV_SPLIT_NO), idx);
  2579. if (idx != 0) {
  2580. throw std::runtime_error(format("illegal split file: %d, model must be loaded with the first split", idx));
  2581. }
  2582. char split_prefix[PATH_MAX] = {0};
  2583. if (!llama_split_prefix(split_prefix, sizeof(split_prefix), fname.c_str(), idx, n_split)) {
  2584. throw std::runtime_error(format("invalid split file: %s", fname.c_str()));
  2585. }
  2586. if (trace > 0) {
  2587. LLAMA_LOG_INFO("%s: loading additional %d GGUFs\n", __func__, n_split);
  2588. }
  2589. char split_path[PATH_MAX] = {0};
  2590. for (idx = 1; idx < n_split; idx++) {
  2591. llama_split_path(split_path, sizeof(split_path), split_prefix, idx, n_split);
  2592. struct gguf_init_params split_params = {
  2593. /*.no_alloc = */ true,
  2594. /*.ctx = */ &ctx,
  2595. };
  2596. struct gguf_context * ctx_gguf = gguf_init_from_file(split_path, split_params);
  2597. if (!ctx_gguf) {
  2598. throw std::runtime_error(format("%s: failed to load GGUF split from %s\n", __func__, split_path));
  2599. }
  2600. // Save tensors data offset info of the shard.
  2601. for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  2602. weights.emplace_back(idx, cur->name, ctx_gguf, cur);
  2603. }
  2604. files.emplace_back(new llama_file(split_path, "rb"));
  2605. contexts.emplace_back(ctx);
  2606. gguf_free(ctx_gguf);
  2607. }
  2608. get_key(llm_kv(LLM_KV_SPLIT_TENSORS_COUNT), n_tensors);
  2609. // sanity check
  2610. {
  2611. const int n_tensors_loaded = (int) weights.size();
  2612. if (n_tensors != n_tensors_loaded) {
  2613. throw std::runtime_error(format("corrupted model: %d tensors expected but %d found", n_tensors, n_tensors_loaded));
  2614. }
  2615. }
  2616. LLAMA_LOG_INFO("%s: additional %d GGUFs metadata loaded.\n", __func__, n_split - 1);
  2617. }
  2618. n_kv = gguf_get_n_kv(meta);
  2619. n_tensors = weights.size();
  2620. fver = (enum llama_fver) gguf_get_version(meta);
  2621. for (auto & w : weights) {
  2622. n_elements += ggml_nelements(w.tensor);
  2623. n_bytes += ggml_nbytes(w.tensor);
  2624. }
  2625. LLAMA_LOG_INFO("%s: loaded meta data with %d key-value pairs and %d tensors from %s (version %s)\n",
  2626. __func__, n_kv, n_tensors, fname.c_str(), llama_file_version_name(fver));
  2627. // determine file type based on the number of tensors for each quantization and print meta data
  2628. // TODO: make optional
  2629. {
  2630. std::map<enum ggml_type, uint32_t> n_type;
  2631. uint32_t n_type_max = 0;
  2632. enum ggml_type type_max = GGML_TYPE_F32;
  2633. for (int i = 0; i < n_tensors; i++) {
  2634. const ggml_tensor * tensor = weights.at(i).tensor;
  2635. enum ggml_type type = tensor->type;
  2636. n_type[type]++;
  2637. if (n_type_max < n_type[type]) {
  2638. n_type_max = n_type[type];
  2639. type_max = type;
  2640. }
  2641. if (trace > 0) {
  2642. const uint16_t sid = weights.at(i).idx;
  2643. 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());
  2644. }
  2645. }
  2646. switch (type_max) {
  2647. case GGML_TYPE_F32: ftype = LLAMA_FTYPE_ALL_F32; break;
  2648. case GGML_TYPE_F16: ftype = LLAMA_FTYPE_MOSTLY_F16; break;
  2649. case GGML_TYPE_Q4_0: ftype = LLAMA_FTYPE_MOSTLY_Q4_0; break;
  2650. case GGML_TYPE_Q4_1: ftype = LLAMA_FTYPE_MOSTLY_Q4_1; break;
  2651. case GGML_TYPE_Q5_0: ftype = LLAMA_FTYPE_MOSTLY_Q5_0; break;
  2652. case GGML_TYPE_Q5_1: ftype = LLAMA_FTYPE_MOSTLY_Q5_1; break;
  2653. case GGML_TYPE_Q8_0: ftype = LLAMA_FTYPE_MOSTLY_Q8_0; break;
  2654. case GGML_TYPE_Q2_K: ftype = LLAMA_FTYPE_MOSTLY_Q2_K; break;
  2655. case GGML_TYPE_Q3_K: ftype = LLAMA_FTYPE_MOSTLY_Q3_K_M; break;
  2656. case GGML_TYPE_Q4_K: ftype = LLAMA_FTYPE_MOSTLY_Q4_K_M; break;
  2657. case GGML_TYPE_Q5_K: ftype = LLAMA_FTYPE_MOSTLY_Q5_K_M; break;
  2658. case GGML_TYPE_Q6_K: ftype = LLAMA_FTYPE_MOSTLY_Q6_K; break;
  2659. case GGML_TYPE_IQ2_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XXS; break;
  2660. case GGML_TYPE_IQ2_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XS; break;
  2661. case GGML_TYPE_IQ2_S: ftype = LLAMA_FTYPE_MOSTLY_IQ2_S; break;
  2662. case GGML_TYPE_IQ3_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ3_XXS; break;
  2663. case GGML_TYPE_IQ1_S: ftype = LLAMA_FTYPE_MOSTLY_IQ1_S; break;
  2664. case GGML_TYPE_IQ1_M: ftype = LLAMA_FTYPE_MOSTLY_IQ1_M; break;
  2665. case GGML_TYPE_IQ4_NL: ftype = LLAMA_FTYPE_MOSTLY_IQ4_NL; break;
  2666. case GGML_TYPE_IQ4_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ4_XS; break;
  2667. case GGML_TYPE_IQ3_S: ftype = LLAMA_FTYPE_MOSTLY_IQ3_S; break;
  2668. default:
  2669. {
  2670. LLAMA_LOG_WARN("%s: unknown type %s\n", __func__, ggml_type_name(type_max));
  2671. ftype = LLAMA_FTYPE_ALL_F32;
  2672. } break;
  2673. }
  2674. // this is a way to mark that we have "guessed" the file type
  2675. ftype = (llama_ftype) (ftype | LLAMA_FTYPE_GUESSED);
  2676. {
  2677. const int kid = gguf_find_key(meta, "general.file_type");
  2678. if (kid >= 0) {
  2679. ftype = (llama_ftype) gguf_get_val_u32(meta, kid);
  2680. }
  2681. }
  2682. LLAMA_LOG_INFO("%s: Dumping metadata keys/values. Note: KV overrides do not apply in this output.\n", __func__);
  2683. for (int i = 0; i < n_kv; i++) {
  2684. const char * name = gguf_get_key(meta, i);
  2685. const enum gguf_type type = gguf_get_kv_type(meta, i);
  2686. const std::string type_name =
  2687. type == GGUF_TYPE_ARRAY
  2688. ? format("%s[%s,%d]", gguf_type_name(type), gguf_type_name(gguf_get_arr_type(meta, i)), gguf_get_arr_n(meta, i))
  2689. : gguf_type_name(type);
  2690. std::string value = gguf_kv_to_str(meta, i);
  2691. const size_t MAX_VALUE_LEN = 40;
  2692. if (value.size() > MAX_VALUE_LEN) {
  2693. value = format("%s...", value.substr(0, MAX_VALUE_LEN - 3).c_str());
  2694. }
  2695. replace_all(value, "\n", "\\n");
  2696. LLAMA_LOG_INFO("%s: - kv %3d: %42s %-16s = %s\n", __func__, i, name, type_name.c_str(), value.c_str());
  2697. }
  2698. // print type counts
  2699. for (auto & kv : n_type) {
  2700. if (kv.second == 0) {
  2701. continue;
  2702. }
  2703. LLAMA_LOG_INFO("%s: - type %4s: %4d tensors\n", __func__, ggml_type_name(kv.first), kv.second);
  2704. }
  2705. }
  2706. if (!llama_mmap::SUPPORTED) {
  2707. LLAMA_LOG_WARN("%s: mmap is not supported on this platform\n", __func__);
  2708. use_mmap = false;
  2709. }
  2710. this->use_mmap = use_mmap;
  2711. }
  2712. ~llama_model_loader() {
  2713. if (meta) {
  2714. gguf_free(meta);
  2715. }
  2716. for (auto * ctx : contexts) {
  2717. ggml_free(ctx);
  2718. }
  2719. }
  2720. template<typename T>
  2721. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2722. get_arr_n(const std::string & key, T & result, const bool required = true) {
  2723. const int kid = gguf_find_key(meta, key.c_str());
  2724. if (kid < 0) {
  2725. if (required) {
  2726. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2727. }
  2728. return false;
  2729. }
  2730. struct GGUFMeta::ArrayInfo arr_info =
  2731. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(meta, kid);
  2732. result = arr_info.length;
  2733. return true;
  2734. }
  2735. template<typename T>
  2736. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2737. get_arr_n(const enum llm_kv kid, T & result, const bool required = true) {
  2738. return get_arr_n(llm_kv(kid), result, required);
  2739. }
  2740. template<typename T>
  2741. bool get_key(const std::string & key, T & result, const bool required = true) {
  2742. auto it = kv_overrides.find(key);
  2743. const struct llama_model_kv_override * override =
  2744. it != kv_overrides.end() ? &it->second : nullptr;
  2745. const bool found = GGUFMeta::GKV<T>::set(meta, key, result, override);
  2746. if (required && !found) {
  2747. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2748. }
  2749. return found;
  2750. }
  2751. template<typename T>
  2752. bool get_key(const enum llm_kv kid, T & result, const bool required = true) {
  2753. return get_key(llm_kv(kid), result, required);
  2754. }
  2755. std::string get_arch_name() const {
  2756. return arch_name;
  2757. }
  2758. enum llm_arch get_arch() const {
  2759. return llm_kv.arch;
  2760. }
  2761. const char * get_tensor_name(int i) const {
  2762. return weights.at(i).tensor->name;
  2763. }
  2764. const llama_tensor_weight * get_weight(const char * name) const {
  2765. for (const auto & weight : weights) {
  2766. if (strcmp(name, weight.tensor->name) == 0) {
  2767. return &weight;
  2768. }
  2769. }
  2770. return nullptr;
  2771. }
  2772. const llama_tensor_weight & require_weight(const char * name) const {
  2773. const llama_tensor_weight * weight = get_weight(name);
  2774. if (!weight) {
  2775. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name));
  2776. }
  2777. return *weight;
  2778. }
  2779. struct ggml_tensor * get_tensor_meta(const char * name) const {
  2780. const auto * weight = get_weight(name);
  2781. if (!weight) {
  2782. return nullptr;
  2783. }
  2784. return weight->tensor;
  2785. }
  2786. struct ggml_tensor * require_tensor_meta(const char * name) const {
  2787. struct ggml_tensor * tensor = get_tensor_meta(name);
  2788. if (!tensor) {
  2789. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name));
  2790. }
  2791. return tensor;
  2792. }
  2793. struct ggml_tensor * get_tensor_meta(int i) const {
  2794. return get_tensor_meta(get_tensor_name(i));
  2795. }
  2796. struct ggml_tensor * create_tensor_for(struct ggml_context * ctx, const struct ggml_tensor * cur) {
  2797. struct ggml_tensor * tensor = ggml_dup_tensor(ctx, cur);
  2798. ggml_set_name(tensor, ggml_get_name(cur));
  2799. n_created++;
  2800. return tensor;
  2801. }
  2802. const struct ggml_tensor * check_tensor_dims(const std::string & name, const std::vector<int64_t> & ne, bool required) const {
  2803. const struct ggml_tensor * cur = get_tensor_meta(name.c_str());
  2804. if (cur == NULL) {
  2805. if (!required) {
  2806. return NULL;
  2807. }
  2808. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
  2809. }
  2810. {
  2811. bool is_ok = true;
  2812. for (size_t i = 0; i < GGML_MAX_DIMS; ++i) {
  2813. if ((i < ne.size() && ne[i] != cur->ne[i]) || (i >= ne.size() && cur->ne[i] != 1)) {
  2814. is_ok = false;
  2815. break;
  2816. }
  2817. }
  2818. if (!is_ok) {
  2819. throw std::runtime_error(
  2820. format("%s: tensor '%s' has wrong shape; expected %s, got %s",
  2821. __func__, name.c_str(),
  2822. llama_format_tensor_shape(ne).c_str(),
  2823. llama_format_tensor_shape(cur).c_str()));
  2824. }
  2825. }
  2826. return cur;
  2827. }
  2828. struct ggml_tensor * create_tensor(struct ggml_context * ctx, const std::string & name, const std::vector<int64_t> & ne, bool required = true) {
  2829. const struct ggml_tensor * cur = check_tensor_dims(name, ne, required);
  2830. if (cur == NULL) {
  2831. return NULL;
  2832. }
  2833. return create_tensor_for(ctx, cur);
  2834. }
  2835. 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) {
  2836. const struct ggml_tensor * cur = check_tensor_dims(name, ne, required);
  2837. if (cur == NULL) {
  2838. return NULL;
  2839. }
  2840. if (cur->type != base->type) {
  2841. 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)));
  2842. }
  2843. std::array<int64_t, GGML_MAX_DIMS> dims;
  2844. for (size_t i = 0; i < GGML_MAX_DIMS; ++i) {
  2845. dims[i] = i < ne.size() ? ne[i] : 1;
  2846. }
  2847. struct ggml_tensor * tensor = ggml_view_4d(ctx, base,
  2848. dims[0], dims[1], dims[2], dims[3],
  2849. cur->nb[1], cur->nb[2], cur->nb[3],
  2850. offset);
  2851. ggml_set_name(tensor, name.c_str());
  2852. n_created++;
  2853. return tensor;
  2854. }
  2855. void done_getting_tensors() const {
  2856. if (n_created != n_tensors) {
  2857. throw std::runtime_error(format("%s: wrong number of tensors; expected %d, got %d", __func__, n_tensors, n_created));
  2858. }
  2859. }
  2860. void init_mappings(bool prefetch = true, llama_mlocks * mlock_mmaps = nullptr) {
  2861. if (use_mmap) {
  2862. mappings.reserve(files.size());
  2863. mmaps_used.reserve(files.size());
  2864. for (const auto & file : files) {
  2865. std::unique_ptr<llama_mmap> mapping(new llama_mmap(file.get(), prefetch ? -1 : 0, ggml_is_numa()));
  2866. mmaps_used.emplace_back(mapping->size, 0);
  2867. if (mlock_mmaps) {
  2868. std::unique_ptr<llama_mlock> mlock_mmap(new llama_mlock());
  2869. mlock_mmap->init(mapping->addr);
  2870. mlock_mmaps->emplace_back(std::move(mlock_mmap));
  2871. }
  2872. mappings.emplace_back(std::move(mapping));
  2873. }
  2874. }
  2875. // compute the total size of all tensors for progress reporting
  2876. for (auto & w : weights) {
  2877. size_data += ggml_nbytes(w.tensor);
  2878. }
  2879. }
  2880. void get_mapping_range(size_t * first, size_t * last, void ** addr, int idx, ggml_context * ctx) const {
  2881. GGML_ASSERT(!mappings.empty());
  2882. const auto & mapping = mappings.at(idx);
  2883. *first = mapping->size;
  2884. *last = 0;
  2885. *addr = mapping->addr;
  2886. for (ggml_tensor * tensor = ggml_get_first_tensor(ctx); tensor; tensor = ggml_get_next_tensor(ctx, tensor)) {
  2887. try {
  2888. const auto * weight = get_weight(ggml_get_name(tensor));
  2889. if (!weight) {
  2890. continue;
  2891. }
  2892. if (weight->idx != idx) {
  2893. continue;
  2894. }
  2895. *first = std::min(*first, weight->offs);
  2896. *last = std::max(*last, weight->offs + ggml_nbytes(tensor));
  2897. } catch(...) {
  2898. // the tensor is not in the model
  2899. }
  2900. }
  2901. }
  2902. // for backwards compatibility, does not support ggml-backend
  2903. void load_data_for(struct ggml_tensor * cur) const {
  2904. const auto & w = require_weight(ggml_get_name(cur));
  2905. if (use_mmap) {
  2906. const auto & mapping = mappings.at(w.idx);
  2907. if (cur->data == nullptr) {
  2908. cur->data = (uint8_t *)mapping->addr + w.offs;
  2909. } else {
  2910. memcpy(cur->data, (uint8_t *)mapping->addr + w.offs, ggml_nbytes(cur));
  2911. }
  2912. } else {
  2913. GGML_ASSERT(cur->data != nullptr);
  2914. GGML_ASSERT(w.idx < files.size());
  2915. const auto & file = files.at(w.idx);
  2916. file->seek(w.offs, SEEK_SET);
  2917. file->read_raw(cur->data, ggml_nbytes(cur));
  2918. }
  2919. }
  2920. size_t size_done = 0;
  2921. size_t size_data = 0;
  2922. std::vector<std::pair<size_t, size_t>> mmaps_used;
  2923. // Returns false if cancelled by progress_callback
  2924. bool load_all_data(
  2925. struct ggml_context * ctx,
  2926. llama_buf_map & bufs_mmap,
  2927. llama_mlocks * lmlocks,
  2928. llama_progress_callback progress_callback,
  2929. void * progress_callback_user_data) {
  2930. GGML_ASSERT(size_data != 0 && "call init_mappings() first");
  2931. std::vector<no_init<uint8_t>> read_buf;
  2932. for (struct ggml_tensor * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  2933. const auto * weight = get_weight(ggml_get_name(cur));
  2934. if (weight == nullptr) {
  2935. // this can happen with split experts models
  2936. continue;
  2937. }
  2938. if (progress_callback) {
  2939. if (!progress_callback((float) size_done / size_data, progress_callback_user_data)) {
  2940. return false;
  2941. }
  2942. }
  2943. size_t n_size = ggml_nbytes(cur);
  2944. if (use_mmap) {
  2945. const auto & mapping = mappings.at(weight->idx);
  2946. ggml_backend_buffer_t buf_mmap = nullptr;
  2947. if (bufs_mmap.count(weight->idx)) {
  2948. buf_mmap = bufs_mmap.at(weight->idx);
  2949. }
  2950. GGML_ASSERT(buf_mmap || cur->data); // either we have a buffer to allocate the tensor in, or it is already allocated
  2951. if (buf_mmap && cur->data == nullptr) {
  2952. ggml_backend_tensor_alloc(buf_mmap, cur, (uint8_t *) mapping->addr + weight->offs);
  2953. if (lmlocks) {
  2954. const auto & lmlock = lmlocks->at(weight->idx);
  2955. lmlock->grow_to(weight->offs + ggml_nbytes(cur));
  2956. }
  2957. auto & mmap_used = mmaps_used[weight->idx];
  2958. mmap_used.first = std::min(mmap_used.first, weight->offs);
  2959. mmap_used.second = std::max(mmap_used.second, weight->offs + n_size);
  2960. } else {
  2961. ggml_backend_tensor_set(cur, (uint8_t *) mapping->addr + weight->offs, 0, n_size);
  2962. }
  2963. } else {
  2964. GGML_ASSERT(weight->idx < files.size());
  2965. const auto & file = files.at(weight->idx);
  2966. if (ggml_backend_buffer_is_host(cur->buffer)) {
  2967. file->seek(weight->offs, SEEK_SET);
  2968. file->read_raw(cur->data, ggml_nbytes(cur));
  2969. } else {
  2970. read_buf.resize(ggml_nbytes(cur));
  2971. file->seek(weight->offs, SEEK_SET);
  2972. file->read_raw(read_buf.data(), ggml_nbytes(cur));
  2973. ggml_backend_tensor_set(cur, read_buf.data(), 0, n_size);
  2974. }
  2975. }
  2976. size_done += n_size;
  2977. }
  2978. // check if this is the last call and do final cleanup
  2979. if (size_done >= size_data) {
  2980. // unmap offloaded tensors and metadata
  2981. if (use_mmap) {
  2982. for (uint32_t idx = 0; idx < mappings.size(); idx++) {
  2983. const auto & mmap_used = mmaps_used.at(idx);
  2984. auto & mapping = mappings.at(idx);
  2985. mapping->unmap_fragment(0, mmap_used.first);
  2986. if (mmap_used.second != 0) {
  2987. mapping->unmap_fragment(mmap_used.second, mapping->size);
  2988. }
  2989. }
  2990. }
  2991. if (progress_callback) {
  2992. // Even though the model is done loading, we still honor
  2993. // cancellation since we need to free allocations.
  2994. return progress_callback(1.0f, progress_callback_user_data);
  2995. }
  2996. }
  2997. return true;
  2998. }
  2999. };
  3000. template<>
  3001. bool llama_model_loader::get_key(const enum llm_kv kid, enum llama_pooling_type & result, const bool required) {
  3002. uint32_t tmp;
  3003. const bool found = get_key(kid, tmp, required);
  3004. if (found) {
  3005. result = (enum llama_pooling_type) tmp;
  3006. } else {
  3007. result = LLAMA_POOLING_TYPE_UNSPECIFIED;
  3008. }
  3009. return found;
  3010. }
  3011. //
  3012. // load LLaMA models
  3013. //
  3014. static const char * llama_model_arch_name(llm_arch arch) {
  3015. auto it = LLM_ARCH_NAMES.find(arch);
  3016. if (it == LLM_ARCH_NAMES.end()) {
  3017. return "unknown";
  3018. }
  3019. return it->second;
  3020. }
  3021. static std::string llama_model_ftype_name(llama_ftype ftype) {
  3022. if (ftype & LLAMA_FTYPE_GUESSED) {
  3023. return llama_model_ftype_name((enum llama_ftype) (ftype & ~LLAMA_FTYPE_GUESSED)) + " (guessed)";
  3024. }
  3025. switch (ftype) {
  3026. case LLAMA_FTYPE_ALL_F32: return "all F32";
  3027. case LLAMA_FTYPE_MOSTLY_F16: return "F16";
  3028. case LLAMA_FTYPE_MOSTLY_Q4_0: return "Q4_0";
  3029. case LLAMA_FTYPE_MOSTLY_Q4_1: return "Q4_1";
  3030. case LLAMA_FTYPE_MOSTLY_Q4_1_SOME_F16:
  3031. return "Q4_1, some F16";
  3032. case LLAMA_FTYPE_MOSTLY_Q5_0: return "Q5_0";
  3033. case LLAMA_FTYPE_MOSTLY_Q5_1: return "Q5_1";
  3034. case LLAMA_FTYPE_MOSTLY_Q8_0: return "Q8_0";
  3035. // K-quants
  3036. case LLAMA_FTYPE_MOSTLY_Q2_K: return "Q2_K - Medium";
  3037. case LLAMA_FTYPE_MOSTLY_Q2_K_S: return "Q2_K - Small";
  3038. case LLAMA_FTYPE_MOSTLY_Q3_K_S: return "Q3_K - Small";
  3039. case LLAMA_FTYPE_MOSTLY_Q3_K_M: return "Q3_K - Medium";
  3040. case LLAMA_FTYPE_MOSTLY_Q3_K_L: return "Q3_K - Large";
  3041. case LLAMA_FTYPE_MOSTLY_Q4_K_S: return "Q4_K - Small";
  3042. case LLAMA_FTYPE_MOSTLY_Q4_K_M: return "Q4_K - Medium";
  3043. case LLAMA_FTYPE_MOSTLY_Q5_K_S: return "Q5_K - Small";
  3044. case LLAMA_FTYPE_MOSTLY_Q5_K_M: return "Q5_K - Medium";
  3045. case LLAMA_FTYPE_MOSTLY_Q6_K: return "Q6_K";
  3046. case LLAMA_FTYPE_MOSTLY_IQ2_XXS:return "IQ2_XXS - 2.0625 bpw";
  3047. case LLAMA_FTYPE_MOSTLY_IQ2_XS: return "IQ2_XS - 2.3125 bpw";
  3048. case LLAMA_FTYPE_MOSTLY_IQ2_S: return "IQ2_S - 2.5 bpw";
  3049. case LLAMA_FTYPE_MOSTLY_IQ2_M: return "IQ2_M - 2.7 bpw";
  3050. case LLAMA_FTYPE_MOSTLY_IQ3_XS: return "IQ3_XS - 3.3 bpw";
  3051. case LLAMA_FTYPE_MOSTLY_IQ3_XXS:return "IQ3_XXS - 3.0625 bpw";
  3052. case LLAMA_FTYPE_MOSTLY_IQ1_S :return "IQ1_S - 1.5625 bpw";
  3053. case LLAMA_FTYPE_MOSTLY_IQ1_M :return "IQ1_M - 1.75 bpw";
  3054. case LLAMA_FTYPE_MOSTLY_IQ4_NL: return "IQ4_NL - 4.5 bpw";
  3055. case LLAMA_FTYPE_MOSTLY_IQ4_XS: return "IQ4_XS - 4.25 bpw";
  3056. case LLAMA_FTYPE_MOSTLY_IQ3_S: return "IQ3_S - 3.4375 bpw";
  3057. case LLAMA_FTYPE_MOSTLY_IQ3_M: return "IQ3_S mix - 3.66 bpw";
  3058. default: return "unknown, may not work";
  3059. }
  3060. }
  3061. static const char * llama_model_type_name(e_model type) {
  3062. switch (type) {
  3063. case MODEL_22M: return "22M";
  3064. case MODEL_33M: return "33M";
  3065. case MODEL_109M: return "109M";
  3066. case MODEL_137M: return "137M";
  3067. case MODEL_0_5B: return "0.5B";
  3068. case MODEL_1B: return "1B";
  3069. case MODEL_2B: return "2B";
  3070. case MODEL_3B: return "3B";
  3071. case MODEL_7B: return "7B";
  3072. case MODEL_8B: return "8B";
  3073. case MODEL_13B: return "13B";
  3074. case MODEL_14B: return "14B";
  3075. case MODEL_15B: return "15B";
  3076. case MODEL_20B: return "20B";
  3077. case MODEL_30B: return "30B";
  3078. case MODEL_34B: return "34B";
  3079. case MODEL_35B: return "35B";
  3080. case MODEL_40B: return "40B";
  3081. case MODEL_65B: return "65B";
  3082. case MODEL_70B: return "70B";
  3083. case MODEL_314B: return "314B";
  3084. case MODEL_SMALL: return "0.1B";
  3085. case MODEL_MEDIUM: return "0.4B";
  3086. case MODEL_LARGE: return "0.8B";
  3087. case MODEL_XL: return "1.5B";
  3088. default: return "?B";
  3089. }
  3090. }
  3091. static const char * llama_model_vocab_type_name(enum llama_vocab_type type){
  3092. switch (type) {
  3093. case LLAMA_VOCAB_TYPE_NONE: return "no vocab";
  3094. case LLAMA_VOCAB_TYPE_SPM: return "SPM";
  3095. case LLAMA_VOCAB_TYPE_BPE: return "BPE";
  3096. case LLAMA_VOCAB_TYPE_WPM: return "WPM";
  3097. default: return "unknown";
  3098. }
  3099. }
  3100. static void llm_load_arch(llama_model_loader & ml, llama_model & model) {
  3101. model.arch = ml.get_arch();
  3102. if (model.arch == LLM_ARCH_UNKNOWN) {
  3103. throw std::runtime_error("unknown model architecture: '" + ml.get_arch_name() + "'");
  3104. }
  3105. }
  3106. static void llm_load_hparams(
  3107. llama_model_loader & ml,
  3108. llama_model & model) {
  3109. auto & hparams = model.hparams;
  3110. const gguf_context * ctx = ml.meta;
  3111. // get metadata as string
  3112. for (int i = 0; i < gguf_get_n_kv(ctx); i++) {
  3113. enum gguf_type type = gguf_get_kv_type(ctx, i);
  3114. if (type == GGUF_TYPE_ARRAY) {
  3115. continue;
  3116. }
  3117. const char * name = gguf_get_key(ctx, i);
  3118. const std::string value = gguf_kv_to_str(ctx, i);
  3119. model.gguf_kv.emplace(name, value);
  3120. }
  3121. // get general kv
  3122. ml.get_key(LLM_KV_GENERAL_NAME, model.name, false);
  3123. // get hparams kv
  3124. ml.get_key(LLM_KV_VOCAB_SIZE, hparams.n_vocab, false) || ml.get_arr_n(LLM_KV_TOKENIZER_LIST, hparams.n_vocab);
  3125. ml.get_key(LLM_KV_CONTEXT_LENGTH, hparams.n_ctx_train);
  3126. ml.get_key(LLM_KV_EMBEDDING_LENGTH, hparams.n_embd);
  3127. ml.get_key(LLM_KV_FEED_FORWARD_LENGTH, hparams.n_ff);
  3128. ml.get_key(LLM_KV_ATTENTION_HEAD_COUNT, hparams.n_head);
  3129. ml.get_key(LLM_KV_BLOCK_COUNT, hparams.n_layer);
  3130. ml.get_key(LLM_KV_EXPERT_COUNT, hparams.n_expert, false);
  3131. ml.get_key(LLM_KV_EXPERT_USED_COUNT, hparams.n_expert_used, false);
  3132. GGML_ASSERT(hparams.n_expert <= LLAMA_MAX_EXPERTS);
  3133. GGML_ASSERT(hparams.n_expert_used <= hparams.n_expert);
  3134. if (hparams.n_expert > 0) {
  3135. GGML_ASSERT(hparams.n_expert_used > 0);
  3136. } else {
  3137. GGML_ASSERT(hparams.n_expert_used == 0);
  3138. }
  3139. // n_head_kv is optional, default to n_head
  3140. hparams.n_head_kv = hparams.n_head;
  3141. ml.get_key(LLM_KV_ATTENTION_HEAD_COUNT_KV, hparams.n_head_kv, false);
  3142. bool rope_finetuned = false;
  3143. ml.get_key(LLM_KV_ROPE_SCALING_FINETUNED, rope_finetuned, false);
  3144. hparams.rope_finetuned = rope_finetuned;
  3145. hparams.n_yarn_orig_ctx = hparams.n_ctx_train;
  3146. ml.get_key(LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, hparams.n_yarn_orig_ctx, false);
  3147. // rope_freq_base (optional)
  3148. hparams.rope_freq_base_train = 10000.0f;
  3149. ml.get_key(LLM_KV_ROPE_FREQ_BASE, hparams.rope_freq_base_train, false);
  3150. std::string rope_scaling("linear");
  3151. ml.get_key(LLM_KV_ROPE_SCALING_TYPE, rope_scaling, false);
  3152. hparams.rope_scaling_type_train = llama_rope_scaling_type_from_string(rope_scaling);
  3153. GGML_ASSERT(hparams.rope_scaling_type_train != LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED);
  3154. // rope_freq_scale (inverse of the kv) is optional
  3155. float ropescale = 0.0f;
  3156. if (!ml.get_key(LLM_KV_ROPE_SCALING_FACTOR, ropescale, false)) {
  3157. // try the old key name
  3158. ml.get_key(LLM_KV_ROPE_SCALE_LINEAR, ropescale, false);
  3159. }
  3160. hparams.rope_freq_scale_train = ropescale == 0.0f ? 1.0f : 1.0f/ropescale;
  3161. // sanity check for n_rot (optional)
  3162. {
  3163. hparams.n_rot = (hparams.n_head == 0) ? 0 : hparams.n_embd / hparams.n_head;
  3164. ml.get_key(LLM_KV_ROPE_DIMENSION_COUNT, hparams.n_rot, false);
  3165. if (model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON) {
  3166. if (hparams.n_rot != hparams.n_embd / hparams.n_head) {
  3167. throw std::runtime_error(format("invalid n_rot: %u, expected %u", hparams.n_rot, hparams.n_embd / hparams.n_head));
  3168. }
  3169. }
  3170. // gpt-neox n_rot = rotary_pct * (n_embd / n_head)
  3171. // gpt-j n_rot = rotary_dim
  3172. }
  3173. hparams.n_embd_head_k = (hparams.n_head == 0) ? 0 : hparams.n_embd / hparams.n_head;
  3174. ml.get_key(LLM_KV_ATTENTION_KEY_LENGTH, hparams.n_embd_head_k, false);
  3175. hparams.n_embd_head_v = (hparams.n_head == 0) ? 0 : hparams.n_embd / hparams.n_head;
  3176. ml.get_key(LLM_KV_ATTENTION_VALUE_LENGTH, hparams.n_embd_head_v, false);
  3177. // arch-specific KVs
  3178. switch (model.arch) {
  3179. case LLM_ARCH_LLAMA:
  3180. {
  3181. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3182. switch (hparams.n_layer) {
  3183. case 22: model.type = e_model::MODEL_1B; break;
  3184. case 26: model.type = e_model::MODEL_3B; break;
  3185. case 32: model.type = e_model::MODEL_7B; break;
  3186. case 40: model.type = e_model::MODEL_13B; break;
  3187. case 48: model.type = e_model::MODEL_34B; break;
  3188. case 60: model.type = e_model::MODEL_30B; break;
  3189. case 80: model.type = hparams.n_head == hparams.n_head_kv ? e_model::MODEL_65B : e_model::MODEL_70B; break;
  3190. default: model.type = e_model::MODEL_UNKNOWN;
  3191. }
  3192. } break;
  3193. case LLM_ARCH_MINICPM:
  3194. {
  3195. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3196. switch (hparams.n_layer) {
  3197. case 40: model.type = e_model::MODEL_2B; break;
  3198. default: model.type = e_model::MODEL_UNKNOWN;
  3199. }
  3200. } break;
  3201. case LLM_ARCH_GROK:
  3202. {
  3203. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3204. switch (hparams.n_layer) {
  3205. case 64: model.type = e_model::MODEL_314B; break;
  3206. default: model.type = e_model::MODEL_UNKNOWN;
  3207. }
  3208. } break;
  3209. case LLM_ARCH_FALCON:
  3210. {
  3211. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3212. switch (hparams.n_layer) {
  3213. case 32: model.type = e_model::MODEL_7B; break;
  3214. case 60: model.type = e_model::MODEL_40B; break;
  3215. default: model.type = e_model::MODEL_UNKNOWN;
  3216. }
  3217. } break;
  3218. case LLM_ARCH_BAICHUAN:
  3219. {
  3220. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3221. switch (hparams.n_layer) {
  3222. case 32: model.type = e_model::MODEL_7B; break;
  3223. case 40: model.type = e_model::MODEL_13B; break;
  3224. default: model.type = e_model::MODEL_UNKNOWN;
  3225. }
  3226. if (model.type == e_model::MODEL_13B) {
  3227. // TODO: become GGUF KV parameter
  3228. hparams.f_max_alibi_bias = 8.0f;
  3229. }
  3230. } break;
  3231. case LLM_ARCH_STARCODER:
  3232. {
  3233. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3234. switch (hparams.n_layer) {
  3235. case 24: model.type = e_model::MODEL_1B; break;
  3236. case 36: model.type = e_model::MODEL_3B; break;
  3237. case 42: model.type = e_model::MODEL_7B; break;
  3238. case 40: model.type = e_model::MODEL_15B; break;
  3239. default: model.type = e_model::MODEL_UNKNOWN;
  3240. }
  3241. } break;
  3242. case LLM_ARCH_PERSIMMON:
  3243. {
  3244. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3245. switch (hparams.n_layer) {
  3246. case 36: model.type = e_model::MODEL_8B; break;
  3247. default: model.type = e_model::MODEL_UNKNOWN;
  3248. }
  3249. } break;
  3250. case LLM_ARCH_REFACT:
  3251. {
  3252. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3253. switch (hparams.n_layer) {
  3254. case 32: model.type = e_model::MODEL_1B; break;
  3255. default: model.type = e_model::MODEL_UNKNOWN;
  3256. }
  3257. // TODO: become GGUF KV parameter
  3258. hparams.f_max_alibi_bias = 8.0f;
  3259. } break;
  3260. case LLM_ARCH_BERT:
  3261. {
  3262. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3263. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  3264. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  3265. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type, false);
  3266. switch (hparams.n_layer) {
  3267. case 3:
  3268. model.type = e_model::MODEL_17M; break; // bge-micro
  3269. case 6:
  3270. model.type = e_model::MODEL_22M; break; // MiniLM-L6
  3271. case 12:
  3272. switch (hparams.n_embd) {
  3273. case 384: model.type = e_model::MODEL_33M; break; // MiniLM-L12, bge-small
  3274. case 768: model.type = e_model::MODEL_109M; break; // bge-base
  3275. } break;
  3276. case 24:
  3277. model.type = e_model::MODEL_335M; break; // bge-large
  3278. }
  3279. } break;
  3280. case LLM_ARCH_NOMIC_BERT:
  3281. {
  3282. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3283. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  3284. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  3285. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type);
  3286. if (hparams.n_layer == 12 && hparams.n_embd == 768) {
  3287. model.type = e_model::MODEL_137M;
  3288. }
  3289. } break;
  3290. case LLM_ARCH_BLOOM:
  3291. {
  3292. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3293. switch (hparams.n_layer) {
  3294. case 24: model.type = e_model::MODEL_1B; break;
  3295. case 30:
  3296. switch (hparams.n_embd) {
  3297. case 2560: model.type = e_model::MODEL_3B; break;
  3298. case 4096: model.type = e_model::MODEL_7B; break;
  3299. } break;
  3300. }
  3301. // TODO: become GGUF KV parameter
  3302. hparams.f_max_alibi_bias = 8.0f;
  3303. } break;
  3304. case LLM_ARCH_MPT:
  3305. {
  3306. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3307. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv, false);
  3308. ml.get_key(LLM_KV_ATTENTION_MAX_ALIBI_BIAS, hparams.f_max_alibi_bias);
  3309. switch (hparams.n_layer) {
  3310. case 32: model.type = e_model::MODEL_7B; break;
  3311. case 48: model.type = e_model::MODEL_30B; break;
  3312. default: model.type = e_model::MODEL_UNKNOWN;
  3313. }
  3314. } break;
  3315. case LLM_ARCH_STABLELM:
  3316. {
  3317. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3318. switch (hparams.n_layer) {
  3319. case 24: model.type = e_model::MODEL_1B; break;
  3320. case 32: model.type = e_model::MODEL_3B; break;
  3321. default: model.type = e_model::MODEL_UNKNOWN;
  3322. }
  3323. } break;
  3324. case LLM_ARCH_QWEN:
  3325. {
  3326. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3327. switch (hparams.n_layer) {
  3328. case 32: model.type = e_model::MODEL_7B; break;
  3329. case 40: model.type = e_model::MODEL_13B; break;
  3330. default: model.type = e_model::MODEL_UNKNOWN;
  3331. }
  3332. } break;
  3333. case LLM_ARCH_QWEN2:
  3334. {
  3335. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3336. switch (hparams.n_layer) {
  3337. case 24: model.type = hparams.n_embd == 1024 ? e_model::MODEL_0_5B : e_model::MODEL_1B; break;
  3338. case 32: model.type = e_model::MODEL_7B; break;
  3339. case 40: model.type = hparams.n_head == 20 ? e_model::MODEL_4B : e_model::MODEL_13B; break;
  3340. case 80: model.type = e_model::MODEL_70B; break;
  3341. default: model.type = e_model::MODEL_UNKNOWN;
  3342. }
  3343. } break;
  3344. case LLM_ARCH_PHI2:
  3345. {
  3346. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3347. switch (hparams.n_layer) {
  3348. case 24: model.type = e_model::MODEL_1B; break;
  3349. case 32: model.type = e_model::MODEL_3B; break;
  3350. default: model.type = e_model::MODEL_UNKNOWN;
  3351. }
  3352. } break;
  3353. case LLM_ARCH_PLAMO:
  3354. {
  3355. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3356. switch (hparams.n_layer) {
  3357. case 40: model.type = e_model::MODEL_13B; break;
  3358. default: model.type = e_model::MODEL_UNKNOWN;
  3359. }
  3360. } break;
  3361. case LLM_ARCH_GPT2:
  3362. {
  3363. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3364. switch (hparams.n_layer) {
  3365. case 12: model.type = e_model::MODEL_SMALL; break;
  3366. case 24: model.type = e_model::MODEL_MEDIUM; break;
  3367. case 36: model.type = e_model::MODEL_LARGE; break;
  3368. case 48: model.type = e_model::MODEL_XL; break;
  3369. default: model.type = e_model::MODEL_UNKNOWN;
  3370. }
  3371. } break;
  3372. case LLM_ARCH_CODESHELL:
  3373. {
  3374. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3375. switch (hparams.n_layer) {
  3376. case 42: model.type = e_model::MODEL_SMALL; break;
  3377. default: model.type = e_model::MODEL_UNKNOWN;
  3378. }
  3379. } break;
  3380. case LLM_ARCH_ORION:
  3381. {
  3382. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3383. switch (hparams.n_layer) {
  3384. case 40: model.type = e_model::MODEL_14B; break;
  3385. default: model.type = e_model::MODEL_UNKNOWN;
  3386. }
  3387. } break;
  3388. case LLM_ARCH_INTERNLM2:
  3389. {
  3390. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3391. switch (hparams.n_layer) {
  3392. case 32: model.type = e_model::MODEL_7B; break;
  3393. case 48: model.type = e_model::MODEL_20B; break;
  3394. default: model.type = e_model::MODEL_UNKNOWN;
  3395. }
  3396. } break;
  3397. case LLM_ARCH_GEMMA:
  3398. {
  3399. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3400. switch (hparams.n_layer) {
  3401. case 18: model.type = e_model::MODEL_2B; break;
  3402. case 28: model.type = e_model::MODEL_7B; break;
  3403. default: model.type = e_model::MODEL_UNKNOWN;
  3404. }
  3405. } break;
  3406. case LLM_ARCH_STARCODER2:
  3407. {
  3408. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3409. switch (hparams.n_layer) {
  3410. case 30: model.type = e_model::MODEL_3B; break;
  3411. case 32: model.type = e_model::MODEL_7B; break;
  3412. case 40: model.type = e_model::MODEL_15B; break;
  3413. default: model.type = e_model::MODEL_UNKNOWN;
  3414. }
  3415. } break;
  3416. case LLM_ARCH_MAMBA:
  3417. {
  3418. ml.get_key(LLM_KV_SSM_CONV_KERNEL, hparams.ssm_d_conv);
  3419. ml.get_key(LLM_KV_SSM_INNER_SIZE, hparams.ssm_d_inner);
  3420. ml.get_key(LLM_KV_SSM_STATE_SIZE, hparams.ssm_d_state);
  3421. ml.get_key(LLM_KV_SSM_TIME_STEP_RANK, hparams.ssm_dt_rank);
  3422. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3423. switch (hparams.n_layer) {
  3424. case 24:
  3425. switch (hparams.n_embd) {
  3426. case 768: model.type = e_model::MODEL_SMALL; break;
  3427. default: model.type = e_model::MODEL_UNKNOWN;
  3428. } break;
  3429. case 48:
  3430. switch (hparams.n_embd) {
  3431. case 1024: model.type = e_model::MODEL_MEDIUM; break;
  3432. case 1536: model.type = e_model::MODEL_LARGE; break;
  3433. case 2048: model.type = e_model::MODEL_XL; break;
  3434. default: model.type = e_model::MODEL_UNKNOWN;
  3435. } break;
  3436. case 64:
  3437. switch (hparams.n_embd) {
  3438. case 2560: model.type = e_model::MODEL_3B; break;
  3439. default: model.type = e_model::MODEL_UNKNOWN;
  3440. } break;
  3441. default: model.type = e_model::MODEL_UNKNOWN;
  3442. }
  3443. } break;
  3444. case LLM_ARCH_XVERSE:
  3445. {
  3446. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3447. switch (hparams.n_layer) {
  3448. case 32: model.type = e_model::MODEL_7B; break;
  3449. case 40: model.type = e_model::MODEL_13B; break;
  3450. case 80: model.type = e_model::MODEL_65B; break;
  3451. default: model.type = e_model::MODEL_UNKNOWN;
  3452. }
  3453. } break;
  3454. case LLM_ARCH_COMMAND_R:
  3455. {
  3456. ml.get_key(LLM_KV_LOGIT_SCALE, hparams.f_logit_scale);
  3457. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3458. switch (hparams.n_layer) {
  3459. case 40: model.type = e_model::MODEL_35B; break;
  3460. default: model.type = e_model::MODEL_UNKNOWN;
  3461. }
  3462. } break;
  3463. default: (void)0;
  3464. }
  3465. model.ftype = ml.ftype;
  3466. if (hparams.f_max_alibi_bias > 0.0f) {
  3467. hparams.need_kq_pos = true;
  3468. }
  3469. hparams.rope_type = llama_rope_type(&model);
  3470. }
  3471. // TODO: This should probably be in llama.h
  3472. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special = false);
  3473. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch);
  3474. static void llm_load_vocab(
  3475. llama_model_loader & ml,
  3476. llama_model & model) {
  3477. auto & vocab = model.vocab;
  3478. struct gguf_context * ctx = ml.meta;
  3479. const auto kv = LLM_KV(model.arch);
  3480. // determine vocab type
  3481. {
  3482. std::string tokenizer_name;
  3483. ml.get_key(LLM_KV_TOKENIZER_MODEL, tokenizer_name);
  3484. if (tokenizer_name == "no_vocab") {
  3485. vocab.type = LLAMA_VOCAB_TYPE_NONE;
  3486. // default special tokens
  3487. vocab.special_bos_id = -1;
  3488. vocab.special_eos_id = -1;
  3489. vocab.special_unk_id = -1;
  3490. vocab.special_sep_id = -1;
  3491. vocab.special_pad_id = -1;
  3492. vocab.linefeed_id = -1;
  3493. return;
  3494. } else if (tokenizer_name == "llama") {
  3495. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  3496. // default special tokens
  3497. vocab.special_bos_id = 1;
  3498. vocab.special_eos_id = 2;
  3499. vocab.special_unk_id = 0;
  3500. vocab.special_sep_id = -1;
  3501. vocab.special_pad_id = -1;
  3502. const int add_space_prefix_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_ADD_PREFIX).c_str());
  3503. if (add_space_prefix_keyidx != -1) {
  3504. vocab.add_space_prefix = gguf_get_val_bool(ctx, add_space_prefix_keyidx);
  3505. } // The default value of add_space_prefix is true.
  3506. } else if (tokenizer_name == "gpt2") {
  3507. vocab.type = LLAMA_VOCAB_TYPE_BPE;
  3508. // read bpe merges and populate bpe ranks
  3509. const int merges_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_MERGES).c_str());
  3510. if (merges_keyidx == -1) {
  3511. throw std::runtime_error("cannot find tokenizer merges in model file\n");
  3512. }
  3513. const int n_merges = gguf_get_arr_n(ctx, merges_keyidx);
  3514. for (int i = 0; i < n_merges; i++) {
  3515. const std::string word = gguf_get_arr_str(ctx, merges_keyidx, i);
  3516. GGML_ASSERT(unicode_cpts_from_utf8(word).size() > 0);
  3517. std::string first;
  3518. std::string second;
  3519. const size_t pos = word.find(' ', 1);
  3520. if (pos != std::string::npos) {
  3521. first = word.substr(0, pos);
  3522. second = word.substr(pos + 1);
  3523. }
  3524. vocab.bpe_ranks.emplace(std::make_pair(first, second), i);
  3525. }
  3526. // default special tokens
  3527. vocab.special_bos_id = 11;
  3528. vocab.special_eos_id = 11;
  3529. vocab.special_unk_id = -1;
  3530. vocab.special_sep_id = -1;
  3531. vocab.special_pad_id = -1;
  3532. } else if (tokenizer_name == "bert") {
  3533. vocab.type = LLAMA_VOCAB_TYPE_WPM;
  3534. // default special tokens
  3535. vocab.special_bos_id = 101;
  3536. vocab.special_eos_id = 102;
  3537. vocab.special_unk_id = 100;
  3538. vocab.special_sep_id = -1;
  3539. vocab.special_pad_id = -1;
  3540. vocab.add_space_prefix = false;
  3541. } else {
  3542. LLAMA_LOG_WARN("%s: unknown tokenizer: '%s'", __func__, tokenizer_name.c_str());
  3543. LLAMA_LOG_WARN("%s: using default tokenizer: 'llama'", __func__);
  3544. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  3545. }
  3546. }
  3547. const int token_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_LIST).c_str());
  3548. if (token_idx == -1) {
  3549. throw std::runtime_error("cannot find tokenizer vocab in model file\n");
  3550. }
  3551. const float * scores = nullptr;
  3552. const int score_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_SCORES).c_str());
  3553. if (score_idx != -1) {
  3554. scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
  3555. }
  3556. const int * toktypes = nullptr;
  3557. const int toktype_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE).c_str());
  3558. if (toktype_idx != -1) {
  3559. toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
  3560. }
  3561. const uint32_t n_vocab = gguf_get_arr_n(ctx, token_idx);
  3562. vocab.id_to_token.resize(n_vocab);
  3563. for (uint32_t i = 0; i < n_vocab; i++) {
  3564. std::string word = gguf_get_arr_str(ctx, token_idx, i);
  3565. GGML_ASSERT(unicode_cpts_from_utf8(word).size() > 0);
  3566. vocab.token_to_id[word] = i;
  3567. auto & token_data = vocab.id_to_token[i];
  3568. token_data.text = std::move(word);
  3569. token_data.score = scores ? scores[i] : 0.0f;
  3570. token_data.type = toktypes ? (llama_token_type) toktypes[i] : LLAMA_TOKEN_TYPE_NORMAL;
  3571. }
  3572. GGML_ASSERT(vocab.id_to_token.size() == vocab.token_to_id.size());
  3573. // determine the newline token: LLaMA "<0x0A>" == 10 == '\n', Falcon 193 == '\n'
  3574. if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  3575. try {
  3576. vocab.linefeed_id = llama_byte_to_token(vocab, '\n');
  3577. } catch (const std::exception & e) {
  3578. LLAMA_LOG_WARN("%s: SPM vocabulary, but newline token not found: %s! Using special_pad_id instead.", __func__, e.what());
  3579. vocab.linefeed_id = vocab.special_pad_id;
  3580. }
  3581. } else if (vocab.type == LLAMA_VOCAB_TYPE_WPM) {
  3582. vocab.linefeed_id = vocab.special_pad_id;
  3583. } else {
  3584. const std::vector<int> ids = llama_tokenize_internal(vocab, "\xC4\x8A", false); // U+010A
  3585. GGML_ASSERT(!ids.empty() && "model vocab missing newline token");
  3586. vocab.linefeed_id = ids[0];
  3587. }
  3588. // special tokens
  3589. {
  3590. const std::vector<std::pair<enum llm_kv, int32_t &>> special_token_types = {
  3591. { LLM_KV_TOKENIZER_BOS_ID, vocab.special_bos_id },
  3592. { LLM_KV_TOKENIZER_EOS_ID, vocab.special_eos_id },
  3593. { LLM_KV_TOKENIZER_UNK_ID, vocab.special_unk_id },
  3594. { LLM_KV_TOKENIZER_SEP_ID, vocab.special_sep_id },
  3595. { LLM_KV_TOKENIZER_PAD_ID, vocab.special_pad_id },
  3596. };
  3597. for (const auto & it : special_token_types) {
  3598. const std::string & key = kv(std::get<0>(it));
  3599. int32_t & id = std::get<1>(it);
  3600. uint32_t new_id;
  3601. if (!ml.get_key(std::get<0>(it), new_id, false)) {
  3602. continue;
  3603. }
  3604. if (new_id >= vocab.id_to_token.size()) {
  3605. LLAMA_LOG_WARN("%s: bad special token: '%s' = %ud, using default id %d\n",
  3606. __func__, key.c_str(), new_id, id);
  3607. } else {
  3608. id = new_id;
  3609. }
  3610. }
  3611. // Handle add_bos_token and add_eos_token
  3612. {
  3613. bool temp = true;
  3614. if (ml.get_key(LLM_KV_TOKENIZER_ADD_BOS, temp, false)) {
  3615. vocab.special_add_bos = int(temp);
  3616. }
  3617. if (ml.get_key(LLM_KV_TOKENIZER_ADD_EOS, temp, false)) {
  3618. vocab.special_add_eos = int(temp);
  3619. }
  3620. }
  3621. }
  3622. // build special tokens cache
  3623. {
  3624. // TODO: It is unclear (to me) at this point, whether special tokes are guaranteed to be of a deterministic type,
  3625. // and will always be correctly labeled in 'added_tokens.json' etc.
  3626. // The assumption is, since special tokens aren't meant to be exposed to end user, they are designed
  3627. // to be unmatchable by the tokenizer, therefore tokens from the vocab, which are unmatchable by the tokenizer
  3628. // are special tokens.
  3629. // From testing, this appears to correlate 1:1 with special tokens.
  3630. //
  3631. // Counting special tokens and verifying in only one direction
  3632. // is sufficient to detect difference in those two sets.
  3633. //
  3634. uint32_t special_tokens_count_by_type = 0;
  3635. uint32_t special_tokens_count_from_verification = 0;
  3636. bool special_tokens_definition_mismatch = false;
  3637. for (const auto & t : vocab.token_to_id) {
  3638. const auto & token = t.first;
  3639. const auto & id = t.second;
  3640. // Count all non-normal tokens in the vocab while iterating
  3641. if (vocab.id_to_token[id].type != LLAMA_TOKEN_TYPE_NORMAL) {
  3642. special_tokens_count_by_type++;
  3643. }
  3644. // Skip single character tokens
  3645. if (token.length() > 1) {
  3646. bool is_tokenizable = false;
  3647. // Split token string representation in two, in all possible ways
  3648. // and check if both halves can be matched to a valid token
  3649. for (unsigned i = 1; i < token.length();) {
  3650. const auto left = token.substr(0, i);
  3651. const auto right = token.substr(i);
  3652. // check if we didnt partition in the middle of a utf sequence
  3653. auto utf = utf8_len(left.at(left.length() - 1));
  3654. if (utf == 1) {
  3655. if (vocab.token_to_id.find(left) != vocab.token_to_id.end() &&
  3656. vocab.token_to_id.find(right) != vocab.token_to_id.end() ) {
  3657. is_tokenizable = true;
  3658. break;
  3659. }
  3660. i++;
  3661. } else {
  3662. // skip over the rest of multibyte utf sequence
  3663. i += utf - 1;
  3664. }
  3665. }
  3666. if (!is_tokenizable) {
  3667. // Some tokens are multibyte, but they are utf sequences with equivalent text length of 1
  3668. // it's faster to re-filter them here, since there are way less candidates now
  3669. // Calculate a total "utf" length of a token string representation
  3670. size_t utf8_str_len = 0;
  3671. for (unsigned i = 0; i < token.length();) {
  3672. utf8_str_len++;
  3673. i += utf8_len(token.at(i));
  3674. }
  3675. // And skip the ones which are one character
  3676. if (utf8_str_len > 1) {
  3677. // At this point what we have left are special tokens only
  3678. vocab.special_tokens_cache[token] = id;
  3679. // Count manually found special tokens
  3680. special_tokens_count_from_verification++;
  3681. // If this manually found special token is not marked as such, flag a mismatch
  3682. if (vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL) {
  3683. special_tokens_definition_mismatch = true;
  3684. }
  3685. }
  3686. }
  3687. }
  3688. }
  3689. if (special_tokens_definition_mismatch || special_tokens_count_from_verification != special_tokens_count_by_type) {
  3690. LLAMA_LOG_WARN("%s: mismatch in special tokens definition ( %u/%zu vs %u/%zu ).\n",
  3691. __func__,
  3692. special_tokens_count_from_verification, vocab.id_to_token.size(),
  3693. special_tokens_count_by_type, vocab.id_to_token.size()
  3694. );
  3695. } else {
  3696. LLAMA_LOG_INFO("%s: special tokens definition check successful ( %u/%zu ).\n",
  3697. __func__,
  3698. special_tokens_count_from_verification, vocab.id_to_token.size()
  3699. );
  3700. }
  3701. }
  3702. }
  3703. static void llm_load_print_meta(llama_model_loader & ml, llama_model & model) {
  3704. const auto & hparams = model.hparams;
  3705. const auto & vocab = model.vocab;
  3706. const char * rope_scaling_type = LLAMA_ROPE_SCALING_TYPES.at(hparams.rope_scaling_type_train);
  3707. // hparams
  3708. LLAMA_LOG_INFO("%s: format = %s\n", __func__, llama_file_version_name(ml.fver));
  3709. LLAMA_LOG_INFO("%s: arch = %s\n", __func__, LLM_ARCH_NAMES.at(model.arch));
  3710. LLAMA_LOG_INFO("%s: vocab type = %s\n", __func__, llama_model_vocab_type_name(vocab.type));
  3711. LLAMA_LOG_INFO("%s: n_vocab = %u\n", __func__, hparams.n_vocab);
  3712. LLAMA_LOG_INFO("%s: n_merges = %u\n", __func__, (int) vocab.bpe_ranks.size());
  3713. LLAMA_LOG_INFO("%s: n_ctx_train = %u\n", __func__, hparams.n_ctx_train);
  3714. LLAMA_LOG_INFO("%s: n_embd = %u\n", __func__, hparams.n_embd);
  3715. LLAMA_LOG_INFO("%s: n_head = %u\n", __func__, hparams.n_head);
  3716. LLAMA_LOG_INFO("%s: n_head_kv = %u\n", __func__, hparams.n_head_kv);
  3717. LLAMA_LOG_INFO("%s: n_layer = %u\n", __func__, hparams.n_layer);
  3718. LLAMA_LOG_INFO("%s: n_rot = %u\n", __func__, hparams.n_rot);
  3719. LLAMA_LOG_INFO("%s: n_embd_head_k = %u\n", __func__, hparams.n_embd_head_k);
  3720. LLAMA_LOG_INFO("%s: n_embd_head_v = %u\n", __func__, hparams.n_embd_head_v);
  3721. LLAMA_LOG_INFO("%s: n_gqa = %u\n", __func__, hparams.n_gqa());
  3722. LLAMA_LOG_INFO("%s: n_embd_k_gqa = %u\n", __func__, hparams.n_embd_k_gqa());
  3723. LLAMA_LOG_INFO("%s: n_embd_v_gqa = %u\n", __func__, hparams.n_embd_v_gqa());
  3724. LLAMA_LOG_INFO("%s: f_norm_eps = %.1e\n", __func__, hparams.f_norm_eps);
  3725. LLAMA_LOG_INFO("%s: f_norm_rms_eps = %.1e\n", __func__, hparams.f_norm_rms_eps);
  3726. LLAMA_LOG_INFO("%s: f_clamp_kqv = %.1e\n", __func__, hparams.f_clamp_kqv);
  3727. LLAMA_LOG_INFO("%s: f_max_alibi_bias = %.1e\n", __func__, hparams.f_max_alibi_bias);
  3728. LLAMA_LOG_INFO("%s: f_logit_scale = %.1e\n", __func__, hparams.f_logit_scale);
  3729. LLAMA_LOG_INFO("%s: n_ff = %u\n", __func__, hparams.n_ff);
  3730. LLAMA_LOG_INFO("%s: n_expert = %u\n", __func__, hparams.n_expert);
  3731. LLAMA_LOG_INFO("%s: n_expert_used = %u\n", __func__, hparams.n_expert_used);
  3732. LLAMA_LOG_INFO("%s: causal attn = %d\n", __func__, hparams.causal_attn);
  3733. LLAMA_LOG_INFO("%s: pooling type = %d\n", __func__, hparams.pooling_type);
  3734. LLAMA_LOG_INFO("%s: rope type = %d\n", __func__, hparams.rope_type);
  3735. LLAMA_LOG_INFO("%s: rope scaling = %s\n", __func__, rope_scaling_type);
  3736. LLAMA_LOG_INFO("%s: freq_base_train = %.1f\n", __func__, hparams.rope_freq_base_train);
  3737. LLAMA_LOG_INFO("%s: freq_scale_train = %g\n", __func__, hparams.rope_freq_scale_train);
  3738. LLAMA_LOG_INFO("%s: n_yarn_orig_ctx = %u\n", __func__, hparams.n_yarn_orig_ctx);
  3739. LLAMA_LOG_INFO("%s: rope_finetuned = %s\n", __func__, hparams.rope_finetuned ? "yes" : "unknown");
  3740. LLAMA_LOG_INFO("%s: ssm_d_conv = %u\n", __func__, hparams.ssm_d_conv);
  3741. LLAMA_LOG_INFO("%s: ssm_d_inner = %u\n", __func__, hparams.ssm_d_inner);
  3742. LLAMA_LOG_INFO("%s: ssm_d_state = %u\n", __func__, hparams.ssm_d_state);
  3743. LLAMA_LOG_INFO("%s: ssm_dt_rank = %u\n", __func__, hparams.ssm_dt_rank);
  3744. LLAMA_LOG_INFO("%s: model type = %s\n", __func__, llama_model_type_name(model.type));
  3745. LLAMA_LOG_INFO("%s: model ftype = %s\n", __func__, llama_model_ftype_name(model.ftype).c_str());
  3746. if (ml.n_elements >= 1e12) {
  3747. LLAMA_LOG_INFO("%s: model params = %.2f T\n", __func__, ml.n_elements*1e-12);
  3748. } else if (ml.n_elements >= 1e9) {
  3749. LLAMA_LOG_INFO("%s: model params = %.2f B\n", __func__, ml.n_elements*1e-9);
  3750. } else if (ml.n_elements >= 1e6) {
  3751. LLAMA_LOG_INFO("%s: model params = %.2f M\n", __func__, ml.n_elements*1e-6);
  3752. } else {
  3753. LLAMA_LOG_INFO("%s: model params = %.2f K\n", __func__, ml.n_elements*1e-3);
  3754. }
  3755. if (ml.n_bytes < GiB) {
  3756. 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);
  3757. } else {
  3758. 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);
  3759. }
  3760. // general kv
  3761. LLAMA_LOG_INFO("%s: general.name = %s\n", __func__, model.name.c_str());
  3762. // special tokens
  3763. 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() ); }
  3764. 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() ); }
  3765. 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() ); }
  3766. 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() ); }
  3767. 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() ); }
  3768. 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() ); }
  3769. }
  3770. // Returns false if cancelled by progress_callback
  3771. static bool llm_load_tensors(
  3772. llama_model_loader & ml,
  3773. llama_model & model,
  3774. int n_gpu_layers,
  3775. enum llama_split_mode split_mode,
  3776. int main_gpu,
  3777. const float * tensor_split,
  3778. bool use_mlock,
  3779. llama_progress_callback progress_callback,
  3780. void * progress_callback_user_data) {
  3781. model.t_start_us = ggml_time_us();
  3782. auto & hparams = model.hparams;
  3783. model.split_mode = split_mode;
  3784. model.main_gpu = main_gpu;
  3785. model.n_gpu_layers = n_gpu_layers;
  3786. const int64_t n_layer = hparams.n_layer;
  3787. const int64_t i_gpu_start = std::max((int64_t) hparams.n_layer - n_gpu_layers, (int64_t) 0);
  3788. bool use_mmap_buffer = true;
  3789. // there is very little benefit to offloading the input layer, so always keep it on the CPU
  3790. model.buft_input = llama_default_buffer_type_cpu(true);
  3791. //model.buft_input = llama_default_buffer_type_offload(main_gpu);
  3792. model.buft_layer.resize(n_layer);
  3793. // assign cpu layers
  3794. for (int64_t i = 0; i < i_gpu_start; ++i) {
  3795. model.buft_layer[i] = llama_default_buffer_type_cpu(true);
  3796. }
  3797. if (split_mode == LLAMA_SPLIT_MODE_LAYER) {
  3798. // calculate the split points
  3799. int device_count = llama_get_device_count();
  3800. bool all_zero = tensor_split == nullptr || std::all_of(tensor_split, tensor_split + device_count, [](float x) { return x == 0.0f; });
  3801. std::vector<float> splits(device_count);
  3802. if (all_zero) {
  3803. // default split, by free memory
  3804. for (int i = 0; i < device_count; ++i) {
  3805. splits[i] = llama_get_device_memory(i);
  3806. }
  3807. } else {
  3808. std::copy(tensor_split, tensor_split + device_count, splits.begin());
  3809. }
  3810. // sum and normalize the splits to get the split points
  3811. float split_sum = 0.0f;
  3812. for (int i = 0; i < device_count; ++i) {
  3813. split_sum += splits[i];
  3814. splits[i] = split_sum;
  3815. }
  3816. for (int i = 0; i < device_count; ++i) {
  3817. splits[i] /= split_sum;
  3818. }
  3819. // assign the repeating layers to the devices according to the splits
  3820. int act_gpu_layers = std::min(n_gpu_layers, (int)n_layer + 1);
  3821. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  3822. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(i - i_gpu_start)/act_gpu_layers) - splits.begin();
  3823. model.buft_layer[i] = llama_default_buffer_type_offload(layer_gpu);
  3824. }
  3825. // assign the output layer
  3826. if (n_gpu_layers > n_layer) {
  3827. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(act_gpu_layers - 1)/act_gpu_layers) - splits.begin();
  3828. model.buft_output = llama_default_buffer_type_offload(layer_gpu);
  3829. } else {
  3830. model.buft_output = llama_default_buffer_type_cpu(true);
  3831. }
  3832. } else {
  3833. ggml_backend_buffer_type_t split_buft;
  3834. if (split_mode == LLAMA_SPLIT_MODE_ROW) {
  3835. split_buft = llama_default_buffer_type_split(main_gpu, tensor_split);
  3836. } else {
  3837. // LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_LAYER in backends where it is not supported
  3838. split_buft = llama_default_buffer_type_offload(main_gpu);
  3839. }
  3840. // assign the repeating layers
  3841. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  3842. model.buft_layer[i] = {
  3843. split_buft,
  3844. llama_default_buffer_type_offload(main_gpu)
  3845. };
  3846. }
  3847. // assign the output layer
  3848. if (n_gpu_layers > n_layer) {
  3849. model.buft_output = {
  3850. split_buft,
  3851. llama_default_buffer_type_offload(main_gpu)
  3852. };
  3853. } else {
  3854. model.buft_output = llama_default_buffer_type_cpu(true);
  3855. }
  3856. }
  3857. // count used buffer types
  3858. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  3859. buft_layer_count[model.buft_input.buft]++;
  3860. buft_layer_count[model.buft_input.buft_matrix]++;
  3861. buft_layer_count[model.buft_output.buft]++;
  3862. buft_layer_count[model.buft_output.buft_matrix]++;
  3863. for (int64_t i = 0; i < n_layer; ++i) {
  3864. buft_layer_count[model.buft_layer[i].buft]++;
  3865. buft_layer_count[model.buft_layer[i].buft_matrix]++;
  3866. }
  3867. // create one context per buffer type
  3868. size_t ctx_size = ggml_tensor_overhead()*(ml.n_tensors + 1); // +1 for models where tok_embd is duplicated as output
  3869. // for moe merged tensors
  3870. ctx_size += ggml_tensor_overhead()*hparams.n_expert*n_layer;
  3871. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  3872. for (auto & it : buft_layer_count) {
  3873. struct ggml_init_params params = {
  3874. /*.mem_size =*/ ctx_size,
  3875. /*.mem_buffer =*/ NULL,
  3876. /*.no_alloc =*/ true,
  3877. };
  3878. ggml_context * ctx = ggml_init(params);
  3879. if (!ctx) {
  3880. throw std::runtime_error(format("failed to create context"));
  3881. }
  3882. ctx_map[it.first] = ctx;
  3883. model.ctxs.push_back(ctx);
  3884. }
  3885. LLAMA_LOG_INFO("%s: ggml ctx size = %7.2f MiB\n", __func__, model.ctxs.size()*ctx_size/1024.0/1024.0);
  3886. // create tensors for the weights
  3887. {
  3888. const int64_t n_embd = hparams.n_embd;
  3889. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3890. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  3891. const int64_t n_embd_gqa = n_embd_v_gqa;
  3892. const int64_t n_vocab = hparams.n_vocab;
  3893. const int64_t n_vocab_type = hparams.n_vocab_type;
  3894. const int64_t n_ff = hparams.n_ff;
  3895. const int64_t n_expert = hparams.n_expert;
  3896. if (n_expert > 0 && hparams.n_expert_used == 0) {
  3897. throw std::runtime_error("model has expert layers but no expert layers are used");
  3898. }
  3899. GGML_ASSERT(n_embd_gqa == n_embd_k_gqa);
  3900. ggml_context * ctx_input = ctx_map.at(model.buft_input.buft);
  3901. ggml_context * ctx_output = ctx_map.at(model.buft_output.buft);
  3902. ggml_context * ctx_output_split = ctx_map.at(model.buft_output.buft_matrix);
  3903. auto ctx_for_layer = [&](int i) { return ctx_map.at(model.buft_layer[i].buft); };
  3904. auto ctx_for_layer_split = [&](int i) { return ctx_map.at(model.buft_layer[i].buft_matrix); };
  3905. model.layers.resize(n_layer);
  3906. const auto tn = LLM_TN(model.arch);
  3907. switch (model.arch) {
  3908. case LLM_ARCH_LLAMA:
  3909. case LLM_ARCH_REFACT:
  3910. case LLM_ARCH_MINICPM:
  3911. {
  3912. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3913. // output
  3914. {
  3915. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3916. if (model.arch != LLM_ARCH_MINICPM){
  3917. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  3918. // if output is NULL, init from the input tok embed
  3919. if (model.output == NULL) {
  3920. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3921. ml.n_created--; // artificial tensor
  3922. ml.size_data += ggml_nbytes(model.output);
  3923. }
  3924. }
  3925. }
  3926. for (int i = 0; i < n_layer; ++i) {
  3927. ggml_context * ctx_layer = ctx_for_layer(i);
  3928. ggml_context * ctx_split = ctx_for_layer_split(i);
  3929. auto & layer = model.layers[i];
  3930. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3931. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3932. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3933. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3934. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3935. // optional bias tensors
  3936. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, false);
  3937. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, false);
  3938. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, false);
  3939. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, false);
  3940. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3941. if (n_expert == 0) {
  3942. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3943. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3944. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3945. } else {
  3946. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  3947. layer.ffn_gate_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd, n_ff, n_expert}, false);
  3948. if (layer.ffn_gate_exps) {
  3949. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), { n_ff, n_embd, n_expert});
  3950. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  3951. } else {
  3952. // merge split expert into a single tensor for compatibility with older models
  3953. // requires disabling mmap
  3954. use_mmap_buffer = false;
  3955. ggml_type type_gate = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, 0).c_str())->type;
  3956. ggml_type type_down = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, 0).c_str())->type;
  3957. ggml_type type_up = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, 0).c_str())->type;
  3958. layer.ffn_gate_exps = ggml_new_tensor_3d(ctx_split, type_gate, n_embd, n_ff, n_expert);
  3959. layer.ffn_down_exps = ggml_new_tensor_3d(ctx_split, type_down, n_ff, n_embd, n_expert);
  3960. layer.ffn_up_exps = ggml_new_tensor_3d(ctx_split, type_up, n_embd, n_ff, n_expert);
  3961. ggml_set_name(layer.ffn_gate_exps, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i).c_str());
  3962. ggml_set_name(layer.ffn_down_exps, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i).c_str());
  3963. ggml_set_name(layer.ffn_up_exps, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i).c_str());
  3964. for (uint32_t x = 0; x < n_expert; ++x) {
  3965. // the individual experts are loaded into a view of the merged tensor
  3966. 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);
  3967. 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);
  3968. 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);
  3969. }
  3970. }
  3971. }
  3972. }
  3973. } break;
  3974. case LLM_ARCH_GROK:
  3975. {
  3976. if (n_expert == 0) {
  3977. throw std::runtime_error("Grok model cannot have zero experts");
  3978. }
  3979. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3980. // output
  3981. {
  3982. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3983. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  3984. // if output is NULL, init from the input tok embed
  3985. if (model.output == NULL) {
  3986. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3987. ml.n_created--; // artificial tensor
  3988. ml.size_data += ggml_nbytes(model.output);
  3989. }
  3990. }
  3991. for (int i = 0; i < n_layer; ++i) {
  3992. ggml_context * ctx_layer = ctx_for_layer(i);
  3993. ggml_context * ctx_split = ctx_for_layer_split(i);
  3994. auto & layer = model.layers[i];
  3995. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3996. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3997. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3998. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3999. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4000. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  4001. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4002. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  4003. layer.ffn_gate_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd, n_ff, n_expert}, false);
  4004. if (layer.ffn_gate_exps) {
  4005. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), { n_ff, n_embd, n_expert});
  4006. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  4007. } else {
  4008. // merge split expert into a single tensor for compatibility with older models
  4009. // requires disabling mmap
  4010. use_mmap_buffer = false;
  4011. ggml_type type_gate = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, 0).c_str())->type;
  4012. ggml_type type_down = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, 0).c_str())->type;
  4013. ggml_type type_up = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, 0).c_str())->type;
  4014. layer.ffn_gate_exps = ggml_new_tensor_3d(ctx_split, type_gate, n_embd, n_ff, n_expert);
  4015. layer.ffn_down_exps = ggml_new_tensor_3d(ctx_split, type_down, n_ff, n_embd, n_expert);
  4016. layer.ffn_up_exps = ggml_new_tensor_3d(ctx_split, type_up, n_embd, n_ff, n_expert);
  4017. ggml_set_name(layer.ffn_gate_exps, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i).c_str());
  4018. ggml_set_name(layer.ffn_down_exps, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i).c_str());
  4019. ggml_set_name(layer.ffn_up_exps, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i).c_str());
  4020. for (uint32_t x = 0; x < n_expert; ++x) {
  4021. // the individual experts are loaded into a view of the merged tensor
  4022. 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);
  4023. 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);
  4024. 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);
  4025. }
  4026. }
  4027. layer.layer_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd});
  4028. }
  4029. } break;
  4030. case LLM_ARCH_BAICHUAN:
  4031. {
  4032. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4033. {
  4034. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4035. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4036. }
  4037. for (int i = 0; i < n_layer; ++i) {
  4038. ggml_context * ctx_layer = ctx_for_layer(i);
  4039. ggml_context * ctx_split = ctx_for_layer_split(i);
  4040. auto & layer = model.layers[i];
  4041. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4042. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4043. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4044. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4045. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4046. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4047. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4048. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4049. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4050. }
  4051. } break;
  4052. case LLM_ARCH_FALCON:
  4053. {
  4054. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4055. // output
  4056. {
  4057. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4058. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4059. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  4060. if (!model.output) {
  4061. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}); // needs to be on GPU
  4062. ml.n_created--; // artificial tensor
  4063. ml.size_data += ggml_nbytes(model.output);
  4064. }
  4065. }
  4066. for (int i = 0; i < n_layer; ++i) {
  4067. ggml_context * ctx_layer = ctx_for_layer(i);
  4068. ggml_context * ctx_split = ctx_for_layer_split(i);
  4069. auto & layer = model.layers[i];
  4070. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4071. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4072. layer.attn_norm_2 = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i), {n_embd}, false);
  4073. layer.attn_norm_2_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "bias", i), {n_embd}, false);
  4074. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4075. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4076. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4077. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4078. }
  4079. } break;
  4080. case LLM_ARCH_STARCODER:
  4081. {
  4082. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4083. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  4084. // output
  4085. {
  4086. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4087. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4088. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4089. }
  4090. for (int i = 0; i < n_layer; ++i) {
  4091. ggml_context * ctx_layer = ctx_for_layer(i);
  4092. ggml_context * ctx_split = ctx_for_layer_split(i);
  4093. auto & layer = model.layers[i];
  4094. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4095. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4096. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4097. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  4098. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4099. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4100. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4101. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4102. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4103. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4104. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4105. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4106. }
  4107. } break;
  4108. case LLM_ARCH_PERSIMMON:
  4109. {
  4110. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4111. {
  4112. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4113. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4114. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4115. }
  4116. for (int i = 0; i < n_layer; ++i) {
  4117. ggml_context * ctx_layer = ctx_for_layer(i);
  4118. ggml_context * ctx_split = ctx_for_layer_split(i);
  4119. auto & layer = model.layers[i];
  4120. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4121. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4122. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4123. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  4124. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4125. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4126. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4127. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4128. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4129. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4130. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4131. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4132. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {64});
  4133. layer.attn_q_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "bias", i), {64});
  4134. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {64});
  4135. layer.attn_k_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "bias", i), {64});
  4136. }
  4137. } break;
  4138. case LLM_ARCH_BERT:
  4139. case LLM_ARCH_NOMIC_BERT:
  4140. {
  4141. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4142. model.type_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_TYPES, "weight"), {n_embd, n_vocab_type});
  4143. if (model.arch == LLM_ARCH_BERT) {
  4144. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  4145. }
  4146. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  4147. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  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. if (model.arch == LLM_ARCH_BERT) {
  4153. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4154. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  4155. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4156. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  4157. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4158. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  4159. } else {
  4160. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4161. }
  4162. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4163. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  4164. layer.attn_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "bias", i), {n_embd});
  4165. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4166. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4167. if (model.arch == LLM_ARCH_BERT) {
  4168. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4169. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4170. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4171. } else {
  4172. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4173. }
  4174. layer.layer_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd});
  4175. layer.layer_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "bias", i), {n_embd});
  4176. }
  4177. } break;
  4178. case LLM_ARCH_BLOOM:
  4179. {
  4180. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4181. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  4182. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  4183. // output
  4184. {
  4185. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4186. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4187. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4188. }
  4189. for (int i = 0; i < n_layer; ++i) {
  4190. ggml_context * ctx_layer = ctx_for_layer(i);
  4191. ggml_context * ctx_split = ctx_for_layer_split(i);
  4192. auto & layer = model.layers[i];
  4193. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4194. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4195. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4196. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  4197. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4198. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4199. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4200. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4201. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4202. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4203. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4204. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4205. }
  4206. } break;
  4207. case LLM_ARCH_MPT:
  4208. {
  4209. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4210. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train}, false);
  4211. // output
  4212. {
  4213. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4214. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, false);
  4215. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  4216. if (!model.output) {
  4217. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}); // needs to be on GPU
  4218. ml.n_created--; // artificial tensor
  4219. ml.size_data += ggml_nbytes(model.output);
  4220. }
  4221. }
  4222. for (int i = 0; i < n_layer; ++i) {
  4223. ggml_context * ctx_layer = ctx_for_layer(i);
  4224. ggml_context * ctx_split = ctx_for_layer_split(i);
  4225. auto & layer = model.layers[i];
  4226. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4227. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, false);
  4228. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4229. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, false);
  4230. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4231. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, false);
  4232. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4233. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, false);
  4234. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4235. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, false);
  4236. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4237. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, false);
  4238. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd}, false);
  4239. layer.attn_q_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "bias", i), {n_embd}, false);
  4240. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd}, false);
  4241. layer.attn_k_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "bias", i), {n_embd}, false);
  4242. // AWQ ScaleActivation layer
  4243. layer.ffn_act = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_ACT, "scales", i), {n_ff}, false);
  4244. }
  4245. } break;
  4246. case LLM_ARCH_STABLELM:
  4247. {
  4248. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4249. // output
  4250. {
  4251. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4252. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4253. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4254. }
  4255. for (int i = 0; i < n_layer; ++i) {
  4256. ggml_context * ctx_layer = ctx_for_layer(i);
  4257. ggml_context * ctx_split = ctx_for_layer_split(i);
  4258. auto & layer = model.layers[i];
  4259. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4260. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4261. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4262. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4263. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4264. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4265. // optional bias tensors, present in Stable LM 2 1.6B
  4266. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, false);
  4267. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, false);
  4268. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, false);
  4269. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4270. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4271. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4272. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4273. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4274. }
  4275. } break;
  4276. case LLM_ARCH_QWEN:
  4277. {
  4278. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4279. // output
  4280. {
  4281. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4282. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4283. }
  4284. for (int i = 0; i < n_layer; ++i) {
  4285. ggml_context * ctx_layer = ctx_for_layer(i);
  4286. ggml_context * ctx_split = ctx_for_layer_split(i);
  4287. auto & layer = model.layers[i];
  4288. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4289. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd*3});
  4290. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd*3});
  4291. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4292. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4293. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff/2});
  4294. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff/2, n_embd});
  4295. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff/2});
  4296. }
  4297. } break;
  4298. case LLM_ARCH_QWEN2:
  4299. {
  4300. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4301. // output
  4302. {
  4303. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4304. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4305. }
  4306. for (int i = 0; i < n_layer; ++i) {
  4307. ggml_context * ctx_layer = ctx_for_layer(i);
  4308. ggml_context * ctx_split = ctx_for_layer_split(i);
  4309. auto & layer = model.layers[i];
  4310. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4311. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4312. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4313. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4314. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4315. // optional bias tensors
  4316. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  4317. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  4318. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  4319. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4320. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4321. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4322. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4323. }
  4324. } break;
  4325. case LLM_ARCH_PHI2:
  4326. {
  4327. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4328. // output
  4329. {
  4330. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4331. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4332. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4333. model.output_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT, "bias"), {n_vocab});
  4334. }
  4335. for (int i = 0; i < n_layer; ++i) {
  4336. ggml_context * ctx_layer = ctx_for_layer(i);
  4337. ggml_context * ctx_split = ctx_for_layer_split(i);
  4338. auto & layer = model.layers[i];
  4339. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4340. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4341. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, false);
  4342. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, false);
  4343. if (layer.wqkv == nullptr) {
  4344. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4345. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  4346. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4347. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  4348. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4349. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  4350. }
  4351. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4352. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4353. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4354. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4355. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4356. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4357. }
  4358. } break;
  4359. case LLM_ARCH_PLAMO:
  4360. {
  4361. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4362. // output
  4363. {
  4364. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4365. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, 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.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4373. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4374. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4375. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4376. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4377. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4378. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4379. }
  4380. } break;
  4381. case LLM_ARCH_GPT2:
  4382. {
  4383. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4384. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  4385. // output
  4386. {
  4387. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4388. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4389. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4390. }
  4391. for (int i = 0; i < n_layer; ++i) {
  4392. ggml_context * ctx_layer = ctx_for_layer(i);
  4393. ggml_context * ctx_split = ctx_for_layer_split(i);
  4394. auto & layer = model.layers[i];
  4395. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4396. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4397. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4398. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  4399. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4400. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4401. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4402. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4403. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4404. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4405. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4406. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4407. }
  4408. } break;
  4409. case LLM_ARCH_CODESHELL:
  4410. {
  4411. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4412. // output
  4413. {
  4414. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4415. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4416. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4417. }
  4418. for (int i = 0; i < n_layer; ++i) {
  4419. ggml_context * ctx_layer = ctx_for_layer(i);
  4420. ggml_context * ctx_split = ctx_for_layer_split(i);
  4421. auto & layer = model.layers[i];
  4422. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4423. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4424. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4425. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  4426. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4427. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4428. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4429. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4430. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4431. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4432. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4433. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4434. }
  4435. } break;
  4436. case LLM_ARCH_ORION:
  4437. {
  4438. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4439. {
  4440. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4441. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4442. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4443. }
  4444. for (int i = 0; i < n_layer; ++i) {
  4445. ggml_context * ctx_layer = ctx_for_layer(i);
  4446. ggml_context * ctx_split = ctx_for_layer_split(i);
  4447. auto & layer = model.layers[i];
  4448. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4449. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4450. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4451. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4452. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4453. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4454. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4455. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4456. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4457. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4458. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4459. }
  4460. } break;
  4461. case LLM_ARCH_INTERNLM2:
  4462. {
  4463. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4464. // output
  4465. {
  4466. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4467. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4468. }
  4469. for (int i = 0; i < n_layer; ++i) {
  4470. ggml_context * ctx_layer = ctx_for_layer(i);
  4471. ggml_context * ctx_split = ctx_for_layer_split(i);
  4472. auto & layer = model.layers[i];
  4473. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4474. // layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4475. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4476. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4477. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4478. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4479. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4480. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4481. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4482. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4483. }
  4484. } break;
  4485. case LLM_ARCH_GEMMA:
  4486. {
  4487. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4488. // output
  4489. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4490. 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
  4491. ml.n_created--; // artificial tensor
  4492. ml.size_data += ggml_nbytes(model.output);
  4493. const int64_t n_ff = hparams.n_ff;
  4494. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  4495. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  4496. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  4497. for (uint32_t i = 0; i < n_layer; ++i) {
  4498. ggml_context * ctx_layer = ctx_for_layer(i);
  4499. ggml_context * ctx_split = ctx_for_layer_split(i);
  4500. auto & layer = model.layers[i];
  4501. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4502. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * hparams.n_head});
  4503. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  4504. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  4505. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * hparams.n_head, n_embd});
  4506. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4507. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4508. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4509. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4510. }
  4511. } break;
  4512. case LLM_ARCH_STARCODER2:
  4513. {
  4514. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4515. // output
  4516. {
  4517. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4518. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4519. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  4520. // if output is NULL, init from the input tok embed
  4521. if (model.output == NULL) {
  4522. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4523. ml.n_created--; // artificial tensor
  4524. ml.size_data += ggml_nbytes(model.output);
  4525. }
  4526. }
  4527. for (int i = 0; i < n_layer; ++i) {
  4528. ggml_context * ctx_layer = ctx_for_layer(i);
  4529. ggml_context * ctx_split = ctx_for_layer_split(i);
  4530. auto & layer = model.layers[i];
  4531. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4532. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4533. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4534. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4535. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4536. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4537. // optional bias tensors
  4538. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  4539. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  4540. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  4541. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4542. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4543. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4544. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4545. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4546. // optional bias tensors
  4547. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4548. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP , "bias", i), { n_ff});
  4549. }
  4550. } break;
  4551. case LLM_ARCH_MAMBA:
  4552. {
  4553. const int64_t d_conv = hparams.ssm_d_conv;
  4554. const int64_t d_inner = hparams.ssm_d_inner;
  4555. const int64_t d_state = hparams.ssm_d_state;
  4556. const int64_t dt_rank = hparams.ssm_dt_rank;
  4557. // only an expansion factor of 2 is supported for now
  4558. GGML_ASSERT(2 * n_embd == d_inner);
  4559. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4560. // output
  4561. {
  4562. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4563. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  4564. // if output is NULL, init from the input tok embed, duplicated to allow offloading
  4565. if (model.output == NULL) {
  4566. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4567. ml.n_created--; // artificial tensor
  4568. ml.size_data += ggml_nbytes(model.output);
  4569. }
  4570. }
  4571. for (int i = 0; i < n_layer; ++i) {
  4572. ggml_context * ctx_layer = ctx_for_layer(i);
  4573. ggml_context * ctx_split = ctx_for_layer_split(i);
  4574. auto & layer = model.layers[i];
  4575. // norm
  4576. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4577. layer.ssm_in = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_IN, "weight", i), {n_embd, 2*d_inner});
  4578. layer.ssm_conv1d = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_CONV1D, "weight", i), {d_conv, d_inner});
  4579. layer.ssm_conv1d_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_CONV1D, "bias", i), {d_inner});
  4580. layer.ssm_x = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_X, "weight", i), {d_inner, dt_rank + 2*d_state});
  4581. layer.ssm_dt = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_DT, "weight", i), {dt_rank, d_inner});
  4582. layer.ssm_dt_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_DT, "bias", i), {d_inner});
  4583. // no "weight" suffix for these
  4584. layer.ssm_a = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_A, i), {d_state, d_inner});
  4585. layer.ssm_d = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_D, i), {d_inner});
  4586. // out_proj
  4587. layer.ssm_out = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_OUT, "weight", i), {d_inner, n_embd});
  4588. }
  4589. } break;
  4590. case LLM_ARCH_XVERSE:
  4591. {
  4592. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  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});
  4596. }
  4597. for (int i = 0; i < n_layer; ++i) {
  4598. ggml_context * ctx_layer = ctx_for_layer(i);
  4599. ggml_context * ctx_split = ctx_for_layer_split(i);
  4600. auto & layer = model.layers[i];
  4601. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4602. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4603. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4604. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4605. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4606. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4607. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4608. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4609. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4610. }
  4611. } break;
  4612. case LLM_ARCH_COMMAND_R:
  4613. {
  4614. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4615. // output
  4616. {
  4617. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4618. // init output from the input tok embed
  4619. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4620. ml.n_created--; // artificial tensor
  4621. ml.size_data += ggml_nbytes(model.output);
  4622. }
  4623. for (int i = 0; i < n_layer; ++i) {
  4624. ggml_context * ctx_layer = ctx_for_layer(i);
  4625. ggml_context * ctx_split = ctx_for_layer_split(i);
  4626. auto & layer = model.layers[i];
  4627. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4628. if (n_layer >= 64){
  4629. 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});
  4630. 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});
  4631. }
  4632. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4633. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4634. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4635. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4636. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4637. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4638. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4639. }
  4640. } break;
  4641. default:
  4642. throw std::runtime_error("unknown architecture");
  4643. }
  4644. }
  4645. ml.done_getting_tensors();
  4646. ml.init_mappings(true, use_mlock ? &model.mlock_mmaps : nullptr);
  4647. model.mappings.reserve(ml.mappings.size());
  4648. // create the backend buffers
  4649. std::vector<std::pair<ggml_context *, llama_buf_map>> ctx_bufs;
  4650. ctx_bufs.reserve(ctx_map.size());
  4651. // Ensure we have enough capacity for the maximum backend buffer we will potentially create
  4652. size_t n_max_backend_buffer = ctx_map.size() * ml.files.size();
  4653. model.bufs.reserve(n_max_backend_buffer);
  4654. for (auto & it : ctx_map) {
  4655. ggml_backend_buffer_type_t buft = it.first;
  4656. ggml_context * ctx = it.second;
  4657. llama_buf_map bufs;
  4658. bufs.reserve(n_max_backend_buffer);
  4659. // only the mmap region containing the tensors in the model is mapped to the backend buffer
  4660. // 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
  4661. // this allows using partial offloading when the model size exceeds the metal buffer size, but not the RAM size
  4662. if (ml.use_mmap && use_mmap_buffer && buft == llama_default_buffer_type_cpu(true)) {
  4663. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  4664. void * addr = nullptr;
  4665. size_t first, last;
  4666. ml.get_mapping_range(&first, &last, &addr, idx, ctx);
  4667. if (first >= last) {
  4668. continue;
  4669. }
  4670. ggml_backend_buffer_t buf = ggml_backend_cpu_buffer_from_ptr((char *) addr + first, last - first);
  4671. if (buf == nullptr) {
  4672. throw std::runtime_error("unable to allocate backend CPU buffer");
  4673. }
  4674. model.bufs.push_back(buf);
  4675. bufs.emplace(idx, buf);
  4676. #ifdef GGML_USE_CUDA
  4677. if (n_layer >= n_gpu_layers) {
  4678. ggml_backend_cuda_register_host_buffer(
  4679. ggml_backend_buffer_get_base(buf),
  4680. ggml_backend_buffer_get_size(buf));
  4681. }
  4682. #endif
  4683. }
  4684. }
  4685. #ifdef GGML_USE_METAL
  4686. else if (ml.use_mmap && use_mmap_buffer && buft == ggml_backend_metal_buffer_type()) {
  4687. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  4688. const size_t max_size = ggml_get_max_tensor_size(ctx);
  4689. void * addr = nullptr;
  4690. size_t first, last;
  4691. ml.get_mapping_range(&first, &last, &addr, idx, ctx);
  4692. if (first >= last) {
  4693. continue;
  4694. }
  4695. ggml_backend_buffer_t buf = ggml_backend_metal_buffer_from_ptr((char *) addr + first, last - first, max_size);
  4696. if (buf == nullptr) {
  4697. throw std::runtime_error("unable to allocate backend metal buffer");
  4698. }
  4699. model.bufs.push_back(buf);
  4700. bufs.emplace(idx, buf);
  4701. }
  4702. }
  4703. #endif
  4704. else {
  4705. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  4706. if (buf == nullptr) {
  4707. throw std::runtime_error("unable to allocate backend buffer");
  4708. }
  4709. model.bufs.push_back(buf);
  4710. if (use_mlock && ggml_backend_buffer_is_host(buf)) {
  4711. model.mlock_bufs.emplace_back(new llama_mlock);
  4712. auto & mlock_buf = model.mlock_bufs.back();
  4713. mlock_buf->init (ggml_backend_buffer_get_base(buf));
  4714. mlock_buf->grow_to(ggml_backend_buffer_get_size(buf));
  4715. }
  4716. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  4717. bufs.emplace(idx, buf);
  4718. }
  4719. }
  4720. if (bufs.empty()) {
  4721. throw std::runtime_error("failed to allocate buffer");
  4722. }
  4723. for (auto & buf : bufs) {
  4724. // indicate that this buffer contains weights
  4725. // 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
  4726. ggml_backend_buffer_set_usage(buf.second, GGML_BACKEND_BUFFER_USAGE_WEIGHTS);
  4727. }
  4728. ctx_bufs.emplace_back(ctx, bufs);
  4729. }
  4730. if (llama_supports_gpu_offload()) {
  4731. const int n_gpu = std::min(n_gpu_layers, int(hparams.n_layer));
  4732. LLAMA_LOG_INFO("%s: offloading %d repeating layers to GPU\n", __func__, n_gpu);
  4733. if (n_gpu_layers > (int) hparams.n_layer) {
  4734. LLAMA_LOG_INFO("%s: offloading non-repeating layers to GPU\n", __func__);
  4735. }
  4736. const int max_backend_supported_layers = hparams.n_layer + 1;
  4737. const int max_offloadable_layers = hparams.n_layer + 1;
  4738. LLAMA_LOG_INFO("%s: offloaded %d/%d layers to GPU\n", __func__, std::min(n_gpu_layers, max_offloadable_layers), max_backend_supported_layers);
  4739. }
  4740. // print memory requirements
  4741. for (ggml_backend_buffer_t buf : model.bufs) {
  4742. 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);
  4743. }
  4744. // populate tensors_by_name
  4745. for (ggml_context * ctx : model.ctxs) {
  4746. for (auto * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  4747. model.tensors_by_name.emplace_back(ggml_get_name(cur), cur);
  4748. }
  4749. }
  4750. // load tensor data
  4751. for (auto & it : ctx_bufs) {
  4752. ggml_context * ctx = it.first;
  4753. auto & bufs = it.second;
  4754. if (!ml.load_all_data(ctx, bufs, use_mlock ? &model.mlock_mmaps : NULL, progress_callback, progress_callback_user_data)) {
  4755. return false;
  4756. }
  4757. }
  4758. if (use_mmap_buffer) {
  4759. for (auto & mapping : ml.mappings) {
  4760. model.mappings.emplace_back(std::move(mapping));
  4761. }
  4762. }
  4763. // loading time will be recalculate after the first eval, so
  4764. // we take page faults deferred by mmap() into consideration
  4765. model.t_load_us = ggml_time_us() - model.t_start_us;
  4766. return true;
  4767. }
  4768. // Returns 0 on success, -1 on error, and -2 on cancellation via llama_progress_callback
  4769. static int llama_model_load(const std::string & fname, llama_model & model, llama_model_params & params) {
  4770. try {
  4771. llama_model_loader ml(fname, params.use_mmap, params.kv_overrides);
  4772. model.hparams.vocab_only = params.vocab_only;
  4773. try {
  4774. llm_load_arch(ml, model);
  4775. } catch(const std::exception & e) {
  4776. throw std::runtime_error("error loading model architecture: " + std::string(e.what()));
  4777. }
  4778. try {
  4779. llm_load_hparams(ml, model);
  4780. } catch(const std::exception & e) {
  4781. throw std::runtime_error("error loading model hyperparameters: " + std::string(e.what()));
  4782. }
  4783. try {
  4784. llm_load_vocab(ml, model);
  4785. } catch(const std::exception & e) {
  4786. throw std::runtime_error("error loading model vocabulary: " + std::string(e.what()));
  4787. }
  4788. llm_load_print_meta(ml, model);
  4789. if (model.vocab.type != LLAMA_VOCAB_TYPE_NONE &&
  4790. model.hparams.n_vocab != model.vocab.id_to_token.size()) {
  4791. throw std::runtime_error("vocab size mismatch");
  4792. }
  4793. if (params.vocab_only) {
  4794. LLAMA_LOG_INFO("%s: vocab only - skipping tensors\n", __func__);
  4795. return 0;
  4796. }
  4797. #ifdef GGML_USE_KOMPUTE
  4798. if (params.n_gpu_layers > 0 && (
  4799. !(model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON)
  4800. || !(
  4801. model.ftype == LLAMA_FTYPE_ALL_F32 ||
  4802. model.ftype == LLAMA_FTYPE_MOSTLY_F16 ||
  4803. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ||
  4804. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_1
  4805. )
  4806. )) {
  4807. // TODO(cebtenzzre): propagate this error outside of llama_load_model_from_file
  4808. LLAMA_LOG_WARN("%s: disabling Kompute due to unsupported model arch or quantization\n", __func__);
  4809. params.n_gpu_layers = 0;
  4810. }
  4811. #endif
  4812. #ifdef GGML_USE_SYCL
  4813. if (params.split_mode == LLAMA_SPLIT_MODE_NONE) {
  4814. ggml_backend_sycl_set_single_device_mode(params.main_gpu);
  4815. //SYCL use device index (0, 1, 2) directly, uer input device id, then convert to device index.
  4816. params.main_gpu = ggml_backend_sycl_get_device_index(params.main_gpu);
  4817. } else {
  4818. ggml_backend_sycl_set_mul_device_mode();
  4819. }
  4820. #endif
  4821. if (!llm_load_tensors(
  4822. ml, model, params.n_gpu_layers, params.split_mode, params.main_gpu, params.tensor_split, params.use_mlock,
  4823. params.progress_callback, params.progress_callback_user_data
  4824. )) {
  4825. return -2;
  4826. }
  4827. } catch (const std::exception & err) {
  4828. LLAMA_LOG_ERROR("%s: error loading model: %s\n", __func__, err.what());
  4829. return -1;
  4830. }
  4831. return 0;
  4832. }
  4833. //
  4834. // llm_build
  4835. //
  4836. using llm_build_cb = std::function<void(struct ggml_tensor * cur, const char * name, int nl)>;
  4837. enum llm_ffn_op_type {
  4838. LLM_FFN_SILU,
  4839. LLM_FFN_GELU,
  4840. LLM_FFN_RELU,
  4841. LLM_FFN_RELU_SQR,
  4842. };
  4843. enum llm_ffn_gate_type {
  4844. LLM_FFN_SEQ,
  4845. LLM_FFN_PAR, // ffn_gate is parallel to ffn_up
  4846. };
  4847. enum llm_norm_type {
  4848. LLM_NORM,
  4849. LLM_NORM_RMS,
  4850. };
  4851. static struct ggml_tensor * llm_build_inp_embd(
  4852. struct ggml_context * ctx,
  4853. struct llama_context & lctx,
  4854. const llama_hparams & hparams,
  4855. const llama_batch & batch,
  4856. struct ggml_tensor * tok_embd,
  4857. const llm_build_cb & cb) {
  4858. const int64_t n_embd = hparams.n_embd;
  4859. struct ggml_tensor * inpL;
  4860. if (batch.token) {
  4861. lctx.inp_tokens = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, batch.n_tokens);
  4862. cb(lctx.inp_tokens, "inp_tokens", -1);
  4863. ggml_set_input(lctx.inp_tokens);
  4864. inpL = ggml_get_rows(ctx, tok_embd, lctx.inp_tokens);
  4865. } else {
  4866. #ifdef GGML_USE_MPI
  4867. GGML_ASSERT(false && "not implemented");
  4868. #endif
  4869. lctx.inp_embd = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, batch.n_tokens);
  4870. inpL = lctx.inp_embd;
  4871. ggml_set_input(lctx.inp_embd);
  4872. }
  4873. cb(inpL, "inp_embd", -1);
  4874. return inpL;
  4875. }
  4876. static void llm_build_kv_store(
  4877. struct ggml_context * ctx,
  4878. const llama_hparams & hparams,
  4879. const llama_kv_cache & kv,
  4880. struct ggml_cgraph * graph,
  4881. struct ggml_tensor * k_cur,
  4882. struct ggml_tensor * v_cur,
  4883. int64_t n_ctx,
  4884. int32_t n_tokens,
  4885. int32_t kv_head,
  4886. const llm_build_cb & cb,
  4887. int64_t il) {
  4888. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  4889. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  4890. GGML_ASSERT(kv.size == n_ctx);
  4891. // compute the transposed [n_tokens, n_embd] V matrix
  4892. assert(v_cur->ne[0] == n_embd_v_gqa && v_cur->ne[1] == n_tokens);
  4893. struct ggml_tensor * v_cur_t = ggml_transpose(ctx, v_cur);
  4894. cb(v_cur_t, "v_cur_t", il);
  4895. struct ggml_tensor * k_cache_view = ggml_view_1d(ctx, kv.k_l[il], n_tokens*n_embd_k_gqa,
  4896. (ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa))*kv_head);
  4897. cb(k_cache_view, "k_cache_view", il);
  4898. struct ggml_tensor * v_cache_view = ggml_view_2d(ctx, kv.v_l[il], n_tokens, n_embd_v_gqa,
  4899. ( n_ctx)*ggml_element_size(kv.v_l[il]),
  4900. (kv_head)*ggml_element_size(kv.v_l[il]));
  4901. cb(v_cache_view, "v_cache_view", il);
  4902. // important: storing RoPE-ed version of K in the KV cache!
  4903. ggml_build_forward_expand(graph, ggml_cpy(ctx, k_cur, k_cache_view));
  4904. ggml_build_forward_expand(graph, ggml_cpy(ctx, v_cur_t, v_cache_view));
  4905. }
  4906. static struct ggml_tensor * llm_build_norm(
  4907. struct ggml_context * ctx,
  4908. struct ggml_tensor * cur,
  4909. const llama_hparams & hparams,
  4910. struct ggml_tensor * mw,
  4911. struct ggml_tensor * mb,
  4912. llm_norm_type type,
  4913. const llm_build_cb & cb,
  4914. int il) {
  4915. switch (type) {
  4916. case LLM_NORM: cur = ggml_norm (ctx, cur, hparams.f_norm_eps); break;
  4917. case LLM_NORM_RMS: cur = ggml_rms_norm(ctx, cur, hparams.f_norm_rms_eps); break;
  4918. }
  4919. if (mw || mb) {
  4920. cb(cur, "norm", il);
  4921. }
  4922. if (mw) {
  4923. cur = ggml_mul(ctx, cur, mw);
  4924. if (mb) {
  4925. cb(cur, "norm_w", il);
  4926. }
  4927. }
  4928. if (mb) {
  4929. cur = ggml_add(ctx, cur, mb);
  4930. }
  4931. return cur;
  4932. }
  4933. static struct ggml_tensor * llm_build_ffn(
  4934. struct ggml_context * ctx,
  4935. struct ggml_tensor * cur,
  4936. struct ggml_tensor * up,
  4937. struct ggml_tensor * up_b,
  4938. struct ggml_tensor * gate,
  4939. struct ggml_tensor * gate_b,
  4940. struct ggml_tensor * down,
  4941. struct ggml_tensor * down_b,
  4942. struct ggml_tensor * act_scales,
  4943. llm_ffn_op_type type_op,
  4944. llm_ffn_gate_type type_gate,
  4945. const llm_build_cb & cb,
  4946. int il) {
  4947. struct ggml_tensor * tmp = ggml_mul_mat(ctx, up, cur);
  4948. cb(tmp, "ffn_up", il);
  4949. if (up_b) {
  4950. tmp = ggml_add(ctx, tmp, up_b);
  4951. cb(tmp, "ffn_up_b", il);
  4952. }
  4953. if (gate) {
  4954. switch (type_gate) {
  4955. case LLM_FFN_SEQ:
  4956. {
  4957. cur = ggml_mul_mat(ctx, gate, tmp);
  4958. cb(cur, "ffn_gate", il);
  4959. } break;
  4960. case LLM_FFN_PAR:
  4961. {
  4962. cur = ggml_mul_mat(ctx, gate, cur);
  4963. cb(cur, "ffn_gate", il);
  4964. } break;
  4965. }
  4966. if (gate_b) {
  4967. cur = ggml_add(ctx, cur, gate_b);
  4968. cb(cur, "ffn_gate_b", il);
  4969. }
  4970. } else {
  4971. cur = tmp;
  4972. }
  4973. switch (type_op) {
  4974. case LLM_FFN_SILU:
  4975. {
  4976. cur = ggml_silu(ctx, cur);
  4977. cb(cur, "ffn_silu", il);
  4978. } break;
  4979. case LLM_FFN_GELU:
  4980. {
  4981. cur = ggml_gelu(ctx, cur);
  4982. cb(cur, "ffn_gelu", il);
  4983. if (act_scales != NULL) {
  4984. cur = ggml_div(ctx, cur, act_scales);
  4985. cb(cur, "ffn_act", il);
  4986. }
  4987. } break;
  4988. case LLM_FFN_RELU:
  4989. {
  4990. cur = ggml_relu(ctx, cur);
  4991. cb(cur, "ffn_relu", il);
  4992. } break;
  4993. case LLM_FFN_RELU_SQR:
  4994. {
  4995. cur = ggml_relu(ctx, cur);
  4996. cb(cur, "ffn_relu", il);
  4997. cur = ggml_sqr(ctx, cur);
  4998. cb(cur, "ffn_sqr(relu)", il);
  4999. } break;
  5000. }
  5001. if (type_gate == LLM_FFN_PAR) {
  5002. cur = ggml_mul(ctx, cur, tmp);
  5003. cb(cur, "ffn_gate_par", il);
  5004. }
  5005. cur = ggml_mul_mat(ctx, down, cur);
  5006. if (down_b) {
  5007. cb(cur, "ffn_down", il);
  5008. }
  5009. if (down_b) {
  5010. cur = ggml_add(ctx, cur, down_b);
  5011. }
  5012. return cur;
  5013. }
  5014. // if max_alibi_bias > 0 then apply ALiBi
  5015. static struct ggml_tensor * llm_build_kqv(
  5016. struct ggml_context * ctx,
  5017. const llama_model & model,
  5018. const llama_hparams & hparams,
  5019. const llama_kv_cache & kv,
  5020. struct ggml_cgraph * graph,
  5021. struct ggml_tensor * wo,
  5022. struct ggml_tensor * wo_b,
  5023. struct ggml_tensor * q_cur,
  5024. struct ggml_tensor * kq_mask,
  5025. struct ggml_tensor * kq_pos,
  5026. int64_t n_ctx,
  5027. int32_t n_tokens,
  5028. int32_t n_kv,
  5029. float kq_scale,
  5030. const llm_build_cb & cb,
  5031. int il) {
  5032. const int64_t n_head = hparams.n_head;
  5033. const int64_t n_head_kv = hparams.n_head_kv;
  5034. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  5035. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  5036. const int64_t n_embd_head_v = hparams.n_embd_head_v;
  5037. struct ggml_tensor * q = ggml_permute(ctx, q_cur, 0, 2, 1, 3);
  5038. cb(q, "q", il);
  5039. struct ggml_tensor * k =
  5040. ggml_view_3d(ctx, kv.k_l[il],
  5041. n_embd_head_k, n_kv, n_head_kv,
  5042. ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa),
  5043. ggml_row_size(kv.k_l[il]->type, n_embd_head_k),
  5044. 0);
  5045. cb(k, "k", il);
  5046. struct ggml_tensor * kq = ggml_mul_mat(ctx, k, q);
  5047. cb(kq, "kq", il);
  5048. if (model.arch == LLM_ARCH_PHI2) {
  5049. // for this arch, we need to perform the KQ multiplication with F32 precision, otherwise we get NaNs
  5050. // ref: https://github.com/ggerganov/llama.cpp/pull/4490#issuecomment-1859055847
  5051. ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  5052. }
  5053. if (model.arch == LLM_ARCH_GROK) {
  5054. // need to do the following:
  5055. // multiply by attn_output_multiplyer of 0.08838834764831845
  5056. // and then :
  5057. // kq = 30 * tanh(kq / 30)
  5058. // before the softmax below
  5059. //try from phi2
  5060. //ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  5061. kq = ggml_tanh(ctx, ggml_scale(ctx, kq, 0.08838834764831845f/30.0f));
  5062. kq = ggml_scale(ctx, kq, 30);
  5063. }
  5064. #if defined(GGML_USE_KOMPUTE)
  5065. #pragma message("TODO: ALiBi support in ggml_soft_max_ext is not implemented for Kompute")
  5066. #pragma message(" Falling back to ggml_alibi(). Will become an error in Mar 2024")
  5067. #pragma message("ref: https://github.com/ggerganov/llama.cpp/pull/5488")
  5068. if (hparams.f_max_alibi_bias > 0.0f) {
  5069. kq = ggml_scale(ctx, kq, kq_scale);
  5070. cb(kq, "kq_scaled", il);
  5071. kq = ggml_alibi(ctx, kq, /*n_past*/ 0, n_head, hparams.f_max_alibi_bias);
  5072. cb(kq, "kq_scaled_alibi", il);
  5073. kq = ggml_add(ctx, kq, kq_mask);
  5074. cb(kq, "kq_masked", il);
  5075. kq = ggml_soft_max(ctx, kq);
  5076. cb(kq, "kq_soft_max", il);
  5077. } else
  5078. #endif
  5079. {
  5080. kq = ggml_soft_max_ext(ctx, kq, kq_mask, kq_pos, kq_scale, hparams.f_max_alibi_bias);
  5081. cb(kq, "kq_soft_max_ext", il);
  5082. }
  5083. GGML_ASSERT(kv.size == n_ctx);
  5084. // split cached v into n_head heads
  5085. struct ggml_tensor * v =
  5086. ggml_view_3d(ctx, kv.v_l[il],
  5087. n_kv, n_embd_head_v, n_head_kv,
  5088. ggml_element_size(kv.v_l[il])*n_ctx,
  5089. ggml_element_size(kv.v_l[il])*n_ctx*n_embd_head_v,
  5090. 0);
  5091. cb(v, "v", il);
  5092. struct ggml_tensor * kqv = ggml_mul_mat(ctx, v, kq);
  5093. cb(kqv, "kqv", il);
  5094. struct ggml_tensor * kqv_merged = ggml_permute(ctx, kqv, 0, 2, 1, 3);
  5095. cb(kqv_merged, "kqv_merged", il);
  5096. struct ggml_tensor * cur = ggml_cont_2d(ctx, kqv_merged, n_embd_head_k*n_head, n_tokens);
  5097. cb(cur, "kqv_merged_cont", il);
  5098. ggml_build_forward_expand(graph, cur);
  5099. cur = ggml_mul_mat(ctx, wo, cur);
  5100. if (wo_b) {
  5101. cb(cur, "kqv_wo", il);
  5102. }
  5103. if (wo_b) {
  5104. cur = ggml_add(ctx, cur, wo_b);
  5105. }
  5106. return cur;
  5107. }
  5108. static struct ggml_tensor * llm_build_kv(
  5109. struct ggml_context * ctx,
  5110. const llama_model & model,
  5111. const llama_hparams & hparams,
  5112. const llama_kv_cache & kv,
  5113. struct ggml_cgraph * graph,
  5114. struct ggml_tensor * wo,
  5115. struct ggml_tensor * wo_b,
  5116. struct ggml_tensor * k_cur,
  5117. struct ggml_tensor * v_cur,
  5118. struct ggml_tensor * q_cur,
  5119. struct ggml_tensor * kq_mask,
  5120. struct ggml_tensor * kq_pos,
  5121. int64_t n_ctx,
  5122. int32_t n_tokens,
  5123. int32_t kv_head,
  5124. int32_t n_kv,
  5125. float kq_scale,
  5126. const llm_build_cb & cb,
  5127. int il) {
  5128. // these nodes are added to the graph together so that they are not reordered
  5129. // by doing so, the number of splits in the graph is reduced
  5130. ggml_build_forward_expand(graph, q_cur);
  5131. ggml_build_forward_expand(graph, k_cur);
  5132. ggml_build_forward_expand(graph, v_cur);
  5133. llm_build_kv_store(ctx, hparams, kv, graph, k_cur, v_cur, n_ctx, n_tokens, kv_head, cb, il);
  5134. struct ggml_tensor * cur;
  5135. cur = llm_build_kqv(ctx, model, hparams, kv, graph, wo, wo_b,
  5136. q_cur, kq_mask, kq_pos, n_ctx, n_tokens, n_kv, kq_scale, cb, il);
  5137. cb(cur, "kqv_out", il);
  5138. return cur;
  5139. }
  5140. struct llm_build_context {
  5141. const llama_model & model;
  5142. llama_context & lctx;
  5143. const llama_hparams & hparams;
  5144. const llama_cparams & cparams;
  5145. const llama_batch & batch;
  5146. const llama_kv_cache & kv_self;
  5147. const int64_t n_embd;
  5148. const int64_t n_layer;
  5149. const int64_t n_rot;
  5150. const int64_t n_ctx; // user-specified context size (can be different from n_ctx_train)
  5151. const int64_t n_head;
  5152. const int64_t n_head_kv;
  5153. const int64_t n_embd_head_k;
  5154. const int64_t n_embd_k_gqa;
  5155. const int64_t n_embd_head_v;
  5156. const int64_t n_embd_v_gqa;
  5157. const int64_t n_expert;
  5158. const int64_t n_expert_used;
  5159. const float freq_base;
  5160. const float freq_scale;
  5161. const float ext_factor;
  5162. const float attn_factor;
  5163. const float beta_fast;
  5164. const float beta_slow;
  5165. const float norm_eps;
  5166. const float norm_rms_eps;
  5167. const int32_t n_tokens;
  5168. const int32_t n_kv; // size of KV cache to consider (n_kv <= kv_self.size)
  5169. const int32_t n_outputs;
  5170. const int32_t kv_head; // index of where we store new KV data in the cache
  5171. const int32_t n_orig_ctx;
  5172. const enum llama_pooling_type pooling_type;
  5173. const enum llama_rope_type rope_type;
  5174. const llm_build_cb & cb;
  5175. std::vector<uint8_t> & buf_compute_meta;
  5176. struct ggml_context * ctx0 = nullptr;
  5177. // TODO: consider making the entire interface noexcept
  5178. llm_build_context(
  5179. llama_context & lctx,
  5180. const llama_batch & batch,
  5181. const llm_build_cb & cb,
  5182. bool worst_case) :
  5183. model (lctx.model),
  5184. lctx (lctx),
  5185. hparams (model.hparams),
  5186. cparams (lctx.cparams),
  5187. batch (batch),
  5188. kv_self (lctx.kv_self),
  5189. n_embd (hparams.n_embd),
  5190. n_layer (hparams.n_layer),
  5191. n_rot (hparams.n_rot),
  5192. n_ctx (cparams.n_ctx),
  5193. n_head (hparams.n_head),
  5194. n_head_kv (hparams.n_head_kv),
  5195. n_embd_head_k (hparams.n_embd_head_k),
  5196. n_embd_k_gqa (hparams.n_embd_k_gqa()),
  5197. n_embd_head_v (hparams.n_embd_head_v),
  5198. n_embd_v_gqa (hparams.n_embd_v_gqa()),
  5199. n_expert (hparams.n_expert),
  5200. n_expert_used (hparams.n_expert_used),
  5201. freq_base (cparams.rope_freq_base),
  5202. freq_scale (cparams.rope_freq_scale),
  5203. ext_factor (cparams.yarn_ext_factor),
  5204. attn_factor (cparams.yarn_attn_factor),
  5205. beta_fast (cparams.yarn_beta_fast),
  5206. beta_slow (cparams.yarn_beta_slow),
  5207. norm_eps (hparams.f_norm_eps),
  5208. norm_rms_eps (hparams.f_norm_rms_eps),
  5209. n_tokens (batch.n_tokens),
  5210. n_kv (worst_case ? kv_self.size : kv_self.n),
  5211. n_outputs (worst_case ? n_tokens : lctx.n_outputs),
  5212. kv_head (worst_case ? (kv_self.recurrent ? 0 : kv_self.size - n_tokens) : kv_self.head),
  5213. n_orig_ctx (cparams.n_yarn_orig_ctx),
  5214. pooling_type (cparams.pooling_type),
  5215. rope_type (hparams.rope_type),
  5216. cb (cb),
  5217. buf_compute_meta (lctx.buf_compute_meta) {
  5218. // all initializations should be done in init()
  5219. }
  5220. void init() {
  5221. struct ggml_init_params params = {
  5222. /*.mem_size =*/ buf_compute_meta.size(),
  5223. /*.mem_buffer =*/ buf_compute_meta.data(),
  5224. /*.no_alloc =*/ true,
  5225. };
  5226. ctx0 = ggml_init(params);
  5227. lctx.inp_tokens = nullptr;
  5228. lctx.inp_embd = nullptr;
  5229. lctx.inp_pos = nullptr;
  5230. lctx.inp_out_ids = nullptr;
  5231. lctx.inp_KQ_mask = nullptr;
  5232. lctx.inp_KQ_pos = nullptr;
  5233. lctx.inp_K_shift = nullptr;
  5234. lctx.inp_mean = nullptr;
  5235. lctx.inp_cls = nullptr;
  5236. lctx.inp_s_copy = nullptr;
  5237. lctx.inp_s_mask = nullptr;
  5238. lctx.inp_s_seq = nullptr;
  5239. }
  5240. void free() {
  5241. if (ctx0) {
  5242. ggml_free(ctx0);
  5243. ctx0 = nullptr;
  5244. }
  5245. }
  5246. struct ggml_cgraph * build_k_shift() {
  5247. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5248. GGML_ASSERT(kv_self.size == n_ctx);
  5249. lctx.inp_K_shift = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_ctx);
  5250. cb(lctx.inp_K_shift, "K_shift", -1);
  5251. ggml_set_input(lctx.inp_K_shift);
  5252. for (int il = 0; il < n_layer; ++il) {
  5253. struct ggml_tensor * tmp =
  5254. // we rotate only the first n_rot dimensions
  5255. ggml_rope_custom_inplace(ctx0,
  5256. ggml_view_3d(ctx0, kv_self.k_l[il],
  5257. n_embd_head_k, n_head_kv, n_ctx,
  5258. ggml_row_size(kv_self.k_l[il]->type, n_embd_head_k),
  5259. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  5260. 0),
  5261. lctx.inp_K_shift, n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5262. ext_factor, attn_factor, beta_fast, beta_slow);
  5263. cb(tmp, "K_shifted", il);
  5264. ggml_build_forward_expand(gf, tmp);
  5265. }
  5266. return gf;
  5267. }
  5268. struct ggml_cgraph * build_s_copy() {
  5269. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5270. GGML_ASSERT(kv_self.recurrent);
  5271. struct ggml_tensor * state_copy = build_inp_s_copy();
  5272. for (int il = 0; il < n_layer; ++il) {
  5273. struct ggml_tensor * conv_states = ggml_reshape_2d(ctx0, kv_self.k_l[il], hparams.n_embd_k_s(), kv_self.size);
  5274. struct ggml_tensor * ssm_states = ggml_reshape_2d(ctx0, kv_self.v_l[il], hparams.n_embd_v_s(), kv_self.size);
  5275. conv_states = ggml_get_rows(ctx0, conv_states, state_copy);
  5276. ssm_states = ggml_get_rows(ctx0, ssm_states, state_copy);
  5277. // TODO: name the intermediate tensors with cb()
  5278. ggml_build_forward_expand(gf, ggml_cpy(ctx0, conv_states, kv_self.k_l[il]));
  5279. ggml_build_forward_expand(gf, ggml_cpy(ctx0, ssm_states, kv_self.v_l[il]));
  5280. }
  5281. return gf;
  5282. }
  5283. struct ggml_cgraph * build_defrag(const std::vector<uint32_t> & ids) {
  5284. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5285. for (uint32_t i = 0; i < ids.size(); ++i) {
  5286. const uint32_t id = ids[i];
  5287. if (i == id || id == ids.size()) {
  5288. continue;
  5289. }
  5290. uint32_t nm = 1;
  5291. while (i + nm < ids.size() && ids[i + nm] == id + nm) {
  5292. nm++;
  5293. }
  5294. for (int il = 0; il < n_layer; ++il) {
  5295. ggml_tensor * view_k_src = ggml_view_2d(ctx0, kv_self.k_l[il],
  5296. n_embd_k_gqa, nm,
  5297. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  5298. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*i));
  5299. ggml_tensor * view_k_dst = ggml_view_2d(ctx0, kv_self.k_l[il],
  5300. n_embd_k_gqa, nm,
  5301. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  5302. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*id));
  5303. ggml_tensor * view_v_src = ggml_view_2d(ctx0, kv_self.v_l[il],
  5304. nm, n_embd_v_gqa,
  5305. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  5306. ggml_row_size(kv_self.v_l[il]->type, i));
  5307. ggml_tensor * view_v_dst = ggml_view_2d(ctx0, kv_self.v_l[il],
  5308. nm, n_embd_v_gqa,
  5309. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  5310. ggml_row_size(kv_self.v_l[il]->type, id));
  5311. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_k_src, view_k_dst));
  5312. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_v_src, view_v_dst));
  5313. }
  5314. i += nm - 1;
  5315. }
  5316. //LLAMA_LOG_INFO("gf->n_nodes = %d\n", gf->n_nodes);
  5317. return gf;
  5318. }
  5319. struct ggml_tensor * build_inp_pos() {
  5320. lctx.inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  5321. cb(lctx.inp_pos, "inp_pos", -1);
  5322. ggml_set_input(lctx.inp_pos);
  5323. return lctx.inp_pos;
  5324. }
  5325. struct ggml_tensor * build_inp_out_ids() {
  5326. lctx.inp_out_ids = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_outputs);
  5327. cb(lctx.inp_out_ids, "inp_out_ids", -1);
  5328. ggml_set_input(lctx.inp_out_ids);
  5329. return lctx.inp_out_ids;
  5330. }
  5331. struct ggml_tensor * build_inp_KQ_mask(bool causal = true) {
  5332. if (causal) {
  5333. lctx.inp_KQ_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_kv, n_tokens);
  5334. } else {
  5335. lctx.inp_KQ_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, n_tokens);
  5336. }
  5337. cb(lctx.inp_KQ_mask, "KQ_mask", -1);
  5338. ggml_set_input(lctx.inp_KQ_mask);
  5339. return lctx.inp_KQ_mask;
  5340. }
  5341. struct ggml_tensor * build_inp_KQ_pos() {
  5342. lctx.inp_KQ_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, n_kv);
  5343. cb(lctx.inp_KQ_pos, "KQ_pos", -1);
  5344. ggml_set_input(lctx.inp_KQ_pos);
  5345. return lctx.inp_KQ_pos;
  5346. }
  5347. struct ggml_tensor * build_inp_mean() {
  5348. lctx.inp_mean = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, n_tokens);
  5349. cb(lctx.inp_mean, "inp_mean", -1);
  5350. ggml_set_input(lctx.inp_mean);
  5351. return lctx.inp_mean;
  5352. }
  5353. struct ggml_tensor * build_inp_cls() {
  5354. lctx.inp_cls = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  5355. cb(lctx.inp_cls, "inp_cls", -1);
  5356. ggml_set_input(lctx.inp_cls);
  5357. return lctx.inp_cls;
  5358. }
  5359. struct ggml_tensor * build_inp_s_copy() {
  5360. lctx.inp_s_copy = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, kv_self.size);
  5361. cb(lctx.inp_s_copy, "inp_s_copy", -1);
  5362. ggml_set_input(lctx.inp_s_copy);
  5363. return lctx.inp_s_copy;
  5364. }
  5365. struct ggml_tensor * build_inp_s_mask() {
  5366. lctx.inp_s_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, 1, n_kv);
  5367. cb(lctx.inp_s_mask, "inp_s_mask", -1);
  5368. ggml_set_input(lctx.inp_s_mask);
  5369. return lctx.inp_s_mask;
  5370. }
  5371. struct ggml_tensor * build_inp_s_seq() {
  5372. lctx.inp_s_seq = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_kv, n_tokens);
  5373. cb(lctx.inp_s_seq, "inp_s_seq", -1);
  5374. ggml_set_input(lctx.inp_s_seq);
  5375. return lctx.inp_s_seq;
  5376. }
  5377. struct ggml_cgraph * build_llama() {
  5378. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5379. // mutable variable, needed during the last layer of the computation to skip unused tokens
  5380. int32_t n_tokens = this->n_tokens;
  5381. const int64_t n_embd_head = hparams.n_embd_head_v;
  5382. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5383. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5384. struct ggml_tensor * cur;
  5385. struct ggml_tensor * inpL;
  5386. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5387. // inp_pos - contains the positions
  5388. struct ggml_tensor * inp_pos = build_inp_pos();
  5389. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5390. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5391. for (int il = 0; il < n_layer; ++il) {
  5392. struct ggml_tensor * inpSA = inpL;
  5393. // norm
  5394. cur = llm_build_norm(ctx0, inpL, hparams,
  5395. model.layers[il].attn_norm, NULL,
  5396. LLM_NORM_RMS, cb, il);
  5397. cb(cur, "attn_norm", il);
  5398. // self-attention
  5399. {
  5400. // compute Q and K and RoPE them
  5401. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5402. cb(Qcur, "Qcur", il);
  5403. if (model.layers[il].bq) {
  5404. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5405. cb(Qcur, "Qcur", il);
  5406. }
  5407. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5408. cb(Kcur, "Kcur", il);
  5409. if (model.layers[il].bk) {
  5410. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5411. cb(Kcur, "Kcur", il);
  5412. }
  5413. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5414. cb(Vcur, "Vcur", il);
  5415. if (model.layers[il].bv) {
  5416. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  5417. cb(Vcur, "Vcur", il);
  5418. }
  5419. Qcur = ggml_rope_custom(
  5420. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5421. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5422. ext_factor, attn_factor, beta_fast, beta_slow
  5423. );
  5424. cb(Qcur, "Qcur", il);
  5425. Kcur = ggml_rope_custom(
  5426. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5427. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5428. ext_factor, attn_factor, beta_fast, beta_slow
  5429. );
  5430. cb(Kcur, "Kcur", il);
  5431. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5432. model.layers[il].wo, model.layers[il].bo,
  5433. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5434. }
  5435. if (il == n_layer - 1) {
  5436. // skip computing output for unused tokens
  5437. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  5438. n_tokens = n_outputs;
  5439. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  5440. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  5441. }
  5442. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5443. cb(ffn_inp, "ffn_inp", il);
  5444. // feed-forward network
  5445. if (model.layers[il].ffn_gate_inp == nullptr) {
  5446. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5447. model.layers[il].ffn_norm, NULL,
  5448. LLM_NORM_RMS, cb, il);
  5449. cb(cur, "ffn_norm", il);
  5450. cur = llm_build_ffn(ctx0, cur,
  5451. model.layers[il].ffn_up, NULL,
  5452. model.layers[il].ffn_gate, NULL,
  5453. model.layers[il].ffn_down, NULL,
  5454. NULL,
  5455. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5456. cb(cur, "ffn_out", il);
  5457. } else {
  5458. // MoE branch
  5459. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5460. model.layers[il].ffn_norm, NULL,
  5461. LLM_NORM_RMS, cb, il);
  5462. cb(cur, "ffn_norm", il);
  5463. ggml_tensor * logits = ggml_mul_mat(ctx0, model.layers[il].ffn_gate_inp, cur); // [n_tokens, num_experts]
  5464. cb(logits, "ffn_moe_logits", il);
  5465. ggml_tensor * probs = ggml_soft_max(ctx0, logits); // [n_tokens, num_experts]
  5466. cb(probs, "ffn_moe_probs", il);
  5467. // select experts
  5468. ggml_tensor * selected_experts = ggml_top_k(ctx0, probs, n_expert_used); // [n_tokens, num_experts_per_tok]
  5469. cb(selected_experts->src[0], "ffn_moe_argsort", il);
  5470. ggml_tensor * weights = ggml_get_rows(ctx0,
  5471. ggml_reshape_3d(ctx0, probs, 1, n_expert, n_tokens), selected_experts);
  5472. cb(weights, "ffn_moe_weights", il);
  5473. weights = ggml_reshape_2d(ctx0, weights, n_expert_used, n_tokens); // [n_tokens, num_experts_per_tok]
  5474. ggml_tensor * weights_sum = ggml_sum_rows(ctx0, weights);
  5475. cb(weights_sum, "ffn_moe_weights_sum", il);
  5476. weights = ggml_div(ctx0, weights, weights_sum); // [n_tokens, num_experts_per_tok]
  5477. cb(weights, "ffn_moe_weights_norm", il);
  5478. // compute expert outputs
  5479. ggml_tensor * moe_out = nullptr;
  5480. for (int i = 0; i < n_expert_used; ++i) {
  5481. ggml_tensor * cur_expert;
  5482. ggml_tensor * cur_up = ggml_mul_mat_id(ctx0, model.layers[il].ffn_up_exps, selected_experts, i, cur);
  5483. cb(cur_up, "ffn_moe_up", il);
  5484. ggml_tensor * cur_gate = ggml_mul_mat_id(ctx0, model.layers[il].ffn_gate_exps, selected_experts, i, cur);
  5485. cb(cur_gate, "ffn_moe_gate", il);
  5486. cur_gate = ggml_silu(ctx0, cur_gate);
  5487. cb(cur_gate, "ffn_moe_silu", il);
  5488. cur_expert = ggml_mul(ctx0, cur_up, cur_gate);
  5489. cb(cur_expert, "ffn_moe_gate_par", il);
  5490. cur_expert = ggml_mul_mat_id(ctx0, model.layers[il].ffn_down_exps, selected_experts, i, cur_expert); // [n_tokens, n_embd]
  5491. cb(cur_expert, "ffn_moe_down", il);
  5492. cur_expert = ggml_mul(ctx0, cur_expert,
  5493. ggml_view_2d(ctx0, weights, 1, n_tokens, weights->nb[1], i*weights->nb[0]));
  5494. cb(cur_expert, "ffn_moe_weighted", il);
  5495. if (i == 0) {
  5496. moe_out = cur_expert;
  5497. } else {
  5498. moe_out = ggml_add(ctx0, moe_out, cur_expert);
  5499. cb(moe_out, "ffn_moe_out", il);
  5500. }
  5501. }
  5502. cur = moe_out;
  5503. }
  5504. cur = ggml_add(ctx0, cur, ffn_inp);
  5505. cb(cur, "ffn_out", il);
  5506. ggml_tensor * layer_dir = lctx.cvec.tensor_for(il);
  5507. if (layer_dir != nullptr) {
  5508. cur = ggml_add(ctx0, cur, layer_dir);
  5509. }
  5510. cb(cur, "l_out", il);
  5511. // input for next layer
  5512. inpL = cur;
  5513. }
  5514. cur = inpL;
  5515. cur = llm_build_norm(ctx0, cur, hparams,
  5516. model.output_norm, NULL,
  5517. LLM_NORM_RMS, cb, -1);
  5518. cb(cur, "result_norm", -1);
  5519. // lm_head
  5520. cur = ggml_mul_mat(ctx0, model.output, cur);
  5521. cb(cur, "result_output", -1);
  5522. ggml_build_forward_expand(gf, cur);
  5523. return gf;
  5524. }
  5525. struct ggml_cgraph * build_baichuan() {
  5526. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5527. const int64_t n_embd_head = hparams.n_embd_head_v;
  5528. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5529. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5530. struct ggml_tensor * cur;
  5531. struct ggml_tensor * inpL;
  5532. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5533. // inp_pos - contains the positions
  5534. struct ggml_tensor * inp_pos = model.type == MODEL_7B ? build_inp_pos() : nullptr;
  5535. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5536. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5537. // positions of the tokens in the KV cache
  5538. struct ggml_tensor * KQ_pos = build_inp_KQ_pos();
  5539. for (int il = 0; il < n_layer; ++il) {
  5540. struct ggml_tensor * inpSA = inpL;
  5541. cur = llm_build_norm(ctx0, inpL, hparams,
  5542. model.layers[il].attn_norm, NULL,
  5543. LLM_NORM_RMS, cb, il);
  5544. cb(cur, "attn_norm", il);
  5545. // self-attention
  5546. {
  5547. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5548. cb(Qcur, "Qcur", il);
  5549. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5550. cb(Kcur, "Kcur", il);
  5551. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5552. cb(Vcur, "Vcur", il);
  5553. switch (model.type) {
  5554. case MODEL_7B:
  5555. Qcur = ggml_rope_custom(
  5556. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5557. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5558. ext_factor, attn_factor, beta_fast, beta_slow
  5559. );
  5560. Kcur = ggml_rope_custom(
  5561. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5562. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5563. ext_factor, attn_factor, beta_fast, beta_slow
  5564. );
  5565. break;
  5566. case MODEL_13B:
  5567. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd/n_head, n_head, n_tokens);
  5568. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd/n_head, n_head, n_tokens);
  5569. break;
  5570. default:
  5571. GGML_ASSERT(false);
  5572. }
  5573. cb(Qcur, "Qcur", il);
  5574. cb(Kcur, "Kcur", il);
  5575. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5576. model.layers[il].wo, NULL,
  5577. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5578. }
  5579. if (il == n_layer - 1) {
  5580. // skip computing output for unused tokens
  5581. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  5582. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  5583. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  5584. }
  5585. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5586. cb(ffn_inp, "ffn_inp", il);
  5587. // feed-forward network
  5588. {
  5589. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5590. model.layers[il].ffn_norm, NULL,
  5591. LLM_NORM_RMS, cb, il);
  5592. cb(cur, "ffn_norm", il);
  5593. cur = llm_build_ffn(ctx0, cur,
  5594. model.layers[il].ffn_up, NULL,
  5595. model.layers[il].ffn_gate, NULL,
  5596. model.layers[il].ffn_down, NULL,
  5597. NULL,
  5598. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5599. cb(cur, "ffn_out", il);
  5600. }
  5601. cur = ggml_add(ctx0, cur, ffn_inp);
  5602. cb(cur, "l_out", il);
  5603. // input for next layer
  5604. inpL = cur;
  5605. }
  5606. cur = inpL;
  5607. cur = llm_build_norm(ctx0, cur, hparams,
  5608. model.output_norm, NULL,
  5609. LLM_NORM_RMS, cb, -1);
  5610. cb(cur, "result_norm", -1);
  5611. // lm_head
  5612. cur = ggml_mul_mat(ctx0, model.output, cur);
  5613. cb(cur, "result_output", -1);
  5614. ggml_build_forward_expand(gf, cur);
  5615. return gf;
  5616. }
  5617. struct ggml_cgraph * build_xverse() {
  5618. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5619. const int64_t n_embd_head = hparams.n_embd_head_v;
  5620. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5621. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5622. struct ggml_tensor * cur;
  5623. struct ggml_tensor * inpL;
  5624. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5625. // inp_pos - contains the positions
  5626. struct ggml_tensor * inp_pos = build_inp_pos();
  5627. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5628. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5629. // positions of the tokens in the KV cache
  5630. struct ggml_tensor * KQ_pos = build_inp_KQ_pos();
  5631. for (int il = 0; il < n_layer; ++il) {
  5632. struct ggml_tensor * inpSA = inpL;
  5633. cur = llm_build_norm(ctx0, inpL, hparams,
  5634. model.layers[il].attn_norm, NULL,
  5635. LLM_NORM_RMS, cb, il);
  5636. cb(cur, "attn_norm", il);
  5637. // self-attention
  5638. {
  5639. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5640. cb(Qcur, "Qcur", il);
  5641. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5642. cb(Kcur, "Kcur", il);
  5643. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5644. cb(Vcur, "Vcur", il);
  5645. Qcur = ggml_rope_custom(
  5646. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5647. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5648. ext_factor, attn_factor, beta_fast, beta_slow
  5649. );
  5650. cb(Qcur, "Qcur", il);
  5651. Kcur = ggml_rope_custom(
  5652. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5653. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5654. ext_factor, attn_factor, beta_fast, beta_slow
  5655. );
  5656. cb(Kcur, "Kcur", il);
  5657. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5658. model.layers[il].wo, NULL,
  5659. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5660. }
  5661. if (il == n_layer - 1) {
  5662. // skip computing output for unused tokens
  5663. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  5664. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  5665. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  5666. }
  5667. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5668. cb(ffn_inp, "ffn_inp", il);
  5669. // feed-forward network
  5670. {
  5671. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5672. model.layers[il].ffn_norm, NULL,
  5673. LLM_NORM_RMS, cb, il);
  5674. cb(cur, "ffn_norm", il);
  5675. cur = llm_build_ffn(ctx0, cur,
  5676. model.layers[il].ffn_up, NULL,
  5677. model.layers[il].ffn_gate, NULL,
  5678. model.layers[il].ffn_down, NULL,
  5679. NULL,
  5680. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5681. cb(cur, "ffn_out", il);
  5682. }
  5683. cur = ggml_add(ctx0, cur, ffn_inp);
  5684. cb(cur, "l_out", il);
  5685. // input for next layer
  5686. inpL = cur;
  5687. }
  5688. cur = inpL;
  5689. cur = llm_build_norm(ctx0, cur, hparams, model.output_norm, NULL, LLM_NORM_RMS, cb, -1);
  5690. cb(cur, "result_norm", -1);
  5691. // lm_head
  5692. cur = ggml_mul_mat(ctx0, model.output, cur);
  5693. cb(cur, "result_output", -1);
  5694. ggml_build_forward_expand(gf, cur);
  5695. return gf;
  5696. }
  5697. struct ggml_cgraph * build_falcon() {
  5698. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5699. const int64_t n_embd_head = hparams.n_embd_head_v;
  5700. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5701. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5702. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5703. struct ggml_tensor * cur;
  5704. struct ggml_tensor * inpL;
  5705. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5706. // inp_pos - contains the positions
  5707. struct ggml_tensor * inp_pos = build_inp_pos();
  5708. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5709. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5710. for (int il = 0; il < n_layer; ++il) {
  5711. struct ggml_tensor * attn_norm;
  5712. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  5713. model.layers[il].attn_norm,
  5714. model.layers[il].attn_norm_b,
  5715. LLM_NORM, cb, il);
  5716. cb(attn_norm, "attn_norm", il);
  5717. // self-attention
  5718. {
  5719. if (model.layers[il].attn_norm_2) {
  5720. // Falcon-40B
  5721. cur = llm_build_norm(ctx0, inpL, hparams,
  5722. model.layers[il].attn_norm_2,
  5723. model.layers[il].attn_norm_2_b,
  5724. LLM_NORM, cb, il);
  5725. cb(cur, "attn_norm_2", il);
  5726. } else {
  5727. cur = attn_norm;
  5728. }
  5729. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5730. cb(cur, "wqkv", il);
  5731. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5732. 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)));
  5733. 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)));
  5734. cb(Qcur, "Qcur", il);
  5735. cb(Kcur, "Kcur", il);
  5736. cb(Vcur, "Vcur", il);
  5737. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5738. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  5739. // using mode = 2 for neox mode
  5740. Qcur = ggml_rope_custom(
  5741. ctx0, Qcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5742. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5743. );
  5744. cb(Qcur, "Qcur", il);
  5745. Kcur = ggml_rope_custom(
  5746. ctx0, Kcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5747. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5748. );
  5749. cb(Kcur, "Kcur", il);
  5750. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5751. model.layers[il].wo, NULL,
  5752. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5753. }
  5754. if (il == n_layer - 1) {
  5755. // skip computing output for unused tokens
  5756. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  5757. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  5758. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  5759. attn_norm = ggml_get_rows(ctx0, attn_norm, inp_out_ids);
  5760. }
  5761. struct ggml_tensor * ffn_inp = cur;
  5762. // feed forward
  5763. {
  5764. cur = llm_build_ffn(ctx0, attn_norm, // !! use the attn norm, not the result
  5765. model.layers[il].ffn_up, NULL,
  5766. NULL, NULL,
  5767. model.layers[il].ffn_down, NULL,
  5768. NULL,
  5769. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5770. cb(cur, "ffn_out", il);
  5771. }
  5772. cur = ggml_add(ctx0, cur, ffn_inp);
  5773. cb(cur, "l_out", il);
  5774. cur = ggml_add(ctx0, cur, inpL);
  5775. cb(cur, "l_out", il);
  5776. // input for next layer
  5777. inpL = cur;
  5778. }
  5779. cur = inpL;
  5780. // norm
  5781. cur = llm_build_norm(ctx0, cur, hparams,
  5782. model.output_norm,
  5783. model.output_norm_b,
  5784. LLM_NORM, cb, -1);
  5785. cb(cur, "result_norm", -1);
  5786. cur = ggml_mul_mat(ctx0, model.output, cur);
  5787. cb(cur, "result_output", -1);
  5788. ggml_build_forward_expand(gf, cur);
  5789. return gf;
  5790. }
  5791. struct ggml_cgraph * build_grok() {
  5792. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5793. // mutable variable, needed during the last layer of the computation to skip unused tokens
  5794. int32_t n_tokens = this->n_tokens;
  5795. const int64_t n_embd_head = hparams.n_embd_head_v;
  5796. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5797. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5798. struct ggml_tensor * cur;
  5799. struct ggml_tensor * inpL;
  5800. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5801. // multiply by embedding_multiplier_scale of 78.38367176906169
  5802. inpL = ggml_scale(ctx0, inpL, 78.38367176906169f);
  5803. // inp_pos - contains the positions
  5804. struct ggml_tensor * inp_pos = build_inp_pos();
  5805. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5806. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5807. for (int il = 0; il < n_layer; ++il) {
  5808. struct ggml_tensor * inpSA = inpL;
  5809. // norm
  5810. cur = llm_build_norm(ctx0, inpL, hparams,
  5811. model.layers[il].attn_norm, NULL,
  5812. LLM_NORM_RMS, cb, il);
  5813. cb(cur, "attn_norm", il);
  5814. // self-attention
  5815. {
  5816. // compute Q and K and RoPE them
  5817. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5818. cb(Qcur, "Qcur", il);
  5819. if (model.layers[il].bq) {
  5820. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5821. cb(Qcur, "Qcur", il);
  5822. }
  5823. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5824. cb(Kcur, "Kcur", il);
  5825. if (model.layers[il].bk) {
  5826. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5827. cb(Kcur, "Kcur", il);
  5828. }
  5829. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5830. cb(Vcur, "Vcur", il);
  5831. if (model.layers[il].bv) {
  5832. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  5833. cb(Vcur, "Vcur", il);
  5834. }
  5835. Qcur = ggml_rope_custom(
  5836. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5837. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5838. ext_factor, attn_factor, beta_fast, beta_slow
  5839. );
  5840. cb(Qcur, "Qcur", il);
  5841. Kcur = ggml_rope_custom(
  5842. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5843. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5844. ext_factor, attn_factor, beta_fast, beta_slow
  5845. );
  5846. cb(Kcur, "Kcur", il);
  5847. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5848. model.layers[il].wo, model.layers[il].bo,
  5849. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  5850. }
  5851. if (il == n_layer - 1) {
  5852. // skip computing output for unused tokens
  5853. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  5854. n_tokens = n_outputs;
  5855. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  5856. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  5857. }
  5858. // Grok
  5859. // if attn_out_norm is present then apply it before adding the input
  5860. if (model.layers[il].attn_out_norm) {
  5861. cur = llm_build_norm(ctx0, cur, hparams,
  5862. model.layers[il].attn_out_norm, NULL,
  5863. LLM_NORM_RMS, cb, il);
  5864. cb(cur, "attn_out_norm", il);
  5865. }
  5866. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5867. cb(ffn_inp, "ffn_inp", il);
  5868. // feed-forward network
  5869. // MoE branch
  5870. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5871. model.layers[il].ffn_norm, NULL,
  5872. LLM_NORM_RMS, cb, il);
  5873. cb(cur, "ffn_norm", il);
  5874. ggml_tensor * logits = ggml_mul_mat(ctx0, model.layers[il].ffn_gate_inp, cur); // [n_tokens, num_experts]
  5875. cb(logits, "ffn_moe_logits", il);
  5876. ggml_tensor * probs = ggml_soft_max(ctx0, logits); // [n_tokens, num_experts]
  5877. cb(probs, "ffn_moe_probs", il);
  5878. // select experts
  5879. ggml_tensor * selected_experts = ggml_top_k(ctx0, probs, n_expert_used); // [n_tokens, num_experts_per_tok]
  5880. cb(selected_experts->src[0], "ffn_moe_argsort", il);
  5881. ggml_tensor * weights = ggml_get_rows(ctx0,
  5882. ggml_reshape_3d(ctx0, probs, 1, n_expert, n_tokens), selected_experts);
  5883. cb(weights, "ffn_moe_weights", il);
  5884. weights = ggml_reshape_2d(ctx0, weights, n_expert_used, n_tokens); // [n_tokens, num_experts_per_tok]
  5885. ggml_tensor * weights_sum = ggml_sum_rows(ctx0, weights);
  5886. cb(weights_sum, "ffn_moe_weights_sum", il);
  5887. weights = ggml_div(ctx0, weights, weights_sum); // [n_tokens, num_experts_per_tok]
  5888. cb(weights, "ffn_moe_weights_norm", il);
  5889. // compute expert outputs
  5890. ggml_tensor * moe_out = nullptr;
  5891. for (int i = 0; i < n_expert_used; ++i) {
  5892. ggml_tensor * cur_expert;
  5893. ggml_tensor * cur_up = ggml_mul_mat_id(ctx0, model.layers[il].ffn_up_exps, selected_experts, i, cur);
  5894. cb(cur_up, "ffn_moe_up", il);
  5895. ggml_tensor * cur_gate = ggml_mul_mat_id(ctx0, model.layers[il].ffn_gate_exps, selected_experts, i, cur);
  5896. cb(cur_gate, "ffn_moe_gate", il);
  5897. //GeLU
  5898. cur_gate = ggml_gelu(ctx0, cur_gate);
  5899. cb(cur_gate, "ffn_moe_gelu", il);
  5900. cur_expert = ggml_mul(ctx0, cur_up, cur_gate);
  5901. cb(cur_expert, "ffn_moe_gate_par", il);
  5902. cur_expert = ggml_mul_mat_id(ctx0, model.layers[il].ffn_down_exps, selected_experts, i, cur_expert); // [n_tokens, n_embd]
  5903. cb(cur_expert, "ffn_moe_down", il);
  5904. cur_expert = ggml_mul(ctx0, cur_expert,
  5905. ggml_view_2d(ctx0, weights, 1, n_tokens, weights->nb[1], i*weights->nb[0]));
  5906. cb(cur_expert, "ffn_moe_weighted", il);
  5907. if (i == 0) {
  5908. moe_out = cur_expert;
  5909. } else {
  5910. moe_out = ggml_add(ctx0, moe_out, cur_expert);
  5911. cb(moe_out, "ffn_moe_out", il);
  5912. }
  5913. }
  5914. cur = moe_out;
  5915. // Grok
  5916. // if layer_out_norm is present then apply it before adding the input
  5917. // Idea: maybe ffn_out_norm is a better name
  5918. if (model.layers[il].layer_out_norm) {
  5919. cur = llm_build_norm(ctx0, cur, hparams,
  5920. model.layers[il].layer_out_norm, NULL,
  5921. LLM_NORM_RMS, cb, il);
  5922. cb(cur, "layer_out_norm", il);
  5923. }
  5924. cur = ggml_add(ctx0, cur, ffn_inp);
  5925. cb(cur, "ffn_out", il);
  5926. ggml_tensor * layer_dir = lctx.cvec.tensor_for(il);
  5927. if (layer_dir != nullptr) {
  5928. cur = ggml_add(ctx0, cur, layer_dir);
  5929. }
  5930. cb(cur, "l_out", il);
  5931. // input for next layer
  5932. inpL = cur;
  5933. }
  5934. cur = inpL;
  5935. cur = llm_build_norm(ctx0, cur, hparams,
  5936. model.output_norm, NULL,
  5937. LLM_NORM_RMS, cb, -1);
  5938. cb(cur, "result_norm", -1);
  5939. // lm_head
  5940. cur = ggml_mul_mat(ctx0, model.output, cur);
  5941. // Grok
  5942. // multiply logits by output_multiplier_scale of 0.5773502691896257
  5943. cur = ggml_scale(ctx0, cur, 0.5773502691896257f);
  5944. cb(cur, "result_output", -1);
  5945. ggml_build_forward_expand(gf, cur);
  5946. return gf;
  5947. }
  5948. struct ggml_cgraph * build_starcoder() {
  5949. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5950. const int64_t n_embd_head = hparams.n_embd_head_v;
  5951. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5952. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5953. struct ggml_tensor * cur;
  5954. struct ggml_tensor * inpL;
  5955. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5956. // inp_pos - contains the positions
  5957. struct ggml_tensor * inp_pos = build_inp_pos();
  5958. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5959. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5960. struct ggml_tensor * pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  5961. cb(pos, "pos_embd", -1);
  5962. inpL = ggml_add(ctx0, inpL, pos);
  5963. cb(inpL, "inpL", -1);
  5964. for (int il = 0; il < n_layer; ++il) {
  5965. cur = llm_build_norm(ctx0, inpL, hparams,
  5966. model.layers[il].attn_norm,
  5967. model.layers[il].attn_norm_b,
  5968. LLM_NORM, cb, il);
  5969. cb(cur, "attn_norm", il);
  5970. // self-attention
  5971. {
  5972. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5973. cb(cur, "wqkv", il);
  5974. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5975. cb(cur, "bqkv", il);
  5976. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5977. 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)));
  5978. 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)));
  5979. cb(Qcur, "Qcur", il);
  5980. cb(Kcur, "Kcur", il);
  5981. cb(Vcur, "Vcur", il);
  5982. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5983. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5984. model.layers[il].wo, model.layers[il].bo,
  5985. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5986. }
  5987. if (il == n_layer - 1) {
  5988. // skip computing output for unused tokens
  5989. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  5990. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  5991. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  5992. }
  5993. // add the input
  5994. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5995. cb(ffn_inp, "ffn_inp", il);
  5996. // FF
  5997. {
  5998. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5999. model.layers[il].ffn_norm,
  6000. model.layers[il].ffn_norm_b,
  6001. LLM_NORM, cb, il);
  6002. cb(cur, "ffn_norm", il);
  6003. cur = llm_build_ffn(ctx0, cur,
  6004. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6005. NULL, NULL,
  6006. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6007. NULL,
  6008. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6009. cb(cur, "ffn_out", il);
  6010. }
  6011. inpL = ggml_add(ctx0, cur, ffn_inp);
  6012. cb(inpL, "l_out", il);
  6013. }
  6014. cur = llm_build_norm(ctx0, inpL, hparams,
  6015. model.output_norm,
  6016. model.output_norm_b,
  6017. LLM_NORM, cb, -1);
  6018. cb(cur, "result_norm", -1);
  6019. cur = ggml_mul_mat(ctx0, model.output, cur);
  6020. cb(cur, "result_output", -1);
  6021. ggml_build_forward_expand(gf, cur);
  6022. return gf;
  6023. }
  6024. struct ggml_cgraph * build_persimmon() {
  6025. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6026. const int64_t n_embd_head = hparams.n_embd_head_v;
  6027. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6028. GGML_ASSERT(n_embd_head/2 == hparams.n_rot);
  6029. struct ggml_tensor * cur;
  6030. struct ggml_tensor * inpL;
  6031. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6032. // inp_pos - contains the positions
  6033. struct ggml_tensor * inp_pos = build_inp_pos();
  6034. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6035. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6036. for (int il = 0; il < n_layer; ++il) {
  6037. struct ggml_tensor * residual = inpL;
  6038. cur = llm_build_norm(ctx0, inpL, hparams,
  6039. model.layers[il].attn_norm,
  6040. model.layers[il].attn_norm_b,
  6041. LLM_NORM, cb, il);
  6042. cb(cur, "attn_norm", il);
  6043. // self attention
  6044. {
  6045. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6046. cb(cur, "wqkv", il);
  6047. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6048. cb(cur, "bqkv", il);
  6049. // split qkv
  6050. GGML_ASSERT(n_head_kv == n_head);
  6051. struct ggml_tensor * tmpqkv = ggml_reshape_4d(ctx0, cur, n_embd_head, 3, n_head, n_tokens);
  6052. cb(tmpqkv, "tmpqkv", il);
  6053. struct ggml_tensor * tmpqkv_perm = ggml_cont(ctx0, ggml_permute(ctx0, tmpqkv, 0, 3, 1, 2));
  6054. cb(tmpqkv_perm, "tmpqkv", il);
  6055. struct ggml_tensor * tmpq = ggml_view_3d(
  6056. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  6057. ggml_element_size(tmpqkv_perm) * n_embd_head,
  6058. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  6059. 0
  6060. );
  6061. cb(tmpq, "tmpq", il);
  6062. struct ggml_tensor * tmpk = ggml_view_3d(
  6063. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  6064. ggml_element_size(tmpqkv_perm) * n_embd_head,
  6065. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  6066. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens
  6067. );
  6068. cb(tmpk, "tmpk", il);
  6069. // Q/K Layernorm
  6070. tmpq = llm_build_norm(ctx0, tmpq, hparams,
  6071. model.layers[il].attn_q_norm,
  6072. model.layers[il].attn_q_norm_b,
  6073. LLM_NORM, cb, il);
  6074. cb(tmpq, "tmpq", il);
  6075. tmpk = llm_build_norm(ctx0, tmpk, hparams,
  6076. model.layers[il].attn_k_norm,
  6077. model.layers[il].attn_k_norm_b,
  6078. LLM_NORM, cb, il);
  6079. cb(tmpk, "tmpk", il);
  6080. // RoPE the first n_rot of q/k, pass the other half, and concat.
  6081. struct ggml_tensor * qrot = ggml_view_3d(
  6082. ctx0, tmpq, n_rot, n_head, n_tokens,
  6083. ggml_element_size(tmpq) * n_embd_head,
  6084. ggml_element_size(tmpq) * n_embd_head * n_head,
  6085. 0
  6086. );
  6087. cb(qrot, "qrot", il);
  6088. struct ggml_tensor * krot = ggml_view_3d(
  6089. ctx0, tmpk, n_rot, n_head, n_tokens,
  6090. ggml_element_size(tmpk) * n_embd_head,
  6091. ggml_element_size(tmpk) * n_embd_head * n_head,
  6092. 0
  6093. );
  6094. cb(krot, "krot", il);
  6095. // get the second half of tmpq, e.g tmpq[n_rot:, :, :]
  6096. struct ggml_tensor * qpass = ggml_view_3d(
  6097. ctx0, tmpq, n_rot, n_head, n_tokens,
  6098. ggml_element_size(tmpq) * n_embd_head,
  6099. ggml_element_size(tmpq) * n_embd_head * n_head,
  6100. ggml_element_size(tmpq) * n_rot
  6101. );
  6102. cb(qpass, "qpass", il);
  6103. struct ggml_tensor * kpass = ggml_view_3d(
  6104. ctx0, tmpk, n_rot, n_head, n_tokens,
  6105. ggml_element_size(tmpk) * n_embd_head,
  6106. ggml_element_size(tmpk) * n_embd_head * n_head,
  6107. ggml_element_size(tmpk) * n_rot
  6108. );
  6109. cb(kpass, "kpass", il);
  6110. struct ggml_tensor * qrotated = ggml_rope_custom(
  6111. ctx0, qrot, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  6112. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  6113. );
  6114. cb(qrotated, "qrotated", il);
  6115. struct ggml_tensor * krotated = ggml_rope_custom(
  6116. ctx0, krot, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  6117. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  6118. );
  6119. cb(krotated, "krotated", il);
  6120. // ggml currently only supports concatenation on dim=2
  6121. // so we need to permute qrot, qpass, concat, then permute back.
  6122. qrotated = ggml_cont(ctx0, ggml_permute(ctx0, qrotated, 2, 1, 0, 3));
  6123. cb(qrotated, "qrotated", il);
  6124. krotated = ggml_cont(ctx0, ggml_permute(ctx0, krotated, 2, 1, 0, 3));
  6125. cb(krotated, "krotated", il);
  6126. qpass = ggml_cont(ctx0, ggml_permute(ctx0, qpass, 2, 1, 0, 3));
  6127. cb(qpass, "qpass", il);
  6128. kpass = ggml_cont(ctx0, ggml_permute(ctx0, kpass, 2, 1, 0, 3));
  6129. cb(kpass, "kpass", il);
  6130. struct ggml_tensor * Qcur = ggml_concat(ctx0, qrotated, qpass);
  6131. cb(Qcur, "Qcur", il);
  6132. struct ggml_tensor * Kcur = ggml_concat(ctx0, krotated, kpass);
  6133. cb(Kcur, "Kcur", il);
  6134. struct ggml_tensor * Q = ggml_cont(ctx0, ggml_permute(ctx0, Qcur, 2, 1, 0, 3));
  6135. cb(Q, "Q", il);
  6136. Kcur = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 2, 1, 0, 3));
  6137. cb(Kcur, "Kcur", il);
  6138. struct ggml_tensor * Vcur = ggml_view_3d(
  6139. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  6140. ggml_element_size(tmpqkv_perm) * n_embd_head,
  6141. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  6142. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens * 2
  6143. );
  6144. cb(Vcur, "Vcur", il);
  6145. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6146. model.layers[il].wo, model.layers[il].bo,
  6147. Kcur, Vcur, Q, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6148. }
  6149. if (il == n_layer - 1) {
  6150. // skip computing output for unused tokens
  6151. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6152. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6153. residual = ggml_get_rows(ctx0, residual, inp_out_ids);
  6154. }
  6155. struct ggml_tensor * ffn_inp = ggml_add(ctx0, residual, cur);
  6156. cb(ffn_inp, "ffn_inp", il);
  6157. // feed-forward network
  6158. {
  6159. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6160. model.layers[il].ffn_norm,
  6161. model.layers[il].ffn_norm_b,
  6162. LLM_NORM, cb, il);
  6163. cb(cur, "ffn_norm", il);
  6164. cur = llm_build_ffn(ctx0, cur,
  6165. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6166. NULL, NULL,
  6167. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6168. NULL,
  6169. LLM_FFN_RELU_SQR, LLM_FFN_SEQ, cb, il);
  6170. cb(cur, "ffn_out", il);
  6171. }
  6172. cur = ggml_add(ctx0, cur, ffn_inp);
  6173. cb(cur, "l_out", il);
  6174. inpL = cur;
  6175. }
  6176. cur = inpL;
  6177. cur = llm_build_norm(ctx0, cur, hparams,
  6178. model.output_norm,
  6179. model.output_norm_b,
  6180. LLM_NORM, cb, -1);
  6181. cb(cur, "result_norm", -1);
  6182. cur = ggml_mul_mat(ctx0, model.output, cur);
  6183. cb(cur, "result_output", -1);
  6184. ggml_build_forward_expand(gf, cur);
  6185. return gf;
  6186. }
  6187. struct ggml_cgraph * build_refact() {
  6188. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6189. const int64_t n_embd_head = hparams.n_embd_head_v;
  6190. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6191. struct ggml_tensor * cur;
  6192. struct ggml_tensor * inpL;
  6193. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6194. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6195. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6196. // positions of the tokens in the KV cache
  6197. struct ggml_tensor * KQ_pos = build_inp_KQ_pos();
  6198. for (int il = 0; il < n_layer; ++il) {
  6199. struct ggml_tensor * inpSA = inpL;
  6200. cur = llm_build_norm(ctx0, inpL, hparams,
  6201. model.layers[il].attn_norm, NULL,
  6202. LLM_NORM_RMS, cb, il);
  6203. cb(cur, "attn_norm", il);
  6204. // self-attention
  6205. {
  6206. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6207. cb(Qcur, "Qcur", il);
  6208. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6209. cb(Kcur, "Kcur", il);
  6210. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6211. cb(Vcur, "Vcur", il);
  6212. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  6213. cb(Kcur, "Kcur", il);
  6214. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6215. cb(Qcur, "Qcur", il);
  6216. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6217. model.layers[il].wo, NULL,
  6218. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6219. }
  6220. if (il == n_layer - 1) {
  6221. // skip computing output for unused tokens
  6222. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6223. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6224. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  6225. }
  6226. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6227. cb(ffn_inp, "ffn_inp", il);
  6228. // feed-forward network
  6229. {
  6230. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6231. model.layers[il].ffn_norm, NULL,
  6232. LLM_NORM_RMS, cb, il);
  6233. cb(cur, "ffn_norm", il);
  6234. cur = llm_build_ffn(ctx0, cur,
  6235. model.layers[il].ffn_up, NULL,
  6236. model.layers[il].ffn_gate, NULL,
  6237. model.layers[il].ffn_down, NULL,
  6238. NULL,
  6239. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6240. cb(cur, "ffn_out", il);
  6241. }
  6242. cur = ggml_add(ctx0, cur, ffn_inp);
  6243. cb(cur, "l_out", il);
  6244. // input for next layer
  6245. inpL = cur;
  6246. }
  6247. cur = inpL;
  6248. cur = llm_build_norm(ctx0, cur, hparams,
  6249. model.output_norm, NULL,
  6250. LLM_NORM_RMS, cb, -1);
  6251. cb(cur, "result_norm", -1);
  6252. // lm_head
  6253. cur = ggml_mul_mat(ctx0, model.output, cur);
  6254. cb(cur, "result_output", -1);
  6255. ggml_build_forward_expand(gf, cur);
  6256. return gf;
  6257. }
  6258. struct ggml_cgraph * build_bert() {
  6259. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6260. const int64_t n_embd_head = hparams.n_embd_head_v;
  6261. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  6262. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6263. struct ggml_tensor * cur;
  6264. struct ggml_tensor * inpL;
  6265. struct ggml_tensor * inp_pos = build_inp_pos();
  6266. struct ggml_tensor * inp_mean = build_inp_mean();
  6267. struct ggml_tensor * inp_cls = build_inp_cls();
  6268. // construct input embeddings (token, type, position)
  6269. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6270. // token types are hardcoded to zero ("Sentence A")
  6271. struct ggml_tensor * type_row0 = ggml_view_1d(ctx0, model.type_embd, n_embd, 0);
  6272. inpL = ggml_add(ctx0, inpL, type_row0);
  6273. if (model.arch == LLM_ARCH_BERT) {
  6274. inpL = ggml_add(ctx0, ggml_get_rows(ctx0, model.pos_embd, inp_pos), inpL);
  6275. }
  6276. cb(inpL, "inp_embd", -1);
  6277. // embed layer norm
  6278. inpL = llm_build_norm(ctx0, inpL, hparams, model.tok_norm, model.tok_norm_b, LLM_NORM, cb, -1);
  6279. cb(inpL, "inp_norm", -1);
  6280. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6281. struct ggml_tensor * KQ_mask = build_inp_KQ_mask(false);
  6282. // iterate layers
  6283. for (int il = 0; il < n_layer; ++il) {
  6284. struct ggml_tensor * cur = inpL;
  6285. struct ggml_tensor * Qcur;
  6286. struct ggml_tensor * Kcur;
  6287. struct ggml_tensor * Vcur;
  6288. // self-attention
  6289. if (model.arch == LLM_ARCH_BERT) {
  6290. Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, cur), model.layers[il].bq);
  6291. cb(Qcur, "Qcur", il);
  6292. Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, cur), model.layers[il].bk);
  6293. cb(Kcur, "Kcur", il);
  6294. Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, cur), model.layers[il].bv);
  6295. cb(Vcur, "Vcur", il);
  6296. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6297. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  6298. } else {
  6299. // compute Q and K and RoPE them
  6300. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6301. cb(cur, "wqkv", il);
  6302. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6303. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  6304. 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)));
  6305. cb(Qcur, "Qcur", il);
  6306. cb(Kcur, "Kcur", il);
  6307. cb(Vcur, "Vcur", il);
  6308. Qcur = ggml_rope_custom(
  6309. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6310. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6311. ext_factor, attn_factor, beta_fast, beta_slow
  6312. );
  6313. cb(Qcur, "Qcur", il);
  6314. Kcur = ggml_rope_custom(
  6315. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6316. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6317. ext_factor, attn_factor, beta_fast, beta_slow
  6318. );
  6319. cb(Kcur, "Kcur", il);
  6320. }
  6321. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  6322. struct ggml_tensor * k = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 0, 2, 1, 3));
  6323. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  6324. cb(kq, "kq", il);
  6325. kq = ggml_soft_max_ext(ctx0, kq, KQ_mask, nullptr, 1.0f/sqrtf(float(n_embd_head)), hparams.f_max_alibi_bias);
  6326. cb(kq, "kq_soft_max_ext", il);
  6327. struct ggml_tensor * v = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_reshape_2d(ctx0, Vcur, n_embd_gqa, n_tokens)));
  6328. cb(v, "v", il);
  6329. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, ggml_reshape_3d(ctx0, v, n_tokens, n_embd_head, n_head_kv), kq);
  6330. cb(kqv, "kqv", il);
  6331. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  6332. cb(kqv_merged, "kqv_merged", il);
  6333. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  6334. cb(cur, "kqv_merged_cont", il);
  6335. ggml_build_forward_expand(gf, cur);
  6336. cur = ggml_mul_mat(ctx0, model.layers[il].wo, cur);
  6337. if (model.layers[il].bo) {
  6338. cb(cur, "kqv_wo", il);
  6339. }
  6340. if (model.layers[il].bo) {
  6341. cur = ggml_add(ctx0, cur, model.layers[il].bo);
  6342. }
  6343. cb(cur, "kqv_out", il);
  6344. if (il == n_layer - 1 && pooling_type == LLAMA_POOLING_TYPE_NONE) {
  6345. // skip computing output for unused tokens
  6346. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6347. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6348. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  6349. }
  6350. // re-add the layer input
  6351. cur = ggml_add(ctx0, cur, inpL);
  6352. // attention layer norm
  6353. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].attn_out_norm, model.layers[il].attn_out_norm_b, LLM_NORM, cb, il);
  6354. struct ggml_tensor * ffn_inp = cur;
  6355. cb(ffn_inp, "ffn_inp", il);
  6356. // feed-forward network
  6357. if (model.arch == LLM_ARCH_BERT) {
  6358. cur = llm_build_ffn(ctx0, cur,
  6359. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6360. NULL, NULL,
  6361. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6362. NULL,
  6363. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6364. } else {
  6365. cur = llm_build_ffn(ctx0, cur,
  6366. model.layers[il].ffn_up, NULL,
  6367. model.layers[il].ffn_gate, NULL,
  6368. model.layers[il].ffn_down, NULL,
  6369. NULL,
  6370. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6371. }
  6372. cb(cur, "ffn_out", il);
  6373. // attentions bypass the intermediate layer
  6374. cur = ggml_add(ctx0, cur, ffn_inp);
  6375. // output layer norm
  6376. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].layer_out_norm, model.layers[il].layer_out_norm_b, LLM_NORM, cb, il);
  6377. // input for next layer
  6378. inpL = cur;
  6379. }
  6380. // final output
  6381. cur = inpL;
  6382. cb(cur, "result_embd", -1);
  6383. // pooling layer
  6384. switch (pooling_type) {
  6385. case LLAMA_POOLING_TYPE_NONE:
  6386. {
  6387. // nop
  6388. } break;
  6389. case LLAMA_POOLING_TYPE_MEAN:
  6390. {
  6391. cur = ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, cur)), inp_mean);
  6392. cb(cur, "result_embd_pooled", -1);
  6393. } break;
  6394. case LLAMA_POOLING_TYPE_CLS:
  6395. {
  6396. cur = ggml_get_rows(ctx0, cur, inp_cls);
  6397. cb(cur, "result_embd_pooled", -1);
  6398. } break;
  6399. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  6400. {
  6401. GGML_ASSERT(false && "Invalid pooling type");
  6402. } break;
  6403. }
  6404. ggml_build_forward_expand(gf, cur);
  6405. return gf;
  6406. }
  6407. struct ggml_cgraph * build_bloom() {
  6408. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6409. const int64_t n_embd_head = hparams.n_embd_head_v;
  6410. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  6411. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6412. struct ggml_tensor * cur;
  6413. struct ggml_tensor * inpL;
  6414. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6415. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6416. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6417. // positions of the tokens in the KV cache
  6418. struct ggml_tensor * KQ_pos = build_inp_KQ_pos();
  6419. inpL = llm_build_norm(ctx0, inpL, hparams,
  6420. model.tok_norm,
  6421. model.tok_norm_b,
  6422. LLM_NORM, cb, -1);
  6423. cb(inpL, "inp_norm", -1);
  6424. for (int il = 0; il < n_layer; ++il) {
  6425. cur = llm_build_norm(ctx0, inpL, hparams,
  6426. model.layers[il].attn_norm,
  6427. model.layers[il].attn_norm_b,
  6428. LLM_NORM, cb, il);
  6429. cb(cur, "attn_norm", il);
  6430. // self-attention
  6431. {
  6432. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6433. cb(cur, "wqkv", il);
  6434. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6435. cb(cur, "bqkv", il);
  6436. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6437. 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)));
  6438. 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)));
  6439. cb(Qcur, "Qcur", il);
  6440. cb(Kcur, "Kcur", il);
  6441. cb(Vcur, "Vcur", il);
  6442. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6443. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6444. model.layers[il].wo, model.layers[il].bo,
  6445. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6446. }
  6447. if (il == n_layer - 1) {
  6448. // skip computing output for unused tokens
  6449. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6450. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6451. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  6452. }
  6453. // Add the input
  6454. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  6455. cb(ffn_inp, "ffn_inp", il);
  6456. // FF
  6457. {
  6458. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6459. model.layers[il].ffn_norm,
  6460. model.layers[il].ffn_norm_b,
  6461. LLM_NORM, cb, il);
  6462. cb(cur, "ffn_norm", il);
  6463. cur = llm_build_ffn(ctx0, cur,
  6464. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6465. NULL, NULL,
  6466. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6467. NULL,
  6468. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6469. cb(cur, "ffn_out", il);
  6470. }
  6471. inpL = ggml_add(ctx0, cur, ffn_inp);
  6472. cb(inpL, "l_out", il);
  6473. }
  6474. cur = llm_build_norm(ctx0, inpL, hparams,
  6475. model.output_norm,
  6476. model.output_norm_b,
  6477. LLM_NORM, cb, -1);
  6478. cb(cur, "result_norm", -1);
  6479. cur = ggml_mul_mat(ctx0, model.output, cur);
  6480. cb(cur, "result_output", -1);
  6481. ggml_build_forward_expand(gf, cur);
  6482. return gf;
  6483. }
  6484. struct ggml_cgraph * build_mpt() {
  6485. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6486. const int64_t n_embd_head = hparams.n_embd_head_v;
  6487. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  6488. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6489. struct ggml_tensor * cur;
  6490. struct ggml_tensor * pos;
  6491. struct ggml_tensor * inpL;
  6492. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6493. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6494. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6495. // positions of the tokens in the KV cache
  6496. struct ggml_tensor * KQ_pos = build_inp_KQ_pos();
  6497. if (model.pos_embd) {
  6498. // inp_pos - contains the positions
  6499. struct ggml_tensor * inp_pos = build_inp_pos();
  6500. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  6501. cb(pos, "pos_embd", -1);
  6502. inpL = ggml_add(ctx0, inpL, pos);
  6503. cb(inpL, "inpL", -1);
  6504. }
  6505. for (int il = 0; il < n_layer; ++il) {
  6506. struct ggml_tensor * attn_norm;
  6507. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  6508. model.layers[il].attn_norm,
  6509. model.layers[il].attn_norm_b,
  6510. LLM_NORM, cb, il);
  6511. cb(attn_norm, "attn_norm", il);
  6512. // self-attention
  6513. {
  6514. cur = attn_norm;
  6515. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6516. cb(cur, "wqkv", il);
  6517. if (model.layers[il].bqkv){
  6518. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6519. cb(cur, "bqkv", il);
  6520. }
  6521. if (hparams.f_clamp_kqv > 0.0f) {
  6522. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  6523. cb(cur, "wqkv_clamped", il);
  6524. }
  6525. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6526. 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)));
  6527. 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)));
  6528. cb(Qcur, "Qcur", il);
  6529. cb(Kcur, "Kcur", il);
  6530. cb(Vcur, "Vcur", il);
  6531. // Q/K Layernorm
  6532. if (model.layers[il].attn_q_norm) {
  6533. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  6534. model.layers[il].attn_q_norm,
  6535. model.layers[il].attn_q_norm_b,
  6536. LLM_NORM, cb, il);
  6537. cb(Qcur, "Qcur", il);
  6538. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  6539. model.layers[il].attn_k_norm,
  6540. model.layers[il].attn_k_norm_b,
  6541. LLM_NORM, cb, il);
  6542. cb(Kcur, "Kcur", il);
  6543. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6544. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  6545. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6546. model.layers[il].wo, model.layers[il].bo,
  6547. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6548. } else {
  6549. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6550. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6551. model.layers[il].wo, model.layers[il].bo,
  6552. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6553. }
  6554. }
  6555. if (il == n_layer - 1) {
  6556. // skip computing output for unused tokens
  6557. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6558. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6559. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  6560. }
  6561. // Add the input
  6562. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  6563. cb(ffn_inp, "ffn_inp", il);
  6564. // feed forward
  6565. {
  6566. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6567. model.layers[il].ffn_norm,
  6568. model.layers[il].ffn_norm_b,
  6569. LLM_NORM, cb, il);
  6570. cb(cur, "ffn_norm", il);
  6571. cur = llm_build_ffn(ctx0, cur,
  6572. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6573. NULL, NULL,
  6574. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6575. model.layers[il].ffn_act,
  6576. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6577. cb(cur, "ffn_out", il);
  6578. }
  6579. cur = ggml_add(ctx0, cur, ffn_inp);
  6580. cb(cur, "l_out", il);
  6581. // input for next layer
  6582. inpL = cur;
  6583. }
  6584. cur = inpL;
  6585. cur = llm_build_norm(ctx0, cur, hparams,
  6586. model.output_norm,
  6587. model.output_norm_b,
  6588. LLM_NORM, cb, -1);
  6589. cb(cur, "result_norm", -1);
  6590. cur = ggml_mul_mat(ctx0, model.output, cur);
  6591. cb(cur, "result_output", -1);
  6592. ggml_build_forward_expand(gf, cur);
  6593. return gf;
  6594. }
  6595. struct ggml_cgraph * build_stablelm() {
  6596. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  6597. const int64_t n_embd_head = hparams.n_embd_head_v;
  6598. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6599. struct ggml_tensor * cur;
  6600. struct ggml_tensor * inpL;
  6601. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6602. // inp_pos - contains the positions
  6603. struct ggml_tensor * inp_pos = build_inp_pos();
  6604. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6605. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6606. for (int il = 0; il < n_layer; ++il) {
  6607. struct ggml_tensor * inpSA = inpL;
  6608. // norm
  6609. cur = llm_build_norm(ctx0, inpL, hparams,
  6610. model.layers[il].attn_norm,
  6611. model.layers[il].attn_norm_b,
  6612. LLM_NORM, cb, il);
  6613. cb(cur, "attn_norm", il);
  6614. // self-attention
  6615. {
  6616. // compute Q and K and RoPE them
  6617. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6618. cb(Qcur, "Qcur", il);
  6619. if (model.layers[il].bq) {
  6620. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6621. cb(Qcur, "Qcur", il);
  6622. }
  6623. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6624. cb(Kcur, "Kcur", il);
  6625. if (model.layers[il].bk) {
  6626. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6627. cb(Kcur, "Kcur", il);
  6628. }
  6629. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6630. cb(Vcur, "Vcur", il);
  6631. if (model.layers[il].bv) {
  6632. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6633. cb(Vcur, "Vcur", il);
  6634. }
  6635. Qcur = ggml_rope_custom(
  6636. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6637. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6638. ext_factor, attn_factor, beta_fast, beta_slow
  6639. );
  6640. cb(Qcur, "Qcur", il);
  6641. Kcur = ggml_rope_custom(
  6642. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6643. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6644. ext_factor, attn_factor, beta_fast, beta_slow
  6645. );
  6646. cb(Kcur, "Kcur", il);
  6647. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6648. model.layers[il].wo, NULL,
  6649. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6650. }
  6651. if (il == n_layer - 1) {
  6652. // skip computing output for unused tokens
  6653. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6654. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6655. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  6656. }
  6657. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6658. cb(ffn_inp, "ffn_inp", il);
  6659. // feed-forward network
  6660. {
  6661. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6662. model.layers[il].ffn_norm,
  6663. model.layers[il].ffn_norm_b,
  6664. LLM_NORM, cb, il);
  6665. cb(cur, "ffn_norm", il);
  6666. cur = llm_build_ffn(ctx0, cur,
  6667. model.layers[il].ffn_up, NULL,
  6668. model.layers[il].ffn_gate, NULL,
  6669. model.layers[il].ffn_down, NULL,
  6670. NULL,
  6671. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6672. cb(cur, "ffn_out", il);
  6673. }
  6674. cur = ggml_add(ctx0, cur, ffn_inp);
  6675. cb(cur, "l_out", il);
  6676. // input for next layer
  6677. inpL = cur;
  6678. }
  6679. cur = inpL;
  6680. cur = llm_build_norm(ctx0, cur, hparams,
  6681. model.output_norm,
  6682. model.output_norm_b,
  6683. LLM_NORM, cb, -1);
  6684. cb(cur, "result_norm", -1);
  6685. // lm_head
  6686. cur = ggml_mul_mat(ctx0, model.output, cur);
  6687. cb(cur, "result_output", -1);
  6688. ggml_build_forward_expand(gf, cur);
  6689. return gf;
  6690. }
  6691. struct ggml_cgraph * build_qwen() {
  6692. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6693. const int64_t n_embd_head = hparams.n_embd_head_v;
  6694. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6695. struct ggml_tensor * cur;
  6696. struct ggml_tensor * inpL;
  6697. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6698. // inp_pos - contains the positions
  6699. struct ggml_tensor * inp_pos = build_inp_pos();
  6700. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6701. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6702. for (int il = 0; il < n_layer; ++il) {
  6703. struct ggml_tensor * inpSA = inpL;
  6704. cur = llm_build_norm(ctx0, inpL, hparams,
  6705. model.layers[il].attn_norm, NULL,
  6706. LLM_NORM_RMS, cb, il);
  6707. cb(cur, "attn_norm", il);
  6708. // self-attention
  6709. {
  6710. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6711. cb(cur, "wqkv", il);
  6712. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6713. cb(cur, "bqkv", il);
  6714. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6715. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  6716. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 2*sizeof(float)*(n_embd)));
  6717. cb(Qcur, "Qcur", il);
  6718. cb(Kcur, "Kcur", il);
  6719. cb(Vcur, "Vcur", il);
  6720. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6721. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  6722. // using mode = 2 for neox mode
  6723. Qcur = ggml_rope_custom(
  6724. ctx0, Qcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  6725. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  6726. );
  6727. cb(Qcur, "Qcur", il);
  6728. Kcur = ggml_rope_custom(
  6729. ctx0, Kcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  6730. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  6731. );
  6732. cb(Kcur, "Kcur", il);
  6733. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6734. model.layers[il].wo, NULL,
  6735. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6736. }
  6737. if (il == n_layer - 1) {
  6738. // skip computing output for unused tokens
  6739. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6740. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6741. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  6742. }
  6743. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6744. cb(ffn_inp, "ffn_inp", il);
  6745. // feed-forward forward
  6746. {
  6747. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6748. model.layers[il].ffn_norm, NULL,
  6749. LLM_NORM_RMS, cb, il);
  6750. cb(cur, "ffn_norm", il);
  6751. cur = llm_build_ffn(ctx0, cur,
  6752. model.layers[il].ffn_up, NULL,
  6753. model.layers[il].ffn_gate, NULL,
  6754. model.layers[il].ffn_down, NULL,
  6755. NULL,
  6756. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6757. cb(cur, "ffn_out", il);
  6758. }
  6759. cur = ggml_add(ctx0, cur, ffn_inp);
  6760. cb(cur, "l_out", il);
  6761. // input for next layer
  6762. inpL = cur;
  6763. }
  6764. cur = inpL;
  6765. cur = llm_build_norm(ctx0, cur, hparams,
  6766. model.output_norm, NULL,
  6767. LLM_NORM_RMS, cb, -1);
  6768. cb(cur, "result_norm", -1);
  6769. // lm_head
  6770. cur = ggml_mul_mat(ctx0, model.output, cur);
  6771. cb(cur, "result_output", -1);
  6772. ggml_build_forward_expand(gf, cur);
  6773. return gf;
  6774. }
  6775. struct ggml_cgraph * build_qwen2() {
  6776. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6777. const int64_t n_embd_head = hparams.n_embd_head_v;
  6778. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6779. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6780. struct ggml_tensor * cur;
  6781. struct ggml_tensor * inpL;
  6782. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6783. // inp_pos - contains the positions
  6784. struct ggml_tensor * inp_pos = build_inp_pos();
  6785. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6786. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6787. for (int il = 0; il < n_layer; ++il) {
  6788. struct ggml_tensor * inpSA = inpL;
  6789. // norm
  6790. cur = llm_build_norm(ctx0, inpL, hparams,
  6791. model.layers[il].attn_norm, NULL,
  6792. LLM_NORM_RMS, cb, il);
  6793. cb(cur, "attn_norm", il);
  6794. // self-attention
  6795. {
  6796. // compute Q and K and RoPE them
  6797. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6798. cb(Qcur, "Qcur", il);
  6799. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6800. cb(Qcur, "Qcur", il);
  6801. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6802. cb(Kcur, "Kcur", il);
  6803. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6804. cb(Kcur, "Kcur", il);
  6805. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6806. cb(Vcur, "Vcur", il);
  6807. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6808. cb(Vcur, "Vcur", il);
  6809. // these nodes are added to the graph together so that they are not reordered
  6810. // by doing so, the number of splits in the graph is reduced
  6811. ggml_build_forward_expand(gf, Qcur);
  6812. ggml_build_forward_expand(gf, Kcur);
  6813. ggml_build_forward_expand(gf, Vcur);
  6814. Qcur = ggml_rope_custom(
  6815. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6816. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6817. ext_factor, attn_factor, beta_fast, beta_slow
  6818. );
  6819. cb(Qcur, "Qcur", il);
  6820. Kcur = ggml_rope_custom(
  6821. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6822. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6823. ext_factor, attn_factor, beta_fast, beta_slow
  6824. );
  6825. cb(Kcur, "Kcur", il);
  6826. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6827. model.layers[il].wo, model.layers[il].bo,
  6828. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6829. }
  6830. if (il == n_layer - 1) {
  6831. // skip computing output for unused tokens
  6832. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6833. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6834. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  6835. }
  6836. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6837. cb(ffn_inp, "ffn_inp", il);
  6838. // feed-forward network
  6839. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6840. model.layers[il].ffn_norm, NULL,
  6841. LLM_NORM_RMS, cb, il);
  6842. cb(cur, "ffn_norm", il);
  6843. cur = llm_build_ffn(ctx0, cur,
  6844. model.layers[il].ffn_up, NULL,
  6845. model.layers[il].ffn_gate, NULL,
  6846. model.layers[il].ffn_down, NULL,
  6847. NULL,
  6848. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6849. cb(cur, "ffn_out", il);
  6850. cur = ggml_add(ctx0, cur, ffn_inp);
  6851. cb(cur, "l_out", il);
  6852. // input for next layer
  6853. inpL = cur;
  6854. }
  6855. cur = inpL;
  6856. cur = llm_build_norm(ctx0, cur, hparams,
  6857. model.output_norm, NULL,
  6858. LLM_NORM_RMS, cb, -1);
  6859. cb(cur, "result_norm", -1);
  6860. // lm_head
  6861. cur = ggml_mul_mat(ctx0, model.output, cur);
  6862. cb(cur, "result_output", -1);
  6863. ggml_build_forward_expand(gf, cur);
  6864. return gf;
  6865. }
  6866. struct ggml_cgraph * build_phi2() {
  6867. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6868. const int64_t n_embd_head = hparams.n_embd_head_v;
  6869. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  6870. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6871. struct ggml_tensor * cur;
  6872. struct ggml_tensor * attn_norm_output;
  6873. struct ggml_tensor * ffn_output;
  6874. struct ggml_tensor * inpL;
  6875. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6876. // inp_pos - contains the positions
  6877. struct ggml_tensor * inp_pos = build_inp_pos();
  6878. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6879. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6880. for (int il = 0; il < n_layer; ++il) {
  6881. attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  6882. model.layers[il].attn_norm,
  6883. model.layers[il].attn_norm_b,
  6884. LLM_NORM, cb, il);
  6885. cb(attn_norm_output, "attn_norm", il);
  6886. // self-attention
  6887. {
  6888. struct ggml_tensor * Qcur = nullptr;
  6889. struct ggml_tensor * Kcur = nullptr;
  6890. struct ggml_tensor * Vcur = nullptr;
  6891. if (model.layers[il].wqkv) {
  6892. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, attn_norm_output);
  6893. cb(cur, "wqkv", il);
  6894. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6895. cb(cur, "bqkv", il);
  6896. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6897. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  6898. 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)));
  6899. } else {
  6900. Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  6901. Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  6902. Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  6903. }
  6904. cb(Qcur, "Qcur", il);
  6905. cb(Kcur, "Kcur", il);
  6906. cb(Vcur, "Vcur", il);
  6907. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6908. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  6909. Qcur = ggml_rope_custom(
  6910. ctx0, Qcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  6911. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  6912. );
  6913. cb(Qcur, "Qcur", il);
  6914. // with phi2, we scale the Q to avoid precision issues
  6915. // ref: https://github.com/ml-explore/mlx-examples/blob/08e862336ade809bc37d1035f94b359e7d1a5152/phi2/phi2.py#L64-L66
  6916. Qcur = ggml_scale(ctx0, Qcur, 1.0f/sqrtf(float(n_embd_head)));
  6917. cb(Qcur, "Qcur", il);
  6918. Kcur = ggml_rope_custom(
  6919. ctx0, Kcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  6920. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  6921. );
  6922. cb(Kcur, "Kcur", il);
  6923. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6924. model.layers[il].wo, model.layers[il].bo,
  6925. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  6926. }
  6927. if (il == n_layer - 1) {
  6928. // skip computing output for unused tokens
  6929. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6930. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6931. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  6932. attn_norm_output = ggml_get_rows(ctx0, attn_norm_output, inp_out_ids);
  6933. }
  6934. // FF
  6935. {
  6936. ffn_output = llm_build_ffn(ctx0, attn_norm_output,
  6937. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6938. NULL, NULL,
  6939. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6940. NULL,
  6941. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6942. cb(ffn_output, "ffn_out", il);
  6943. }
  6944. cur = ggml_add(ctx0, cur, ffn_output);
  6945. cb(cur, "l_out", il);
  6946. cur = ggml_add(ctx0, cur, inpL);
  6947. cb(cur, "l_out", il);
  6948. inpL = cur;
  6949. }
  6950. cur = llm_build_norm(ctx0, inpL, hparams,
  6951. model.output_norm,
  6952. model.output_norm_b,
  6953. LLM_NORM, cb, -1);
  6954. cb(cur, "result_norm", -1);
  6955. cur = ggml_mul_mat(ctx0, model.output, cur);
  6956. cb(cur, "result_output_no_bias", -1);
  6957. cur = ggml_add(ctx0, cur, model.output_b);
  6958. cb(cur, "result_output", -1);
  6959. ggml_build_forward_expand(gf, cur);
  6960. return gf;
  6961. }
  6962. struct ggml_cgraph * build_plamo() {
  6963. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  6964. const int64_t n_embd_head = hparams.n_embd_head_v;
  6965. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6966. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6967. struct ggml_tensor * cur;
  6968. struct ggml_tensor * inpL;
  6969. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6970. // inp_pos - contains the positions
  6971. struct ggml_tensor * inp_pos = build_inp_pos();
  6972. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6973. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6974. for (int il = 0; il < n_layer; ++il) {
  6975. // norm
  6976. cur = llm_build_norm(ctx0, inpL, hparams,
  6977. model.layers[il].attn_norm, NULL,
  6978. LLM_NORM_RMS, cb, il);
  6979. cb(cur, "attn_norm", il);
  6980. struct ggml_tensor * attention_norm = cur;
  6981. // self-attention
  6982. {
  6983. // compute Q and K and RoPE them
  6984. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6985. cb(Qcur, "Qcur", il);
  6986. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6987. cb(Kcur, "Kcur", il);
  6988. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6989. cb(Vcur, "Vcur", il);
  6990. Qcur = ggml_rope_custom(
  6991. ctx0, ggml_reshape_3d(ctx0, Qcur, n_rot, n_head, n_tokens), inp_pos,
  6992. n_embd_head, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6993. ext_factor, attn_factor, beta_fast, beta_slow);
  6994. cb(Qcur, "Qcur", il);
  6995. Kcur = ggml_rope_custom(
  6996. ctx0, ggml_reshape_3d(ctx0, Kcur, n_rot, n_head_kv, n_tokens), inp_pos,
  6997. n_embd_head, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6998. ext_factor, attn_factor, beta_fast, beta_slow);
  6999. cb(Kcur, "Kcur", il);
  7000. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  7001. model.layers[il].wo, NULL,
  7002. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7003. }
  7004. struct ggml_tensor * sa_out = cur;
  7005. cur = attention_norm;
  7006. if (il == n_layer - 1) {
  7007. // skip computing output for unused tokens
  7008. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7009. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7010. sa_out = ggml_get_rows(ctx0, sa_out, inp_out_ids);
  7011. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  7012. }
  7013. // feed-forward network
  7014. {
  7015. cur = llm_build_ffn(ctx0, cur,
  7016. model.layers[il].ffn_up, NULL,
  7017. model.layers[il].ffn_gate, NULL,
  7018. model.layers[il].ffn_down, NULL,
  7019. NULL,
  7020. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  7021. cb(cur, "ffn_out", il);
  7022. }
  7023. cur = ggml_add(ctx0, cur, sa_out);
  7024. cb(cur, "l_out", il);
  7025. cur = ggml_add(ctx0, cur, inpL);
  7026. cb(cur, "l_out", il);
  7027. // input for next layer
  7028. inpL = cur;
  7029. }
  7030. cur = inpL;
  7031. cur = llm_build_norm(ctx0, cur, hparams,
  7032. model.output_norm, NULL,
  7033. LLM_NORM_RMS, cb, -1);
  7034. cb(cur, "result_norm", -1);
  7035. // lm_head
  7036. cur = ggml_mul_mat(ctx0, model.output, cur);
  7037. cb(cur, "result_output", -1);
  7038. ggml_build_forward_expand(gf, cur);
  7039. return gf;
  7040. }
  7041. struct ggml_cgraph * build_gpt2() {
  7042. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7043. const int64_t n_embd_head = hparams.n_embd_head_v;
  7044. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  7045. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7046. struct ggml_tensor * cur;
  7047. struct ggml_tensor * pos;
  7048. struct ggml_tensor * inpL;
  7049. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7050. // inp_pos - contains the positions
  7051. struct ggml_tensor * inp_pos = build_inp_pos();
  7052. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7053. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7054. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  7055. cb(pos, "pos_embd", -1);
  7056. inpL = ggml_add(ctx0, inpL, pos);
  7057. cb(inpL, "inpL", -1);
  7058. for (int il = 0; il < n_layer; ++il) {
  7059. cur = llm_build_norm(ctx0, inpL, hparams,
  7060. model.layers[il].attn_norm,
  7061. model.layers[il].attn_norm_b,
  7062. LLM_NORM, cb, il);
  7063. cb(cur, "attn_norm", il);
  7064. // self-attention
  7065. {
  7066. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  7067. cb(cur, "wqkv", il);
  7068. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  7069. cb(cur, "bqkv", il);
  7070. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  7071. 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)));
  7072. 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)));
  7073. cb(Qcur, "Qcur", il);
  7074. cb(Kcur, "Kcur", il);
  7075. cb(Vcur, "Vcur", il);
  7076. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  7077. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  7078. model.layers[il].wo, model.layers[il].bo,
  7079. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7080. }
  7081. if (il == n_layer - 1) {
  7082. // skip computing output for unused tokens
  7083. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7084. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7085. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  7086. }
  7087. // add the input
  7088. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  7089. cb(ffn_inp, "ffn_inp", il);
  7090. // FF
  7091. {
  7092. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7093. model.layers[il].ffn_norm,
  7094. model.layers[il].ffn_norm_b,
  7095. LLM_NORM, cb, il);
  7096. cb(cur, "ffn_norm", il);
  7097. cur = llm_build_ffn(ctx0, cur,
  7098. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  7099. NULL, NULL,
  7100. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  7101. NULL,
  7102. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  7103. cb(cur, "ffn_out", il);
  7104. }
  7105. inpL = ggml_add(ctx0, cur, ffn_inp);
  7106. cb(inpL, "l_out", il);
  7107. }
  7108. cur = llm_build_norm(ctx0, inpL, hparams,
  7109. model.output_norm,
  7110. model.output_norm_b,
  7111. LLM_NORM, cb, -1);
  7112. cb(cur, "result_norm", -1);
  7113. cur = ggml_mul_mat(ctx0, model.output, cur);
  7114. cb(cur, "result_output", -1);
  7115. ggml_build_forward_expand(gf, cur);
  7116. return gf;
  7117. }
  7118. struct ggml_cgraph * build_codeshell() {
  7119. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7120. const int64_t n_embd_head = hparams.n_embd_head_v;
  7121. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  7122. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7123. GGML_ASSERT(n_embd_head == hparams.n_rot);
  7124. struct ggml_tensor * cur;
  7125. struct ggml_tensor * inpL;
  7126. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7127. // inp_pos - contains the positions
  7128. struct ggml_tensor * inp_pos = build_inp_pos();
  7129. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7130. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7131. for (int il = 0; il < n_layer; ++il) {
  7132. cur = llm_build_norm(ctx0, inpL, hparams,
  7133. model.layers[il].attn_norm,
  7134. model.layers[il].attn_norm_b,
  7135. LLM_NORM, cb, il);
  7136. cb(cur, "attn_norm", il);
  7137. // self-attention
  7138. {
  7139. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  7140. cb(cur, "wqkv", il);
  7141. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  7142. cb(cur, "bqkv", il);
  7143. struct ggml_tensor * tmpq = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  7144. 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)));
  7145. 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)));
  7146. cb(tmpq, "tmpq", il);
  7147. cb(tmpk, "tmpk", il);
  7148. cb(Vcur, "Vcur", il);
  7149. struct ggml_tensor * Qcur = ggml_rope_custom(
  7150. ctx0, ggml_reshape_3d(ctx0, tmpq, n_embd_head, n_head, n_tokens), inp_pos,
  7151. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7152. ext_factor, attn_factor, beta_fast, beta_slow
  7153. );
  7154. cb(Qcur, "Qcur", il);
  7155. struct ggml_tensor * Kcur = ggml_rope_custom(
  7156. ctx0, ggml_reshape_3d(ctx0, tmpk, n_embd_head, n_head_kv, n_tokens), inp_pos,
  7157. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7158. ext_factor, attn_factor, beta_fast, beta_slow
  7159. );
  7160. cb(Kcur, "Kcur", il);
  7161. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  7162. model.layers[il].wo, model.layers[il].bo,
  7163. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7164. }
  7165. if (il == n_layer - 1) {
  7166. // skip computing output for unused tokens
  7167. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7168. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7169. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  7170. }
  7171. // add the input
  7172. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  7173. cb(ffn_inp, "ffn_inp", il);
  7174. // FF
  7175. {
  7176. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7177. model.layers[il].ffn_norm,
  7178. model.layers[il].ffn_norm_b,
  7179. LLM_NORM, cb, il);
  7180. cb(cur, "ffn_norm", il);
  7181. cur = llm_build_ffn(ctx0, cur,
  7182. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  7183. NULL, NULL,
  7184. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  7185. NULL,
  7186. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  7187. cb(cur, "ffn_out", il);
  7188. }
  7189. inpL = ggml_add(ctx0, cur, ffn_inp);
  7190. cb(inpL, "l_out", il);
  7191. }
  7192. cur = llm_build_norm(ctx0, inpL, hparams,
  7193. model.output_norm,
  7194. model.output_norm_b,
  7195. LLM_NORM, cb, -1);
  7196. cb(cur, "result_norm", -1);
  7197. cur = ggml_mul_mat(ctx0, model.output, cur);
  7198. cb(cur, "result_output", -1);
  7199. ggml_build_forward_expand(gf, cur);
  7200. return gf;
  7201. }
  7202. struct ggml_cgraph * build_orion() {
  7203. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7204. const int64_t n_embd_head = hparams.n_embd_head_v;
  7205. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7206. GGML_ASSERT(n_embd_head == hparams.n_rot);
  7207. struct ggml_tensor * cur;
  7208. struct ggml_tensor * inpL;
  7209. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7210. // inp_pos - contains the positions
  7211. struct ggml_tensor * inp_pos = build_inp_pos();
  7212. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7213. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7214. for (int il = 0; il < n_layer; ++il) {
  7215. struct ggml_tensor * inpSA = inpL;
  7216. // norm
  7217. cur = llm_build_norm(ctx0, inpL, hparams,
  7218. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  7219. LLM_NORM, cb, il);
  7220. cb(cur, "attn_norm", il);
  7221. // self-attention
  7222. {
  7223. // compute Q and K and RoPE them
  7224. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  7225. cb(Qcur, "Qcur", il);
  7226. // if (model.layers[il].bq) {
  7227. // Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  7228. // cb(Qcur, "Qcur", il);
  7229. // }
  7230. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  7231. cb(Kcur, "Kcur", il);
  7232. // if (model.layers[il].bk) {
  7233. // Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  7234. // cb(Kcur, "Kcur", il);
  7235. // }
  7236. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  7237. cb(Vcur, "Vcur", il);
  7238. // if (model.layers[il].bv) {
  7239. // Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  7240. // cb(Vcur, "Vcur", il);
  7241. // }
  7242. Qcur = ggml_rope_custom(
  7243. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  7244. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7245. ext_factor, attn_factor, beta_fast, beta_slow
  7246. );
  7247. cb(Qcur, "Qcur", il);
  7248. Kcur = ggml_rope_custom(
  7249. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  7250. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7251. ext_factor, attn_factor, beta_fast, beta_slow
  7252. );
  7253. cb(Kcur, "Kcur", il);
  7254. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  7255. model.layers[il].wo, NULL,
  7256. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7257. }
  7258. if (il == n_layer - 1) {
  7259. // skip computing output for unused tokens
  7260. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7261. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7262. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  7263. }
  7264. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  7265. cb(ffn_inp, "ffn_inp", il);
  7266. // feed-forward network
  7267. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7268. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  7269. LLM_NORM, cb, il);
  7270. cb(cur, "ffn_norm", il);
  7271. cur = llm_build_ffn(ctx0, cur,
  7272. model.layers[il].ffn_up, NULL,
  7273. model.layers[il].ffn_gate, NULL,
  7274. model.layers[il].ffn_down, NULL,
  7275. NULL,
  7276. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  7277. cb(cur, "ffn_out", il);
  7278. cur = ggml_add(ctx0, cur, ffn_inp);
  7279. cb(cur, "l_out", il);
  7280. // input for next layer
  7281. inpL = cur;
  7282. }
  7283. cur = inpL;
  7284. cur = llm_build_norm(ctx0, cur, hparams,
  7285. model.output_norm, model.output_norm_b,
  7286. LLM_NORM, cb, -1);
  7287. cb(cur, "result_norm", -1);
  7288. // lm_head
  7289. cur = ggml_mul_mat(ctx0, model.output, cur);
  7290. cb(cur, "result_output", -1);
  7291. ggml_build_forward_expand(gf, cur);
  7292. return gf;
  7293. }
  7294. struct ggml_cgraph * build_internlm2() {
  7295. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7296. const int64_t n_embd_head = hparams.n_embd_head_v;
  7297. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7298. GGML_ASSERT(n_embd_head == hparams.n_rot);
  7299. struct ggml_tensor * cur;
  7300. struct ggml_tensor * inpL;
  7301. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7302. // inp_pos - contains the positions
  7303. struct ggml_tensor * inp_pos = build_inp_pos();
  7304. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7305. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7306. for (int il = 0; il < n_layer; ++il) {
  7307. struct ggml_tensor * inpSA = inpL;
  7308. // norm
  7309. cur = llm_build_norm(ctx0, inpL, hparams,
  7310. model.layers[il].attn_norm, NULL,
  7311. LLM_NORM_RMS, cb, il);
  7312. cb(cur, "attn_norm", il);
  7313. // self-attention
  7314. {
  7315. // compute Q and K and RoPE them
  7316. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  7317. cb(Qcur, "Qcur", il);
  7318. if (model.layers[il].bq) {
  7319. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  7320. cb(Qcur, "Qcur", il);
  7321. }
  7322. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  7323. cb(Kcur, "Kcur", il);
  7324. if (model.layers[il].bk) {
  7325. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  7326. cb(Kcur, "Kcur", il);
  7327. }
  7328. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  7329. cb(Vcur, "Vcur", il);
  7330. if (model.layers[il].bv) {
  7331. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  7332. cb(Vcur, "Vcur", il);
  7333. }
  7334. Qcur = ggml_rope_custom(
  7335. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  7336. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7337. ext_factor, attn_factor, beta_fast, beta_slow
  7338. );
  7339. cb(Qcur, "Qcur", il);
  7340. Kcur = ggml_rope_custom(
  7341. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  7342. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7343. ext_factor, attn_factor, beta_fast, beta_slow
  7344. );
  7345. cb(Kcur, "Kcur", il);
  7346. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  7347. model.layers[il].wo, model.layers[il].bo,
  7348. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7349. }
  7350. if (il == n_layer - 1) {
  7351. // skip computing output for unused tokens
  7352. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7353. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7354. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  7355. }
  7356. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  7357. cb(ffn_inp, "ffn_inp", il);
  7358. // feed-forward network
  7359. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7360. model.layers[il].ffn_norm, NULL,
  7361. LLM_NORM_RMS, cb, il);
  7362. cb(cur, "ffn_norm", il);
  7363. cur = llm_build_ffn(ctx0, cur,
  7364. model.layers[il].ffn_up, NULL,
  7365. model.layers[il].ffn_gate, NULL,
  7366. model.layers[il].ffn_down, NULL,
  7367. NULL,
  7368. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  7369. cb(cur, "ffn_out", il);
  7370. cur = ggml_add(ctx0, cur, ffn_inp);
  7371. cb(cur, "l_out", il);
  7372. // input for next layer
  7373. inpL = cur;
  7374. }
  7375. cur = inpL;
  7376. cur = llm_build_norm(ctx0, cur, hparams,
  7377. model.output_norm, NULL,
  7378. LLM_NORM_RMS, cb, -1);
  7379. cb(cur, "result_norm", -1);
  7380. // lm_head
  7381. cur = ggml_mul_mat(ctx0, model.output, cur);
  7382. cb(cur, "result_output", -1);
  7383. ggml_build_forward_expand(gf, cur);
  7384. return gf;
  7385. }
  7386. // ref: https://arxiv.org/abs/2203.03466
  7387. // https://github.com/ggerganov/llama.cpp/issues/5276#issuecomment-1925774738
  7388. // based on the original build_llama() function
  7389. struct ggml_cgraph * build_minicpm() {
  7390. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7391. const int64_t n_embd_head = hparams.n_embd_head_v;
  7392. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7393. GGML_ASSERT(n_embd_head == hparams.n_rot);
  7394. const int64_t n_embd = hparams.n_embd;
  7395. //TODO: if the model varies, these parameters need to be read from the model
  7396. const int64_t n_embd_base = 256;
  7397. const float scale_embd = 12.0f;
  7398. const float scale_depth = 1.4f;
  7399. struct ggml_tensor * cur;
  7400. struct ggml_tensor * inpL;
  7401. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7402. // scale the input embeddings
  7403. inpL = ggml_scale(ctx0, inpL, scale_embd);
  7404. cb(inpL, "inp_scaled", -1);
  7405. // inp_pos - contains the positions
  7406. struct ggml_tensor * inp_pos = build_inp_pos();
  7407. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7408. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7409. for (int il = 0; il < n_layer; ++il) {
  7410. struct ggml_tensor * inpSA = inpL;
  7411. // norm
  7412. cur = llm_build_norm(ctx0, inpL, hparams,
  7413. model.layers[il].attn_norm, NULL,
  7414. LLM_NORM_RMS, cb, il);
  7415. cb(cur, "attn_norm", il);
  7416. // self-attention
  7417. {
  7418. // compute Q and K and RoPE them
  7419. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  7420. cb(Qcur, "Qcur", il);
  7421. if (model.layers[il].bq) {
  7422. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  7423. cb(Qcur, "Qcur", il);
  7424. }
  7425. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  7426. cb(Kcur, "Kcur", il);
  7427. if (model.layers[il].bk) {
  7428. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  7429. cb(Kcur, "Kcur", il);
  7430. }
  7431. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  7432. cb(Vcur, "Vcur", il);
  7433. if (model.layers[il].bv) {
  7434. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  7435. cb(Vcur, "Vcur", il);
  7436. }
  7437. Qcur = ggml_rope_custom(
  7438. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  7439. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7440. ext_factor, attn_factor, beta_fast, beta_slow
  7441. );
  7442. cb(Qcur, "Qcur", il);
  7443. Kcur = ggml_rope_custom(
  7444. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  7445. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7446. ext_factor, attn_factor, beta_fast, beta_slow
  7447. );
  7448. cb(Kcur, "Kcur", il);
  7449. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  7450. model.layers[il].wo, model.layers[il].bo,
  7451. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7452. }
  7453. if (il == n_layer - 1) {
  7454. // skip computing output for unused tokens
  7455. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7456. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7457. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  7458. }
  7459. // scale_res - scale the hidden states for residual connection
  7460. const float scale_res = scale_depth/sqrtf(float(n_layer));
  7461. cur = ggml_scale(ctx0, cur, scale_res);
  7462. cb(cur, "hidden_scaled", -1);
  7463. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  7464. cb(ffn_inp, "ffn_inp", il);
  7465. // feed-forward network
  7466. {
  7467. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7468. model.layers[il].ffn_norm, NULL,
  7469. LLM_NORM_RMS, cb, il);
  7470. cb(cur, "ffn_norm", il);
  7471. cur = llm_build_ffn(ctx0, cur,
  7472. model.layers[il].ffn_up, NULL,
  7473. model.layers[il].ffn_gate, NULL,
  7474. model.layers[il].ffn_down, NULL,
  7475. NULL,
  7476. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  7477. cb(cur, "ffn_out", il);
  7478. }
  7479. // scale the hidden states for residual connection
  7480. cur = ggml_scale(ctx0, cur, scale_res);
  7481. cb(cur, "hidden_scaled_ffn", -1);
  7482. cur = ggml_add(ctx0, cur, ffn_inp);
  7483. cb(cur, "l_out", il);
  7484. // input for next layer
  7485. inpL = cur;
  7486. }
  7487. cur = inpL;
  7488. cur = llm_build_norm(ctx0, cur, hparams,
  7489. model.output_norm, NULL,
  7490. LLM_NORM_RMS, cb, -1);
  7491. cb(cur, "result_norm", -1);
  7492. // lm_head scaling
  7493. const float scale_lmhead = float(n_embd_base)/float(n_embd);
  7494. cur = ggml_scale(ctx0, cur, scale_lmhead);
  7495. cb(cur, "lmhead_scaling", -1);
  7496. // lm_head
  7497. cur = ggml_mul_mat(ctx0, model.tok_embd, cur);
  7498. cb(cur, "result_output", -1);
  7499. ggml_build_forward_expand(gf, cur);
  7500. return gf;
  7501. }
  7502. struct ggml_cgraph * build_gemma() {
  7503. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7504. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  7505. struct ggml_tensor * cur;
  7506. struct ggml_tensor * inpL;
  7507. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7508. inpL = ggml_scale(ctx0, inpL, sqrtf(n_embd));
  7509. cb(inpL, "inp_scaled", -1);
  7510. // inp_pos - contains the positions
  7511. struct ggml_tensor * inp_pos = build_inp_pos();
  7512. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7513. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7514. for (int il = 0; il < n_layer; ++il) {
  7515. // norm
  7516. cur = llm_build_norm(ctx0, inpL, hparams,
  7517. model.layers[il].attn_norm, NULL,
  7518. LLM_NORM_RMS, cb, il);
  7519. cb(cur, "attn_norm", il);
  7520. // self-attention
  7521. {
  7522. // compute Q and K and RoPE them
  7523. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  7524. cb(Qcur, "Qcur", il);
  7525. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  7526. cb(Kcur, "Kcur", il);
  7527. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  7528. cb(Vcur, "Vcur", il);
  7529. Qcur = ggml_rope_custom(
  7530. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head_k, n_head, n_tokens), inp_pos,
  7531. n_embd_head_k, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7532. ext_factor, attn_factor, beta_fast, beta_slow);
  7533. cb(Qcur, "Qcur", il);
  7534. Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head_k)));
  7535. cb(Qcur, "Qcur_scaled", il);
  7536. Kcur = ggml_rope_custom(
  7537. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head_k, n_head_kv, n_tokens), inp_pos,
  7538. n_embd_head_k, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7539. ext_factor, attn_factor, beta_fast, beta_slow);
  7540. cb(Kcur, "Kcur", il);
  7541. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  7542. model.layers[il].wo, NULL,
  7543. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  7544. }
  7545. if (il == n_layer - 1) {
  7546. // skip computing output for unused tokens
  7547. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7548. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7549. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  7550. }
  7551. struct ggml_tensor * sa_out = ggml_add(ctx0, cur, inpL);
  7552. cb(sa_out, "sa_out", il);
  7553. cur = llm_build_norm(ctx0, sa_out, hparams,
  7554. model.layers[il].ffn_norm, NULL,
  7555. LLM_NORM_RMS, cb, il);
  7556. cb(cur, "ffn_norm", il);
  7557. // feed-forward network
  7558. {
  7559. cur = llm_build_ffn(ctx0, cur,
  7560. model.layers[il].ffn_up, NULL,
  7561. model.layers[il].ffn_gate, NULL,
  7562. model.layers[il].ffn_down, NULL,
  7563. NULL,
  7564. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  7565. cb(cur, "ffn_out", il);
  7566. }
  7567. cur = ggml_add(ctx0, cur, sa_out);
  7568. cb(cur, "l_out", il);
  7569. // input for next layer
  7570. inpL = cur;
  7571. }
  7572. cur = inpL;
  7573. cur = llm_build_norm(ctx0, cur, hparams,
  7574. model.output_norm, NULL,
  7575. LLM_NORM_RMS, cb, -1);
  7576. cb(cur, "result_norm", -1);
  7577. // lm_head
  7578. cur = ggml_mul_mat(ctx0, model.output, cur);
  7579. cb(cur, "result_output", -1);
  7580. ggml_build_forward_expand(gf, cur);
  7581. return gf;
  7582. }
  7583. struct ggml_cgraph * build_starcoder2() {
  7584. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7585. const int64_t n_embd_head = hparams.n_embd_head_v;
  7586. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7587. GGML_ASSERT(n_embd_head == hparams.n_rot);
  7588. struct ggml_tensor * cur;
  7589. struct ggml_tensor * inpL;
  7590. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7591. // inp_pos - contains the positions
  7592. struct ggml_tensor * inp_pos = build_inp_pos();
  7593. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7594. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7595. for (int il = 0; il < n_layer; ++il) {
  7596. struct ggml_tensor * inpSA = inpL;
  7597. // norm
  7598. cur = llm_build_norm(ctx0, inpL, hparams,
  7599. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  7600. LLM_NORM, cb, il);
  7601. cb(cur, "attn_norm", il);
  7602. // self-attention
  7603. {
  7604. // compute Q and K and RoPE them
  7605. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  7606. cb(Qcur, "Qcur", il);
  7607. if (model.layers[il].bq) {
  7608. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  7609. cb(Qcur, "Qcur", il);
  7610. }
  7611. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  7612. cb(Kcur, "Kcur", il);
  7613. if (model.layers[il].bk) {
  7614. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  7615. cb(Kcur, "Kcur", il);
  7616. }
  7617. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  7618. cb(Vcur, "Vcur", il);
  7619. if (model.layers[il].bv) {
  7620. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  7621. cb(Vcur, "Vcur", il);
  7622. }
  7623. Qcur = ggml_rope_custom(
  7624. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  7625. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7626. ext_factor, attn_factor, beta_fast, beta_slow
  7627. );
  7628. cb(Qcur, "Qcur", il);
  7629. Kcur = ggml_rope_custom(
  7630. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  7631. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7632. ext_factor, attn_factor, beta_fast, beta_slow
  7633. );
  7634. cb(Kcur, "Kcur", il);
  7635. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  7636. model.layers[il].wo, model.layers[il].bo,
  7637. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7638. }
  7639. if (il == n_layer - 1) {
  7640. // skip computing output for unused tokens
  7641. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7642. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7643. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  7644. }
  7645. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  7646. cb(ffn_inp, "ffn_inp", il);
  7647. // feed-forward network
  7648. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7649. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  7650. LLM_NORM, cb, il);
  7651. cb(cur, "ffn_norm", il);
  7652. cur = llm_build_ffn(ctx0, cur,
  7653. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  7654. NULL, NULL,
  7655. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  7656. NULL,
  7657. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  7658. cb(cur, "ffn_out", il);
  7659. cur = ggml_add(ctx0, cur, ffn_inp);
  7660. cb(cur, "l_out", il);
  7661. // input for next layer
  7662. inpL = cur;
  7663. }
  7664. cur = inpL;
  7665. cur = llm_build_norm(ctx0, cur, hparams,
  7666. model.output_norm, model.output_norm_b,
  7667. LLM_NORM, cb, -1);
  7668. cb(cur, "result_norm", -1);
  7669. // lm_head
  7670. cur = ggml_mul_mat(ctx0, model.output, cur);
  7671. cb(cur, "result_output", -1);
  7672. ggml_build_forward_expand(gf, cur);
  7673. return gf;
  7674. }
  7675. struct ggml_cgraph * build_mamba() {
  7676. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7677. const int64_t d_model = n_embd;
  7678. const int64_t d_conv = hparams.ssm_d_conv;
  7679. const int64_t d_inner = hparams.ssm_d_inner;
  7680. GGML_ASSERT(2 * d_model == d_inner);
  7681. const int64_t d_state = hparams.ssm_d_state;
  7682. const int64_t dt_rank = hparams.ssm_dt_rank;
  7683. struct ggml_tensor * cur;
  7684. struct ggml_tensor * inpL;
  7685. // {n_embd, n_tokens}
  7686. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7687. struct ggml_tensor * state_mask = build_inp_s_mask();
  7688. struct ggml_tensor * state_seq = build_inp_s_seq();
  7689. for (int il = 0; il < n_layer; ++il) {
  7690. // (ab)using the KV cache to store the states
  7691. struct ggml_tensor * conv_states = ggml_reshape_2d(ctx0, kv_self.k_l[il], hparams.n_embd_k_s(), kv_self.size);
  7692. struct ggml_tensor * ssm_states = ggml_reshape_2d(ctx0, kv_self.v_l[il], hparams.n_embd_v_s(), kv_self.size);
  7693. // clear states of sequences which are starting at the beginning of this batch
  7694. {
  7695. conv_states = ggml_mul(ctx0,
  7696. ggml_view_2d(ctx0, conv_states, conv_states->ne[0], n_kv, conv_states->nb[1], kv_head*conv_states->nb[1]),
  7697. state_mask);
  7698. ssm_states = ggml_mul(ctx0,
  7699. ggml_view_2d(ctx0, ssm_states, ssm_states->ne[0], n_kv, ssm_states->nb[1], kv_head*ssm_states->nb[1]),
  7700. state_mask);
  7701. }
  7702. conv_states = ggml_reshape_3d(ctx0, conv_states, d_conv - 1, d_inner, n_kv);
  7703. ssm_states = ggml_reshape_3d(ctx0, ssm_states, d_state, d_inner, n_kv);
  7704. // norm
  7705. cur = llm_build_norm(ctx0, inpL, hparams,
  7706. model.layers[il].attn_norm, NULL,
  7707. LLM_NORM_RMS, cb, il);
  7708. cb(cur, "attn_norm", il);
  7709. // {n_embd, 2*d_inner} * {n_embd, n_tokens} => {2*d_inner, n_tokens}
  7710. struct ggml_tensor * xz = ggml_mul_mat(ctx0, model.layers[il].ssm_in, cur);
  7711. // split the above in two
  7712. // => {d_inner, n_tokens}
  7713. struct ggml_tensor * x = ggml_view_2d(ctx0, xz, d_inner, xz->ne[1], xz->nb[1], 0);
  7714. struct ggml_tensor * z = ggml_view_2d(ctx0, xz, d_inner, xz->ne[1], xz->nb[1], ggml_element_size(xz)*d_inner);
  7715. // conv
  7716. {
  7717. // Custom operator which is needed only to ease simultaneous sequence processing.
  7718. // For a single sequence, the equivalent is to concatenate the columns of conv_states and x,
  7719. // then make a self-overlapping view of that over d_conv columns at each stride in the 3rd dimension,
  7720. // then element-wise multiply that with the conv1d weigth,
  7721. // then sum the elements of each row,
  7722. // (the last two steps are a dot product over rows (also doable with mul_mat))
  7723. // then permute away the ne[0] dimension,
  7724. // and then you're left with the resulting x tensor.
  7725. // The new conv_states is the last (d_conv - 1) columns
  7726. // of the last 3rd dimensional "layer" of the self-overlapping view.
  7727. // For simultaneous sequences, it's more complicated.
  7728. struct ggml_tensor * x_conv = ggml_ssm_conv(ctx0, conv_states, x, model.layers[il].ssm_conv1d, state_seq);
  7729. // store last (d_conv - 1) columns of the conv_state part of x_conv back into the KV cache
  7730. ggml_build_forward_expand(gf,
  7731. ggml_cpy(ctx0,
  7732. 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)),
  7733. 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))));
  7734. // extract x from x_conv
  7735. x = ggml_view_2d(ctx0, x_conv, d_inner, n_tokens, d_inner*ggml_element_size(x_conv), 0);
  7736. // bias
  7737. x = ggml_add(ctx0, x, model.layers[il].ssm_conv1d_b);
  7738. x = ggml_silu(ctx0, x);
  7739. }
  7740. // ssm
  7741. {
  7742. // {d_inner, dt_rank + 2*d_state} * {d_inner, n_tokens} => {dt_rank + 2*d_state, n_tokens}
  7743. struct ggml_tensor * x_db = ggml_mul_mat(ctx0, model.layers[il].ssm_x, x);
  7744. // split
  7745. struct ggml_tensor * dt = ggml_view_2d(ctx0, x_db, dt_rank, n_tokens, x_db->nb[1], 0);
  7746. 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);
  7747. 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));
  7748. // {dt_rank, d_inner} * {dt_rank, n_tokens} => {d_inner, n_tokens}
  7749. dt = ggml_mul_mat(ctx0, model.layers[il].ssm_dt, dt);
  7750. dt = ggml_add(ctx0, dt, model.layers[il].ssm_dt_b);
  7751. // Custom operator to optimize the parallel associative scan
  7752. // as described in the Annex D of the Mamba paper.
  7753. // => {d_inner, n_tokens} and {d_state, d_inner, n_kv} combined,
  7754. // because only a single tensor can be returned.
  7755. struct ggml_tensor * y_ssm_states = ggml_ssm_scan(ctx0, ssm_states, x, dt, model.layers[il].ssm_a, B, C, state_seq);
  7756. // store last states (the second part of y_ssm_states)
  7757. ggml_build_forward_expand(gf,
  7758. ggml_cpy(ctx0,
  7759. ggml_view_1d(ctx0, y_ssm_states, d_state*d_inner*n_kv, d_inner*n_tokens*ggml_element_size(y_ssm_states)),
  7760. 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))));
  7761. struct ggml_tensor * y = ggml_view_2d(ctx0, y_ssm_states, d_inner, n_tokens, d_inner*ggml_element_size(y_ssm_states), 0);
  7762. if (il == n_layer - 1) {
  7763. // skip computing output for unused tokens
  7764. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7765. x = ggml_get_rows(ctx0, x, inp_out_ids);
  7766. y = ggml_get_rows(ctx0, y, inp_out_ids);
  7767. z = ggml_get_rows(ctx0, z, inp_out_ids);
  7768. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  7769. }
  7770. // {d_inner, n_tokens} * {d_inner} => {d_inner, n_tokens}
  7771. y = ggml_add(ctx0, y, ggml_mul(ctx0, x, model.layers[il].ssm_d));
  7772. y = ggml_mul(ctx0, y, ggml_silu(ctx0, z));
  7773. // {d_inner, n_embd} * {d_inner, n_tokens} => {n_embd, n_tokens}
  7774. cur = ggml_mul_mat(ctx0, model.layers[il].ssm_out, y);
  7775. }
  7776. // residual
  7777. cur = ggml_add(ctx0, cur, inpL);
  7778. cb(cur, "l_out", il);
  7779. // input for next layer
  7780. inpL = cur;
  7781. }
  7782. // final rmsnorm
  7783. cur = llm_build_norm(ctx0, inpL, hparams,
  7784. model.output_norm, NULL,
  7785. LLM_NORM_RMS, cb, -1);
  7786. cb(cur, "result_norm", -1);
  7787. // lm_head
  7788. cur = ggml_mul_mat(ctx0, model.output, cur);
  7789. cb(cur, "result_output", -1);
  7790. ggml_build_forward_expand(gf, cur);
  7791. return gf;
  7792. }
  7793. struct ggml_cgraph * build_command_r() {
  7794. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7795. const int64_t n_embd_head = hparams.n_embd_head_v;
  7796. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7797. const float f_logit_scale = hparams.f_logit_scale;
  7798. struct ggml_tensor * cur;
  7799. struct ggml_tensor * inpL;
  7800. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7801. // inp_pos - contains the positions
  7802. struct ggml_tensor * inp_pos = build_inp_pos();
  7803. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7804. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7805. for (int il = 0; il < n_layer; ++il) {
  7806. // norm
  7807. cur = llm_build_norm(ctx0, inpL, hparams,
  7808. model.layers[il].attn_norm, NULL,
  7809. LLM_NORM, cb, il);
  7810. cb(cur, "attn_norm", il);
  7811. struct ggml_tensor * ffn_inp = cur;
  7812. // self-attention
  7813. {
  7814. // compute Q and K and RoPE them
  7815. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  7816. cb(Qcur, "Qcur", il);
  7817. if (model.layers[il].bq) {
  7818. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  7819. cb(Qcur, "Qcur", il);
  7820. }
  7821. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  7822. cb(Kcur, "Kcur", il);
  7823. if (model.layers[il].bk) {
  7824. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  7825. cb(Kcur, "Kcur", il);
  7826. }
  7827. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  7828. cb(Vcur, "Vcur", il);
  7829. if (model.layers[il].bv) {
  7830. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  7831. cb(Vcur, "Vcur", il);
  7832. }
  7833. if (model.layers[il].attn_q_norm) {
  7834. Qcur = ggml_view_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens,
  7835. ggml_element_size(Qcur) * n_embd_head,
  7836. ggml_element_size(Qcur) * n_embd_head * n_head,
  7837. 0);
  7838. cb(Qcur, "Qcur", il);
  7839. Kcur = ggml_view_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens,
  7840. ggml_element_size(Kcur) * n_embd_head,
  7841. ggml_element_size(Kcur) * n_embd_head * n_head_kv,
  7842. 0);
  7843. cb(Kcur, "Kcur", il);
  7844. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  7845. model.layers[il].attn_q_norm,
  7846. NULL,
  7847. LLM_NORM, cb, il);
  7848. cb(Qcur, "Qcur", il);
  7849. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  7850. model.layers[il].attn_k_norm,
  7851. NULL,
  7852. LLM_NORM, cb, il);
  7853. cb(Kcur, "Kcur", il);
  7854. }
  7855. Qcur = ggml_rope_custom(
  7856. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  7857. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7858. ext_factor, attn_factor, beta_fast, beta_slow
  7859. );
  7860. cb(Qcur, "Qcur", il);
  7861. Kcur = ggml_rope_custom(
  7862. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  7863. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7864. ext_factor, attn_factor, beta_fast, beta_slow
  7865. );
  7866. cb(Kcur, "Kcur", il);
  7867. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  7868. model.layers[il].wo, model.layers[il].bo,
  7869. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7870. }
  7871. if (il == n_layer - 1) {
  7872. // skip computing output for unused tokens
  7873. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7874. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7875. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  7876. ffn_inp = ggml_get_rows(ctx0, ffn_inp, inp_out_ids);
  7877. }
  7878. struct ggml_tensor * attn_out = cur;
  7879. // feed-forward network
  7880. {
  7881. cur = llm_build_ffn(ctx0, ffn_inp,
  7882. model.layers[il].ffn_up, NULL,
  7883. model.layers[il].ffn_gate, NULL,
  7884. model.layers[il].ffn_down, NULL,
  7885. NULL,
  7886. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  7887. cb(cur, "ffn_out", il);
  7888. }
  7889. // add together residual + FFN + self-attention
  7890. cur = ggml_add(ctx0, cur, inpL);
  7891. cur = ggml_add(ctx0, cur, attn_out);
  7892. cb(cur, "l_out", il);
  7893. // input for next layer
  7894. inpL = cur;
  7895. }
  7896. cur = inpL;
  7897. cur = llm_build_norm(ctx0, cur, hparams,
  7898. model.output_norm, NULL,
  7899. LLM_NORM, cb, -1);
  7900. cb(cur, "result_norm", -1);
  7901. // lm_head
  7902. cur = ggml_mul_mat(ctx0, model.output, cur);
  7903. if (f_logit_scale) {
  7904. cur = ggml_scale(ctx0, cur, f_logit_scale);
  7905. }
  7906. cb(cur, "result_output", -1);
  7907. ggml_build_forward_expand(gf, cur);
  7908. return gf;
  7909. }
  7910. };
  7911. static struct ggml_cgraph * llama_build_graph_defrag(llama_context & lctx, const std::vector<uint32_t> & ids) {
  7912. llama_batch dummy;
  7913. dummy.n_tokens = 0;
  7914. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  7915. struct llm_build_context llm(lctx, dummy, cb, false);
  7916. llm.init();
  7917. struct ggml_cgraph * result = llm.build_defrag(ids);
  7918. llm.free();
  7919. return result;
  7920. }
  7921. static struct ggml_cgraph * llama_build_graph_k_shift(llama_context & lctx) {
  7922. llama_batch dummy;
  7923. dummy.n_tokens = 0;
  7924. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  7925. struct llm_build_context llm(lctx, dummy, cb, false);
  7926. llm.init();
  7927. struct ggml_cgraph * result = llm.build_k_shift();
  7928. llm.free();
  7929. return result;
  7930. }
  7931. static struct ggml_cgraph * llama_build_graph_s_copy(llama_context & lctx) {
  7932. llama_batch dummy;
  7933. dummy.n_tokens = 0;
  7934. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  7935. struct llm_build_context llm(lctx, dummy, cb, false);
  7936. llm.init();
  7937. struct ggml_cgraph * result = llm.build_s_copy();
  7938. llm.free();
  7939. return result;
  7940. }
  7941. static struct ggml_cgraph * llama_build_graph(
  7942. llama_context & lctx,
  7943. const llama_batch & batch,
  7944. bool worst_case) {
  7945. const auto & model = lctx.model;
  7946. // this callback allows us to apply custom logic to each tensor (e.g. ggml-alloc, offloading, etc.)
  7947. llm_build_cb cb = [&](struct ggml_tensor * cur, const char * name, int il) {
  7948. if (il >= 0) {
  7949. ggml_format_name(cur, "%s-%d", name, il);
  7950. } else {
  7951. ggml_set_name(cur, name);
  7952. }
  7953. if (!lctx.cparams.offload_kqv) {
  7954. if (strcmp(name, "kqv_merged_cont") == 0) {
  7955. // all nodes between the KV store and the attention output are run on the CPU
  7956. ggml_backend_sched_set_tensor_backend(lctx.sched, cur, lctx.backend_cpu);
  7957. }
  7958. }
  7959. // norm may be automatically assigned to the backend of the previous layer, increasing data transfer between backends
  7960. // FIXME: fix in ggml_backend_sched
  7961. const bool full_offload = lctx.model.n_gpu_layers > (int)lctx.model.hparams.n_layer;
  7962. if (batch.n_tokens < 32 || full_offload) {
  7963. if (il != -1 && strcmp(name, "norm") == 0) {
  7964. for (auto * backend : lctx.backends) {
  7965. if (ggml_backend_buft_supports_backend(lctx.model.buft_layer[il].buft, backend)) {
  7966. ggml_backend_sched_set_tensor_backend(lctx.sched, cur, backend);
  7967. break;
  7968. }
  7969. }
  7970. }
  7971. }
  7972. };
  7973. struct ggml_cgraph * result = NULL;
  7974. struct llm_build_context llm(lctx, batch, cb, worst_case);
  7975. llm.init();
  7976. switch (model.arch) {
  7977. case LLM_ARCH_LLAMA:
  7978. {
  7979. result = llm.build_llama();
  7980. } break;
  7981. case LLM_ARCH_BAICHUAN:
  7982. {
  7983. result = llm.build_baichuan();
  7984. } break;
  7985. case LLM_ARCH_FALCON:
  7986. {
  7987. result = llm.build_falcon();
  7988. } break;
  7989. case LLM_ARCH_GROK:
  7990. {
  7991. result = llm.build_grok();
  7992. } break;
  7993. case LLM_ARCH_STARCODER:
  7994. {
  7995. result = llm.build_starcoder();
  7996. } break;
  7997. case LLM_ARCH_PERSIMMON:
  7998. {
  7999. result = llm.build_persimmon();
  8000. } break;
  8001. case LLM_ARCH_REFACT:
  8002. {
  8003. result = llm.build_refact();
  8004. } break;
  8005. case LLM_ARCH_BERT:
  8006. case LLM_ARCH_NOMIC_BERT:
  8007. {
  8008. result = llm.build_bert();
  8009. } break;
  8010. case LLM_ARCH_BLOOM:
  8011. {
  8012. result = llm.build_bloom();
  8013. } break;
  8014. case LLM_ARCH_MPT:
  8015. {
  8016. result = llm.build_mpt();
  8017. } break;
  8018. case LLM_ARCH_STABLELM:
  8019. {
  8020. result = llm.build_stablelm();
  8021. } break;
  8022. case LLM_ARCH_QWEN:
  8023. {
  8024. result = llm.build_qwen();
  8025. } break;
  8026. case LLM_ARCH_QWEN2:
  8027. {
  8028. result = llm.build_qwen2();
  8029. } break;
  8030. case LLM_ARCH_PHI2:
  8031. {
  8032. result = llm.build_phi2();
  8033. } break;
  8034. case LLM_ARCH_PLAMO:
  8035. {
  8036. result = llm.build_plamo();
  8037. } break;
  8038. case LLM_ARCH_GPT2:
  8039. {
  8040. result = llm.build_gpt2();
  8041. } break;
  8042. case LLM_ARCH_CODESHELL:
  8043. {
  8044. result = llm.build_codeshell();
  8045. } break;
  8046. case LLM_ARCH_ORION:
  8047. {
  8048. result = llm.build_orion();
  8049. } break;
  8050. case LLM_ARCH_INTERNLM2:
  8051. {
  8052. result = llm.build_internlm2();
  8053. } break;
  8054. case LLM_ARCH_MINICPM:
  8055. {
  8056. result = llm.build_minicpm();
  8057. } break;
  8058. case LLM_ARCH_GEMMA:
  8059. {
  8060. result = llm.build_gemma();
  8061. } break;
  8062. case LLM_ARCH_STARCODER2:
  8063. {
  8064. result = llm.build_starcoder2();
  8065. } break;
  8066. case LLM_ARCH_MAMBA:
  8067. {
  8068. result = llm.build_mamba();
  8069. } break;
  8070. case LLM_ARCH_XVERSE:
  8071. {
  8072. result = llm.build_xverse();
  8073. } break;
  8074. case LLM_ARCH_COMMAND_R:
  8075. {
  8076. result = llm.build_command_r();
  8077. } break;
  8078. default:
  8079. GGML_ASSERT(false);
  8080. }
  8081. llm.free();
  8082. return result;
  8083. }
  8084. static void llama_set_k_shift(llama_context & lctx) {
  8085. const int64_t kv_size = lctx.kv_self.size;
  8086. assert(ggml_backend_buffer_is_host(lctx.inp_K_shift->buffer));
  8087. int32_t * data = (int32_t *) lctx.inp_K_shift->data;
  8088. for (int i = 0; i < kv_size; ++i) {
  8089. data[i] = lctx.kv_self.cells[i].delta;
  8090. }
  8091. }
  8092. static void llama_set_s_copy(llama_context & lctx) {
  8093. const int64_t kv_size = lctx.kv_self.size;
  8094. assert(ggml_backend_buffer_is_host(lctx.inp_s_copy->buffer));
  8095. int32_t * data = (int32_t *) lctx.inp_s_copy->data;
  8096. for (int i = 0; i < kv_size; ++i) {
  8097. data[i] = lctx.kv_self.cells[i].src;
  8098. }
  8099. }
  8100. static void llama_set_inputs(llama_context & lctx, const llama_batch & batch) {
  8101. //
  8102. // set input data
  8103. //
  8104. const auto & hparams = lctx.model.hparams;
  8105. const auto & cparams = lctx.cparams;
  8106. const auto & kv_self = lctx.kv_self;
  8107. if (batch.token) {
  8108. const int64_t n_tokens = batch.n_tokens;
  8109. ggml_backend_tensor_set(lctx.inp_tokens, batch.token, 0, n_tokens*ggml_element_size(lctx.inp_tokens));
  8110. }
  8111. if (batch.embd) {
  8112. const int64_t n_embd = hparams.n_embd;
  8113. const int64_t n_tokens = batch.n_tokens;
  8114. ggml_backend_tensor_set(lctx.inp_embd, batch.embd, 0, n_tokens*n_embd*ggml_element_size(lctx.inp_embd));
  8115. }
  8116. if (batch.pos && lctx.inp_pos) {
  8117. const int64_t n_tokens = batch.n_tokens;
  8118. ggml_backend_tensor_set(lctx.inp_pos, batch.pos, 0, n_tokens*ggml_element_size(lctx.inp_pos));
  8119. }
  8120. if (hparams.causal_attn || cparams.pooling_type == LLAMA_POOLING_TYPE_NONE) {
  8121. GGML_ASSERT(lctx.inp_out_ids && "every model that can must skip unused outputs");
  8122. const int64_t n_tokens = batch.n_tokens;
  8123. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_out_ids->buffer));
  8124. int32_t * data = (int32_t *) lctx.inp_out_ids->data;
  8125. if (lctx.n_outputs == n_tokens) {
  8126. for (int i = 0; i < n_tokens; ++i) {
  8127. data[i] = i;
  8128. }
  8129. } else if (batch.logits) {
  8130. int32_t n_outputs = 0;
  8131. for (int i = 0; i < n_tokens; ++i) {
  8132. if (batch.logits[i]) {
  8133. data[n_outputs++] = i;
  8134. }
  8135. }
  8136. // the graph needs to have been passed the correct number of outputs
  8137. GGML_ASSERT(lctx.n_outputs == n_outputs);
  8138. } else if (lctx.n_outputs == 1) {
  8139. // only keep last output
  8140. data[0] = n_tokens - 1;
  8141. } else {
  8142. GGML_ASSERT(lctx.n_outputs == 0);
  8143. }
  8144. }
  8145. GGML_ASSERT(
  8146. // (!a || b) is a logical implication (a -> b)
  8147. // !hparams.causal_attn -> !cparams.causal_attn
  8148. (hparams.causal_attn || !cparams.causal_attn) &&
  8149. "causal attention with embedding models is not supported"
  8150. );
  8151. if (lctx.inp_KQ_mask) {
  8152. // NOTE: hparams.causal_attn indicates the model is capable of generation and uses the kv cache.
  8153. if (cparams.causal_attn) {
  8154. const int64_t n_kv = kv_self.n;
  8155. const int64_t n_tokens = batch.n_tokens;
  8156. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  8157. float * data = (float *) lctx.inp_KQ_mask->data;
  8158. // For causal attention, use only the previous KV cells
  8159. // of the correct sequence for each token of the batch.
  8160. // It's assumed that if a token in the batch has multiple sequences, they are equivalent.
  8161. for (int h = 0; h < 1; ++h) {
  8162. for (int j = 0; j < n_tokens; ++j) {
  8163. const llama_pos pos = batch.pos[j];
  8164. const llama_seq_id seq_id = batch.seq_id[j][0];
  8165. for (int i = 0; i < n_kv; ++i) {
  8166. float f;
  8167. if (!lctx.kv_self.cells[i].has_seq_id(seq_id) || lctx.kv_self.cells[i].pos > pos) {
  8168. f = -INFINITY;
  8169. } else {
  8170. f = 0.0f;
  8171. }
  8172. data[h*(n_kv*n_tokens) + j*n_kv + i] = f;
  8173. }
  8174. }
  8175. }
  8176. } else {
  8177. // when using kv cache, the mask needs to match the kv cache size
  8178. const int64_t n_tokens = batch.n_tokens;
  8179. const int64_t n_stride = hparams.causal_attn ? kv_self.n : n_tokens;
  8180. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  8181. float * data = (float *) lctx.inp_KQ_mask->data;
  8182. for (int h = 0; h < 1; ++h) {
  8183. for (int j = 0; j < n_tokens; ++j) {
  8184. const llama_seq_id seq_id = batch.seq_id[j][0];
  8185. for (int i = 0; i < n_tokens; ++i) {
  8186. float f = -INFINITY;
  8187. for (int s = 0; s < batch.n_seq_id[i]; ++s) {
  8188. if (batch.seq_id[i][s] == seq_id) {
  8189. f = 0.0f;
  8190. break;
  8191. }
  8192. }
  8193. data[h*(n_tokens*n_tokens) + j*n_stride + i] = f;
  8194. }
  8195. for (int i = n_tokens; i < n_stride; ++i) {
  8196. data[h*(n_tokens*n_tokens) + j*n_stride + i] = -INFINITY;
  8197. }
  8198. }
  8199. }
  8200. }
  8201. }
  8202. if (hparams.need_kq_pos) {
  8203. const int64_t n_kv = kv_self.n;
  8204. GGML_ASSERT(lctx.inp_KQ_pos);
  8205. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_pos->buffer));
  8206. float * data = (float *) lctx.inp_KQ_pos->data;
  8207. for (int i = 0; i < n_kv; ++i) {
  8208. data[i] = float(lctx.kv_self.cells[i].pos);
  8209. }
  8210. }
  8211. if (cparams.pooling_type == LLAMA_POOLING_TYPE_MEAN) {
  8212. const int64_t n_tokens = batch.n_tokens;
  8213. GGML_ASSERT(lctx.inp_mean);
  8214. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_mean->buffer));
  8215. float * data = (float *) lctx.inp_mean->data;
  8216. memset(lctx.inp_mean->data, 0, n_tokens * n_tokens * ggml_element_size(lctx.inp_mean));
  8217. std::vector<uint64_t> sum(n_tokens, 0);
  8218. for (int i = 0; i < n_tokens; ++i) {
  8219. const llama_seq_id seq_id = batch.seq_id[i][0];
  8220. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == MEAN");
  8221. sum[seq_id] += 1;
  8222. }
  8223. std::vector<float> div(n_tokens, 0.0f);
  8224. for (int i = 0; i < n_tokens; ++i) {
  8225. const uint64_t s = sum[i];
  8226. if (s > 0) {
  8227. div[i] = 1.0f/float(s);
  8228. }
  8229. }
  8230. for (int i = 0; i < n_tokens; ++i) {
  8231. const llama_seq_id seq_id = batch.seq_id[i][0];
  8232. data[seq_id*n_tokens + i] = div[seq_id];
  8233. }
  8234. }
  8235. if (cparams.pooling_type == LLAMA_POOLING_TYPE_CLS) {
  8236. const int64_t n_tokens = batch.n_tokens;
  8237. GGML_ASSERT(lctx.inp_cls);
  8238. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_cls->buffer));
  8239. uint32_t * data = (uint32_t *) lctx.inp_cls->data;
  8240. memset(lctx.inp_cls->data, 0, n_tokens * ggml_element_size(lctx.inp_cls));
  8241. for (int i = 0; i < n_tokens; ++i) {
  8242. const llama_seq_id seq_id = batch.seq_id[i][0];
  8243. const llama_pos pos = batch.pos[i];
  8244. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == CLS");
  8245. if (pos == 0) {
  8246. data[seq_id] = i;
  8247. }
  8248. }
  8249. }
  8250. if (kv_self.recurrent) {
  8251. const int64_t n_kv = kv_self.n;
  8252. if (lctx.inp_s_mask) {
  8253. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_s_mask->buffer));
  8254. float * data = (float *) lctx.inp_s_mask->data;
  8255. // states which are not affected by the current batch are left untouched
  8256. for (int i = 0; i < n_kv; ++i) {
  8257. llama_seq_id seq_id = i + lctx.kv_self.head;
  8258. llama_kv_cell & kv_cell = lctx.kv_self.cells[seq_id];
  8259. bool has_self_seq = kv_cell.has_seq_id(seq_id);
  8260. data[i] = (float) has_self_seq;
  8261. // ensure current sequences will be kept
  8262. if (!has_self_seq && kv_cell.pos >= 0) {
  8263. kv_cell.seq_id.insert(seq_id);
  8264. }
  8265. }
  8266. }
  8267. // For Mamba (and other recurrent architectures),
  8268. // update the correct state(s)/sequence(s) for each token of the batch.
  8269. // Like with the KQ_mask, if a token in the batch has multiple sequences,
  8270. // they are assumed to be equivalent (not here, but in ggml_ssm_scan and ggml_ssm_conv).
  8271. if (lctx.inp_s_seq) {
  8272. const int64_t n_tokens = batch.n_tokens;
  8273. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_s_seq->buffer));
  8274. int32_t * data = (int32_t *) lctx.inp_s_seq->data;
  8275. for (int j = 0; j < n_tokens; ++j) {
  8276. const int32_t n_seq = batch.n_seq_id[j];
  8277. GGML_ASSERT(0 < n_seq); // a token should be part of at least 1 sequence
  8278. for (int i = 0; i < n_kv; ++i) {
  8279. if (i < n_seq) {
  8280. // for this type of model, the head is the minimum seq_id of the batch
  8281. data[j*n_kv + i] = batch.seq_id[j][i] - kv_self.head;
  8282. } else {
  8283. data[j*n_kv + i] = -1;
  8284. }
  8285. }
  8286. }
  8287. }
  8288. }
  8289. }
  8290. // Make sure enough space is available for outputs.
  8291. // Returns max number of outputs for which space was reserved.
  8292. static size_t llama_output_reserve(llama_context & lctx, size_t n_outputs) {
  8293. const auto & cparams = lctx.cparams;
  8294. const auto & hparams = lctx.model.hparams;
  8295. const size_t n_outputs_max = std::max(n_outputs, (size_t) cparams.n_seq_max);
  8296. const auto n_batch = cparams.n_batch;
  8297. const auto n_vocab = hparams.n_vocab;
  8298. const auto n_embd = hparams.n_embd;
  8299. // TODO: use a per-batch flag for logits presence instead
  8300. const bool has_logits = cparams.causal_attn;
  8301. const bool has_embd = cparams.embeddings && (hparams.causal_attn || cparams.pooling_type == LLAMA_POOLING_TYPE_NONE);
  8302. const size_t logits_size = has_logits ? n_vocab*n_outputs_max : 0;
  8303. const size_t embd_size = has_embd ? n_embd*n_outputs_max : 0;
  8304. if (lctx.output_ids.empty()) {
  8305. // init, never resized afterwards
  8306. lctx.output_ids.resize(n_batch);
  8307. }
  8308. const size_t prev_size = lctx.buf_output ? ggml_backend_buffer_get_size(lctx.buf_output) : 0;
  8309. const size_t new_size = (logits_size + embd_size) * sizeof(float);
  8310. // alloc only when more than the current capacity is required
  8311. // TODO: also consider shrinking the buffer
  8312. if (!lctx.buf_output || prev_size < new_size) {
  8313. if (lctx.buf_output) {
  8314. #ifndef NDEBUG
  8315. // This doesn't happen often, but may be annoying in some cases (like the HellaSwag benchmark)
  8316. 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);
  8317. #endif
  8318. ggml_backend_buffer_free(lctx.buf_output);
  8319. lctx.buf_output = nullptr;
  8320. lctx.logits = nullptr;
  8321. lctx.embd = nullptr;
  8322. }
  8323. lctx.buf_output = ggml_backend_buft_alloc_buffer(llama_default_buffer_type_cpu(true), new_size);
  8324. if (lctx.buf_output == nullptr) {
  8325. LLAMA_LOG_ERROR("%s: failed to allocate output buffer of size %.2f MiB\n", __func__, new_size / (1024.0 * 1024.0));
  8326. return 0;
  8327. }
  8328. }
  8329. float * output_base = (float *) ggml_backend_buffer_get_base(lctx.buf_output);
  8330. lctx.logits = has_logits ? output_base : nullptr;
  8331. lctx.embd = has_embd ? output_base + logits_size : nullptr;
  8332. lctx.output_size = n_outputs_max;
  8333. lctx.logits_size = logits_size;
  8334. lctx.embd_size = embd_size;
  8335. // set all ids as invalid (negative)
  8336. std::fill(lctx.output_ids.begin(), lctx.output_ids.end(), -1);
  8337. ggml_backend_buffer_clear(lctx.buf_output, 0);
  8338. lctx.n_outputs = 0;
  8339. return n_outputs_max;
  8340. }
  8341. static void llama_graph_compute(
  8342. llama_context & lctx,
  8343. ggml_cgraph * gf,
  8344. int n_threads) {
  8345. #ifdef GGML_USE_MPI
  8346. const int64_t n_layer = lctx.model.hparams.n_layer;
  8347. ggml_mpi_graph_compute_pre(lctx.ctx_mpi, gf, n_layer);
  8348. #endif
  8349. #ifdef GGML_USE_METAL
  8350. if (ggml_backend_is_metal(lctx.backend_metal)) {
  8351. ggml_backend_metal_set_n_cb(lctx.backend_metal, n_threads);
  8352. }
  8353. #endif
  8354. if (lctx.backend_cpu != nullptr) {
  8355. ggml_backend_cpu_set_n_threads(lctx.backend_cpu, n_threads);
  8356. ggml_backend_cpu_set_abort_callback(lctx.backend_cpu, lctx.abort_callback, lctx.abort_callback_data);
  8357. }
  8358. ggml_backend_sched_graph_compute_async(lctx.sched, gf);
  8359. // fprintf(stderr, "splits: %d\n", ggml_backend_sched_get_n_splits(lctx.sched));
  8360. #ifdef GGML_USE_MPI
  8361. ggml_mpi_graph_compute_post(lctx.ctx_mpi, gf, n_layer);
  8362. #endif
  8363. }
  8364. // decode a batch of tokens by evaluating the transformer
  8365. //
  8366. // - lctx: llama context
  8367. // - batch: batch to evaluate
  8368. //
  8369. // return 0 on success
  8370. // return positive int on warning
  8371. // return negative int on error
  8372. //
  8373. static int llama_decode_internal(
  8374. llama_context & lctx,
  8375. llama_batch batch_all) { // TODO: rename back to batch
  8376. const uint32_t n_tokens_all = batch_all.n_tokens;
  8377. if (n_tokens_all == 0) {
  8378. LLAMA_LOG_ERROR("%s: n_tokens == 0", __func__);
  8379. return -1;
  8380. }
  8381. const auto & model = lctx.model;
  8382. const auto & hparams = model.hparams;
  8383. const auto & cparams = lctx.cparams;
  8384. GGML_ASSERT((!batch_all.token && batch_all.embd) || (batch_all.token && !batch_all.embd)); // NOLINT
  8385. GGML_ASSERT(n_tokens_all <= cparams.n_batch);
  8386. GGML_ASSERT((cparams.causal_attn || cparams.n_ubatch >= n_tokens_all) && "non-causal attention requires n_ubatch >= n_tokens");
  8387. if (lctx.t_compute_start_us == 0) {
  8388. lctx.t_compute_start_us = ggml_time_us();
  8389. }
  8390. lctx.n_queued_tokens += n_tokens_all;
  8391. #ifdef GGML_USE_MPI
  8392. // TODO: needs fix after #3228
  8393. GGML_ASSERT(false && "not implemented");
  8394. //ggml_mpi_eval_init(lctx.ctx_mpi, &n_tokens, &n_past, &n_threads);
  8395. #endif
  8396. auto & kv_self = lctx.kv_self;
  8397. const int64_t n_embd = hparams.n_embd;
  8398. const int64_t n_vocab = hparams.n_vocab;
  8399. uint32_t n_outputs = 0;
  8400. uint32_t n_outputs_prev = 0;
  8401. const auto n_ubatch = cparams.n_ubatch;
  8402. std::vector<llama_pos> pos;
  8403. std::vector<int32_t> n_seq_id;
  8404. std::vector<llama_seq_id *> seq_id_arr;
  8405. std::vector<std::vector<llama_seq_id>> seq_id;
  8406. // count outputs
  8407. if (batch_all.logits) {
  8408. for (uint32_t i = 0; i < n_tokens_all; ++i) {
  8409. n_outputs += batch_all.logits[i] != 0;
  8410. }
  8411. } else if (lctx.logits_all || (cparams.embeddings && cparams.pooling_type != LLAMA_POOLING_TYPE_NONE)) {
  8412. n_outputs = n_tokens_all;
  8413. } else {
  8414. // keep last output only
  8415. n_outputs = 1;
  8416. }
  8417. // reserve output buffer
  8418. if (llama_output_reserve(lctx, n_outputs) < n_outputs) {
  8419. LLAMA_LOG_ERROR("%s: could not reserve space for batch with %u outputs\n", __func__, n_outputs);
  8420. return -2;
  8421. };
  8422. // set output mappings
  8423. if (batch_all.logits) {
  8424. int32_t i_logits = 0;
  8425. for (uint32_t i = 0; i < n_tokens_all; ++i) {
  8426. if (batch_all.logits[i]) {
  8427. lctx.output_ids[i] = i_logits++;
  8428. }
  8429. }
  8430. } else {
  8431. for (uint32_t i = 0; i < n_outputs; ++i) {
  8432. lctx.output_ids[i] = i;
  8433. }
  8434. }
  8435. for (uint32_t cur_token = 0; cur_token < n_tokens_all; cur_token += n_ubatch) {
  8436. const uint32_t n_tokens = std::min(n_ubatch, n_tokens_all - cur_token);
  8437. llama_batch u_batch = {
  8438. /* .n_tokens = */ (int32_t) n_tokens,
  8439. /* .token = */ batch_all.token ? batch_all.token + cur_token : nullptr,
  8440. /* .embd = */ batch_all.embd ? batch_all.embd + cur_token*n_embd : nullptr,
  8441. /* .pos = */ batch_all.pos ? batch_all.pos + cur_token : nullptr,
  8442. /* .n_seq_id = */ batch_all.n_seq_id ? batch_all.n_seq_id + cur_token : nullptr,
  8443. /* .seq_id = */ batch_all.seq_id ? batch_all.seq_id + cur_token : nullptr,
  8444. /* .logits = */ batch_all.logits ? batch_all.logits + cur_token : nullptr,
  8445. /* .all_pos_0 = */ batch_all.all_pos_0 + (llama_pos) cur_token*batch_all.all_pos_1,
  8446. /* .all_pos_1 = */ batch_all.all_pos_1,
  8447. /* .all_seq_id = */ batch_all.all_seq_id,
  8448. };
  8449. // count the outputs in this u_batch
  8450. {
  8451. int32_t n_outputs_new = 0;
  8452. if (u_batch.logits) {
  8453. for (uint32_t i = 0; i < n_tokens; i++) {
  8454. n_outputs_new += u_batch.logits[i] != 0;
  8455. }
  8456. } else if (n_outputs == n_tokens_all) {
  8457. n_outputs_new = n_tokens;
  8458. } else {
  8459. // keep last output only
  8460. if (cur_token + n_tokens >= n_tokens_all) {
  8461. n_outputs_new = 1;
  8462. }
  8463. }
  8464. // needs to happen before the graph is built
  8465. lctx.n_outputs = n_outputs_new;
  8466. }
  8467. int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  8468. GGML_ASSERT(n_threads > 0);
  8469. // helpers for smoother batch API transition
  8470. // after deprecating the llama_eval calls, these will be removed
  8471. if (u_batch.pos == nullptr) {
  8472. pos.resize(n_tokens);
  8473. for (uint32_t i = 0; i < n_tokens; i++) {
  8474. pos[i] = u_batch.all_pos_0 + i*u_batch.all_pos_1;
  8475. }
  8476. u_batch.pos = pos.data();
  8477. }
  8478. if (u_batch.seq_id == nullptr) {
  8479. n_seq_id.resize(n_tokens);
  8480. seq_id.resize(n_tokens);
  8481. seq_id_arr.resize(n_tokens);
  8482. for (uint32_t i = 0; i < n_tokens; i++) {
  8483. n_seq_id[i] = 1;
  8484. seq_id[i].resize(1);
  8485. seq_id[i][0] = u_batch.all_seq_id;
  8486. seq_id_arr[i] = seq_id[i].data();
  8487. }
  8488. u_batch.n_seq_id = n_seq_id.data();
  8489. u_batch.seq_id = seq_id_arr.data();
  8490. }
  8491. // non-causal masks do not use the KV cache
  8492. if (hparams.causal_attn) {
  8493. llama_kv_cache_update(&lctx);
  8494. // if we have enough unused cells before the current head ->
  8495. // better to start searching from the beginning of the cache, hoping to fill it
  8496. if (kv_self.head > kv_self.used + 2*n_tokens) {
  8497. kv_self.head = 0;
  8498. }
  8499. if (!llama_kv_cache_find_slot(kv_self, u_batch)) {
  8500. return 1;
  8501. }
  8502. if (!kv_self.recurrent) {
  8503. // a heuristic, to avoid attending the full cache if it is not yet utilized
  8504. // after enough generations, the benefit from this heuristic disappears
  8505. // if we start defragmenting the cache, the benefit from this will be more important
  8506. kv_self.n = std::min(kv_self.size, std::max(32u, GGML_PAD(llama_kv_cache_cell_max(kv_self), 32)));
  8507. //kv_self.n = llama_kv_cache_cell_max(kv_self);
  8508. }
  8509. }
  8510. //printf("kv_self.n = %5d, kv_self.used = %5d, kv_self.head = %5d\n", kv_self.n, kv_self.used, kv_self.head);
  8511. ggml_backend_sched_reset(lctx.sched);
  8512. ggml_backend_sched_set_eval_callback(lctx.sched, lctx.cparams.cb_eval, lctx.cparams.cb_eval_user_data);
  8513. ggml_cgraph * gf = llama_build_graph(lctx, u_batch, false);
  8514. // the output is always the last tensor in the graph
  8515. struct ggml_tensor * res = gf->nodes[gf->n_nodes - 1];
  8516. struct ggml_tensor * embd = gf->nodes[gf->n_nodes - 2];
  8517. if (lctx.n_outputs == 0) {
  8518. // no output
  8519. res = nullptr;
  8520. embd = nullptr;
  8521. } else if (!hparams.causal_attn) {
  8522. res = nullptr; // do not extract logits for embedding models such as BERT
  8523. // token or sequence embeddings
  8524. embd = gf->nodes[gf->n_nodes - 1];
  8525. GGML_ASSERT(strcmp(embd->name, "result_embd") == 0 || strcmp(embd->name, "result_embd_pooled") == 0);
  8526. } else if (cparams.embeddings) {
  8527. // the embeddings could be in the second to last tensor, or any of the previous tensors
  8528. int i_embd = gf->n_nodes - 2;
  8529. for (int i = 3; strcmp(embd->name, "result_norm") != 0; ++i) {
  8530. i_embd = gf->n_nodes - i;
  8531. if (i_embd < 0) { break; }
  8532. embd = gf->nodes[i_embd];
  8533. }
  8534. GGML_ASSERT(i_embd >= 0 && "missing result_norm tensor");
  8535. // TODO: use a per-batch flag to know when to skip logits while keeping embeddings
  8536. if (!cparams.causal_attn) {
  8537. res = nullptr; // do not extract logits when not needed
  8538. // skip computing logits
  8539. // TODO: is this safe?
  8540. gf->n_nodes = i_embd + 1;
  8541. }
  8542. } else {
  8543. embd = nullptr; // do not extract embeddings when not needed
  8544. GGML_ASSERT(strcmp(res->name, "result_output") == 0 && "missing result_output tensor");
  8545. }
  8546. // 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);
  8547. // for big prompts, if BLAS is enabled, it is better to use only one thread
  8548. // otherwise, the threads are spin-lock waiting for the BLAS calls and are degrading the performance
  8549. // TODO: this is mostly important for Apple Silicon where CBLAS is still performing very well
  8550. // we still need some threads to process all non-mul_mat ops, but not too much to avoid interfering
  8551. // with the BLAS calls. need a better solution
  8552. // MoE Special Case: This logic applies when hparams.n_expert == 0, i.e. the model is NOT an MoE model. When an MoE is
  8553. // being processed then Accelerate/BLAS will not be involved, so capping would limit performance.
  8554. if (n_tokens >= 32 && hparams.n_expert == 0 && ggml_cpu_has_blas() && !ggml_cpu_has_gpublas()) {
  8555. n_threads = std::min(4, n_threads);
  8556. }
  8557. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  8558. llama_set_inputs(lctx, u_batch);
  8559. llama_graph_compute(lctx, gf, n_threads);
  8560. // update the kv ring buffer
  8561. {
  8562. kv_self.head += n_tokens;
  8563. // Ensure kv cache head points to a valid index.
  8564. if (kv_self.head >= kv_self.size) {
  8565. kv_self.head = 0;
  8566. }
  8567. }
  8568. #ifdef GGML_PERF
  8569. // print timing information per ggml operation (for debugging purposes)
  8570. // requires GGML_PERF to be defined
  8571. ggml_graph_print(gf);
  8572. #endif
  8573. // plot the computation graph in dot format (for debugging purposes)
  8574. //if (n_past%100 == 0) {
  8575. // ggml_graph_dump_dot(gf, NULL, "llama.dot");
  8576. //}
  8577. // extract logits
  8578. if (res) {
  8579. ggml_backend_t backend_res = ggml_backend_sched_get_tensor_backend(lctx.sched, res);
  8580. GGML_ASSERT(backend_res != nullptr);
  8581. GGML_ASSERT(lctx.logits != nullptr);
  8582. float * logits_out = lctx.logits + n_outputs_prev*n_vocab;
  8583. const int32_t n_outputs_new = lctx.n_outputs;
  8584. if (n_outputs_new) {
  8585. GGML_ASSERT( n_outputs_prev + n_outputs_new <= n_outputs);
  8586. GGML_ASSERT((n_outputs_prev + n_outputs_new)*n_vocab <= (int64_t) lctx.logits_size);
  8587. ggml_backend_tensor_get_async(backend_res, res, logits_out, 0, n_outputs_new*n_vocab*sizeof(float));
  8588. }
  8589. }
  8590. // extract embeddings
  8591. if (embd) {
  8592. ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend(lctx.sched, embd);
  8593. GGML_ASSERT(backend_embd != nullptr);
  8594. switch (cparams.pooling_type) {
  8595. case LLAMA_POOLING_TYPE_NONE:
  8596. {
  8597. // extract token embeddings
  8598. GGML_ASSERT(lctx.embd != nullptr);
  8599. float * embd_out = lctx.embd + n_outputs_prev*n_embd;
  8600. const int32_t n_outputs_new = lctx.n_outputs;
  8601. if (n_outputs_new) {
  8602. GGML_ASSERT( n_outputs_prev + n_outputs_new <= n_outputs);
  8603. GGML_ASSERT((n_outputs_prev + n_outputs_new)*n_embd <= (int64_t) lctx.embd_size);
  8604. ggml_backend_tensor_get_async(backend_embd, embd, embd_out, 0, n_outputs_new*n_embd*sizeof(float));
  8605. }
  8606. } break;
  8607. case LLAMA_POOLING_TYPE_CLS:
  8608. case LLAMA_POOLING_TYPE_MEAN:
  8609. {
  8610. GGML_ASSERT(strcmp(embd->name, "result_embd_pooled") == 0);
  8611. // extract sequence embeddings
  8612. auto & embd_seq_out = lctx.embd_seq;
  8613. embd_seq_out.clear();
  8614. for (uint32_t i = 0; i < n_tokens; i++) {
  8615. const llama_seq_id seq_id = u_batch.seq_id[i][0];
  8616. if (embd_seq_out.find(seq_id) != embd_seq_out.end()) {
  8617. continue;
  8618. }
  8619. embd_seq_out[seq_id].resize(n_embd);
  8620. ggml_backend_tensor_get_async(backend_embd, embd, embd_seq_out[seq_id].data(), (n_embd*seq_id)*sizeof(float), n_embd*sizeof(float));
  8621. }
  8622. } break;
  8623. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  8624. {
  8625. GGML_ASSERT(false && "unknown pooling type");
  8626. } break;
  8627. }
  8628. }
  8629. n_outputs_prev += lctx.n_outputs;
  8630. }
  8631. // set to total number of outputs in the batch, for use in llama_get_logits_ith
  8632. lctx.n_outputs = n_outputs;
  8633. // wait for the computation to finish (automatically done when obtaining the model output)
  8634. //llama_synchronize(&lctx);
  8635. // decide if we need to defrag the kv cache
  8636. if (cparams.causal_attn && cparams.defrag_thold >= 0.0f) {
  8637. const float fragmentation = kv_self.n >= 128 ? 1.0f - float(kv_self.used)/float(kv_self.n) : 0.0f;
  8638. // queue defragmentation for next llama_kv_cache_update
  8639. if (fragmentation > cparams.defrag_thold) {
  8640. //LLAMA_LOG_INFO("fragmentation: %.2f\n", fragmentation);
  8641. llama_kv_cache_defrag(kv_self);
  8642. }
  8643. }
  8644. return 0;
  8645. }
  8646. // find holes from the beginning of the KV cache and fill them by moving data from the end of the cache
  8647. static void llama_kv_cache_defrag_internal(struct llama_context & lctx) {
  8648. auto & kv_self = lctx.kv_self;
  8649. const auto & hparams = lctx.model.hparams;
  8650. const uint32_t n_layer = hparams.n_layer;
  8651. const uint32_t n_kv = llama_kv_cache_cell_max(kv_self);
  8652. const uint32_t n_used = kv_self.used;
  8653. assert(n_used <= n_kv);
  8654. //const int64_t t_start = ggml_time_us();
  8655. // number of cells moved
  8656. uint32_t n_moves = 0;
  8657. // each move requires 6*n_layer tensors (see build_defrag)
  8658. // - source view, destination view, copy operation
  8659. // - x2 for keys and values
  8660. const uint32_t max_moves = LLAMA_MAX_NODES/(6*n_layer);
  8661. // determine which KV cells to move where
  8662. //
  8663. // cell i moves to ids[i]
  8664. //
  8665. // if ids[i] == i || ids[i] == n_kv, then cell i is not moved
  8666. //
  8667. std::vector<uint32_t> ids(n_kv, n_kv);
  8668. for (uint32_t i0 = 0; i0 < n_used; ++i0) {
  8669. const auto & cell0 = kv_self.cells[i0];
  8670. if (!cell0.is_empty()) {
  8671. ids[i0] = i0;
  8672. continue;
  8673. }
  8674. // found a hole - fill it with data from the end of the cache
  8675. uint32_t nh = 1;
  8676. // determine the size of the hole
  8677. while (i0 + nh < n_used && kv_self.cells[i0 + nh].is_empty()) {
  8678. nh++;
  8679. }
  8680. uint32_t nf = 0;
  8681. uint32_t is = n_kv - 1;
  8682. // starting from the end, find nh non-empty cells
  8683. for (; is > i0; --is) {
  8684. const auto & cell1 = kv_self.cells[is];
  8685. if (cell1.is_empty() || ids[is] != n_kv) {
  8686. continue;
  8687. }
  8688. // non-empty cell which is not yet moved
  8689. nf++;
  8690. if (nf == nh) {
  8691. break;
  8692. }
  8693. }
  8694. // this can only happen if `n_used` is not accurate, which would be a bug
  8695. GGML_ASSERT(nf == nh && "KV defrag bug: nf != nh");
  8696. nf = 0;
  8697. uint32_t i1 = is;
  8698. // are we moving a continuous block of memory?
  8699. bool cont = false;
  8700. // should we stop searching for the next move?
  8701. bool stop = false;
  8702. // go back and move the nf cells to the hole
  8703. for (; i1 < n_kv; ++i1) {
  8704. auto & cell1 = kv_self.cells[i1];
  8705. if (cell1.is_empty() || ids[i1] != n_kv) {
  8706. if (n_moves == max_moves) {
  8707. stop = true;
  8708. break;
  8709. }
  8710. cont = false;
  8711. continue;
  8712. }
  8713. // this cell goes to (i0 + nf)
  8714. ids[i1] = i0 + nf;
  8715. // move the cell meta data
  8716. kv_self.cells[i0 + nf] = cell1;
  8717. // clear the old cell and move the head there
  8718. cell1 = llama_kv_cell();
  8719. kv_self.head = n_used;
  8720. if (!cont) {
  8721. n_moves++;
  8722. cont = true;
  8723. }
  8724. nf++;
  8725. if (nf == nh) {
  8726. break;
  8727. }
  8728. }
  8729. if (stop || n_moves == max_moves) {
  8730. break;
  8731. }
  8732. //LLAMA_LOG_INFO("(tmp log) KV defrag: move [%u, %u) to [%u, %u)\n", is, i1 + 1, i0, i0 + nh);
  8733. i0 += nh - 1;
  8734. }
  8735. if (n_moves == 0) {
  8736. return;
  8737. }
  8738. //LLAMA_LOG_INFO("(tmp log) KV defrag cell moves: %u\n", n_moves);
  8739. //LLAMA_LOG_INFO("expected gf nodes: %u\n", 6*n_moves*n_layer);
  8740. #if 0
  8741. // CPU defrag
  8742. //
  8743. // TODO: optimizations are possible:
  8744. // - multiple threads
  8745. // - avoid copying to the host memory when already there
  8746. //
  8747. // likely not worth the effort, as we have ggml_graph based defrag
  8748. //
  8749. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  8750. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  8751. const uint32_t kv_size = kv_self.size;
  8752. std::vector<uint8_t> buf_k;
  8753. std::vector<uint8_t> buf_v;
  8754. for (uint32_t il = 0; il < n_layer; ++il) {
  8755. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  8756. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_size);
  8757. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  8758. const size_t v_size = ggml_row_size (kv_self.v_l[il]->type, n_embd_v_gqa*kv_size);
  8759. buf_k.resize(k_size);
  8760. buf_v.resize(v_size);
  8761. ggml_backend_tensor_get(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  8762. ggml_backend_tensor_get(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  8763. // batch move [i, i+nm) to [id, id+nm)
  8764. // note: cells can move only to a lower index
  8765. for (uint32_t i = 0; i < n_kv; ++i) {
  8766. const uint32_t id = ids[i];
  8767. if (i == id || id == n_kv) {
  8768. continue;
  8769. }
  8770. uint32_t nm = 1;
  8771. while (i + nm < n_kv && ids[i + nm] == id + nm) {
  8772. nm++;
  8773. }
  8774. // move keys
  8775. {
  8776. const int64_t os = i*k_size_row;
  8777. const int64_t od = id*k_size_row;
  8778. memcpy(buf_k.data() + od, buf_k.data() + os, nm*k_size_row);
  8779. }
  8780. // move values (note: they are transposed)
  8781. {
  8782. const int64_t os = i;
  8783. const int64_t od = id;
  8784. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  8785. 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);
  8786. }
  8787. }
  8788. i += nm - 1;
  8789. }
  8790. ggml_backend_tensor_set(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  8791. ggml_backend_tensor_set(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  8792. }
  8793. #else
  8794. // ggml_graph defrag
  8795. ggml_backend_sched_reset(lctx.sched);
  8796. ggml_cgraph * gf = llama_build_graph_defrag(lctx, ids);
  8797. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  8798. #endif
  8799. //const int64_t t_end = ggml_time_us();
  8800. //LLAMA_LOG_INFO("(tmp log) KV defrag time: %.3f ms\n", (t_end - t_start)/1000.0);
  8801. }
  8802. static void llama_kv_cache_update_internal(struct llama_context & lctx) {
  8803. bool need_reserve = false;
  8804. // apply K-shift if needed
  8805. if (lctx.model.hparams.rope_type != LLAMA_ROPE_TYPE_NONE && lctx.kv_self.has_shift) {
  8806. {
  8807. ggml_backend_sched_reset(lctx.sched);
  8808. ggml_cgraph * gf = llama_build_graph_k_shift(lctx);
  8809. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  8810. llama_set_k_shift(lctx);
  8811. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  8812. need_reserve = true;
  8813. }
  8814. {
  8815. auto & kv_self = lctx.kv_self;
  8816. kv_self.has_shift = false;
  8817. for (uint32_t i = 0; i < kv_self.size; ++i) {
  8818. kv_self.cells[i].delta = 0;
  8819. }
  8820. }
  8821. }
  8822. if (lctx.kv_self.recurrent && lctx.kv_self.do_copy) {
  8823. {
  8824. ggml_backend_sched_reset(lctx.sched);
  8825. ggml_cgraph * gf = llama_build_graph_s_copy(lctx);
  8826. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  8827. llama_set_s_copy(lctx);
  8828. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  8829. need_reserve = true;
  8830. }
  8831. {
  8832. auto & kv_self = lctx.kv_self;
  8833. kv_self.do_copy = false;
  8834. for (uint32_t i = 0; i < kv_self.size; ++i) {
  8835. kv_self.cells[i].src = i;
  8836. }
  8837. }
  8838. }
  8839. // defragment the KV cache if needed
  8840. if (lctx.kv_self.do_defrag) {
  8841. llama_kv_cache_defrag_internal(lctx);
  8842. need_reserve = true;
  8843. lctx.kv_self.do_defrag = false;
  8844. }
  8845. // reserve a worst case graph again
  8846. if (need_reserve) {
  8847. // TODO: extract to a function
  8848. // build worst-case graph
  8849. int n_tokens = (int)std::min(lctx.cparams.n_ctx, lctx.cparams.n_ubatch);
  8850. int n_past = lctx.cparams.n_ctx - n_tokens;
  8851. 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
  8852. ggml_cgraph * gf = llama_build_graph(lctx, llama_batch_get_one(&token, n_tokens, n_past, 0), true);
  8853. // initialize scheduler with the worst-case graph
  8854. ggml_backend_sched_reset(lctx.sched);
  8855. if (!ggml_backend_sched_reserve(lctx.sched, gf)) {
  8856. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  8857. }
  8858. }
  8859. }
  8860. //
  8861. // tokenizer
  8862. //
  8863. static enum llama_vocab_type llama_vocab_get_type(const llama_vocab & vocab) {
  8864. return vocab.type;
  8865. }
  8866. static bool llama_is_normal_token(const llama_vocab & vocab, llama_token id) {
  8867. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  8868. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL;
  8869. }
  8870. static bool llama_is_unknown_token(const llama_vocab & vocab, llama_token id) {
  8871. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  8872. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_UNKNOWN;
  8873. }
  8874. static bool llama_is_control_token(const llama_vocab & vocab, llama_token id) {
  8875. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  8876. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_CONTROL;
  8877. }
  8878. static bool llama_is_byte_token(const llama_vocab & vocab, llama_token id) {
  8879. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  8880. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_BYTE;
  8881. }
  8882. static bool llama_is_user_defined_token(const llama_vocab& vocab, llama_token id) {
  8883. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  8884. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_USER_DEFINED;
  8885. }
  8886. static uint8_t llama_token_to_byte(const llama_vocab& vocab, llama_token id) {
  8887. GGML_ASSERT(llama_vocab_get_type(vocab) != LLAMA_VOCAB_TYPE_NONE);
  8888. GGML_ASSERT(llama_is_byte_token(vocab, id));
  8889. const auto& token_data = vocab.id_to_token.at(id);
  8890. switch (llama_vocab_get_type(vocab)) {
  8891. case LLAMA_VOCAB_TYPE_SPM: {
  8892. auto buf = token_data.text.substr(3, 2);
  8893. return strtol(buf.c_str(), NULL, 16);
  8894. }
  8895. case LLAMA_VOCAB_TYPE_BPE: {
  8896. GGML_ASSERT(false);
  8897. return unicode_utf8_to_byte(token_data.text);
  8898. }
  8899. case LLAMA_VOCAB_TYPE_WPM: {
  8900. GGML_ASSERT(false);
  8901. }
  8902. default:
  8903. GGML_ASSERT(false);
  8904. }
  8905. }
  8906. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch) {
  8907. GGML_ASSERT(llama_vocab_get_type(vocab) != LLAMA_VOCAB_TYPE_NONE);
  8908. static const char * hex = "0123456789ABCDEF";
  8909. switch (llama_vocab_get_type(vocab)) {
  8910. case LLAMA_VOCAB_TYPE_SPM: {
  8911. const char buf[7] = { '<', '0', 'x', hex[ch >> 4], hex[ch & 15], '>', 0 };
  8912. auto token = vocab.token_to_id.find(buf);
  8913. if (token != vocab.token_to_id.end()) {
  8914. return (*token).second;
  8915. }
  8916. // Try to fall back to just the byte as a string
  8917. const char buf2[2] = { (char)ch, 0 };
  8918. return vocab.token_to_id.at(buf2);
  8919. }
  8920. case LLAMA_VOCAB_TYPE_WPM:
  8921. case LLAMA_VOCAB_TYPE_BPE: {
  8922. return vocab.token_to_id.at(unicode_byte_to_utf8(ch));
  8923. }
  8924. default:
  8925. GGML_ASSERT(false);
  8926. }
  8927. }
  8928. static void llama_escape_whitespace(std::string & text) {
  8929. replace_all(text, " ", "\xe2\x96\x81");
  8930. }
  8931. static void llama_unescape_whitespace(std::string & word) {
  8932. replace_all(word, "\xe2\x96\x81", " ");
  8933. }
  8934. struct llm_symbol {
  8935. using index = int;
  8936. index prev;
  8937. index next;
  8938. const char * text;
  8939. size_t n;
  8940. };
  8941. static_assert(std::is_trivially_copyable<llm_symbol>::value, "llm_symbol is not trivially copyable");
  8942. // SPM tokenizer
  8943. // original implementation:
  8944. // https://github.com/ggerganov/llama.cpp/commit/074bea2eb1f1349a0118239c4152914aecaa1be4
  8945. struct llm_bigram_spm {
  8946. struct comparator {
  8947. bool operator()(llm_bigram_spm & l, llm_bigram_spm & r) {
  8948. return (l.score < r.score) || (l.score == r.score && l.left > r.left);
  8949. }
  8950. };
  8951. using queue_storage = std::vector<llm_bigram_spm>;
  8952. using queue = std::priority_queue<llm_bigram_spm, queue_storage, comparator>;
  8953. llm_symbol::index left;
  8954. llm_symbol::index right;
  8955. float score;
  8956. size_t size;
  8957. };
  8958. struct llm_tokenizer_spm {
  8959. llm_tokenizer_spm(const llama_vocab & vocab) : vocab(vocab) {}
  8960. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  8961. // split string into utf8 chars
  8962. int index = 0;
  8963. size_t offs = 0;
  8964. while (offs < text.size()) {
  8965. llm_symbol sym;
  8966. size_t len = utf8_len(text[offs]);
  8967. sym.text = text.c_str() + offs;
  8968. sym.n = std::min(len, text.size() - offs);
  8969. offs += sym.n;
  8970. sym.prev = index - 1;
  8971. sym.next = offs == text.size() ? -1 : index + 1;
  8972. index++;
  8973. symbols.emplace_back(sym);
  8974. }
  8975. // seed the work queue with all possible 2-character tokens.
  8976. for (size_t i = 1; i < symbols.size(); ++i) {
  8977. try_add_bigram(i - 1, i);
  8978. }
  8979. // keep substituting the highest frequency pairs for as long as we can.
  8980. while (!work_queue.empty()) {
  8981. auto bigram = work_queue.top();
  8982. work_queue.pop();
  8983. auto & left_sym = symbols[bigram.left];
  8984. auto & right_sym = symbols[bigram.right];
  8985. // if one of the symbols already got merged, skip it.
  8986. if (left_sym.n == 0 || right_sym.n == 0 ||
  8987. left_sym.n + right_sym.n != bigram.size) {
  8988. continue;
  8989. }
  8990. // merge the right sym into the left one
  8991. left_sym.n += right_sym.n;
  8992. right_sym.n = 0;
  8993. //LLAMA_LOG_INFO("left = '%*s' size = %zu\n", (int) left_sym.n, left_sym.text, bigram.size);
  8994. // remove the right sym from the chain
  8995. left_sym.next = right_sym.next;
  8996. if (right_sym.next >= 0) {
  8997. symbols[right_sym.next].prev = bigram.left;
  8998. }
  8999. // find more substitutions
  9000. try_add_bigram(left_sym.prev, bigram.left);
  9001. try_add_bigram(bigram.left, left_sym.next);
  9002. }
  9003. for (int i = 0; i != -1; i = symbols[i].next) {
  9004. auto & symbol = symbols[i];
  9005. resegment(symbol, output);
  9006. }
  9007. }
  9008. private:
  9009. void resegment(llm_symbol & symbol, std::vector<llama_vocab::id> & output) {
  9010. auto text = std::string(symbol.text, symbol.n);
  9011. auto token = vocab.token_to_id.find(text);
  9012. // Do we need to support is_unused?
  9013. if (token != vocab.token_to_id.end()) {
  9014. output.push_back((*token).second);
  9015. return;
  9016. }
  9017. const auto p = rev_merge.find(text);
  9018. if (p == rev_merge.end()) {
  9019. // output any symbols that did not form tokens as bytes.
  9020. output.reserve(output.size() + symbol.n);
  9021. for (int j = 0; j < (int)symbol.n; ++j) {
  9022. llama_vocab::id token_id = llama_byte_to_token(vocab, symbol.text[j]);
  9023. output.push_back(token_id);
  9024. }
  9025. return;
  9026. }
  9027. resegment(symbols[p->second.first], output);
  9028. resegment(symbols[p->second.second], output);
  9029. }
  9030. void try_add_bigram(int left, int right) {
  9031. if (left == -1 || right == -1) {
  9032. return;
  9033. }
  9034. const std::string text = std::string(symbols[left].text, symbols[left].n + symbols[right].n);
  9035. auto token = vocab.token_to_id.find(text);
  9036. if (token == vocab.token_to_id.end()) {
  9037. return;
  9038. }
  9039. if (static_cast<size_t>((*token).second) >= vocab.id_to_token.size()) {
  9040. return;
  9041. }
  9042. const auto & tok_data = vocab.id_to_token[(*token).second];
  9043. llm_bigram_spm bigram;
  9044. bigram.left = left;
  9045. bigram.right = right;
  9046. bigram.score = tok_data.score;
  9047. bigram.size = text.size();
  9048. work_queue.push(bigram);
  9049. // Do we need to support is_unused?
  9050. rev_merge[text] = std::make_pair(left, right);
  9051. }
  9052. const llama_vocab & vocab;
  9053. std::vector<llm_symbol> symbols;
  9054. llm_bigram_spm::queue work_queue;
  9055. std::map<std::string, std::pair<int, int>> rev_merge;
  9056. };
  9057. // BPE tokenizer
  9058. // adapted from https://github.com/cmp-nct/ggllm.cpp [MIT License]
  9059. // tried to simplify unicode stuff, so most likely does not work 100% correctly!
  9060. // TODO: there are a lot of common parts between spm and bpe tokenizers, should be refactored and reused
  9061. struct llm_bigram_bpe {
  9062. struct comparator {
  9063. bool operator()(const llm_bigram_bpe & l, const llm_bigram_bpe & r) const {
  9064. return l.rank > r.rank || (l.rank == r.rank && l.left > r.left);
  9065. }
  9066. };
  9067. using queue_storage = std::vector<llm_bigram_bpe>;
  9068. using queue = std::priority_queue<llm_bigram_bpe, queue_storage, comparator>;
  9069. llm_symbol::index left;
  9070. llm_symbol::index right;
  9071. std::string text;
  9072. int rank;
  9073. size_t size;
  9074. };
  9075. struct llm_tokenizer_bpe {
  9076. llm_tokenizer_bpe(const llama_vocab & vocab): vocab(vocab) {}
  9077. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  9078. int final_prev_index = -1;
  9079. auto word_collection = bpe_gpt2_preprocess(text);
  9080. symbols_final.clear();
  9081. for (auto & word : word_collection) {
  9082. work_queue = llm_bigram_bpe::queue();
  9083. symbols.clear();
  9084. int index = 0;
  9085. size_t offset = 0;
  9086. while (offset < word.size()) {
  9087. llm_symbol sym;
  9088. size_t char_len = std::min(word.size() - offset, (size_t) ::utf8_len(word[offset]));
  9089. sym.text = word.c_str() + offset;
  9090. sym.n = char_len;
  9091. offset += sym.n;
  9092. sym.prev = index - 1;
  9093. sym.next = offset == word.size() ? -1 : index + 1;
  9094. index++;
  9095. symbols.emplace_back(sym);
  9096. }
  9097. for (size_t i = 1; i < symbols.size(); ++i) {
  9098. add_new_bigram(i - 1, i);
  9099. }
  9100. // build token(s)
  9101. while (!work_queue.empty()) {
  9102. auto bigram = work_queue.top();
  9103. work_queue.pop();
  9104. auto & left_symbol = symbols[bigram.left];
  9105. auto & right_symbol = symbols[bigram.right];
  9106. if (left_symbol.n == 0 || right_symbol.n == 0) {
  9107. continue;
  9108. }
  9109. std::string left_token = std::string(left_symbol.text, left_symbol.n);
  9110. std::string right_token = std::string(right_symbol.text, right_symbol.n);
  9111. if (left_token + right_token != bigram.text) {
  9112. continue; // Skip this bigram if it's outdated
  9113. }
  9114. // merge the right sym into the left one
  9115. left_symbol.n += right_symbol.n;
  9116. right_symbol.n = 0;
  9117. // remove the right sym from the chain
  9118. left_symbol.next = right_symbol.next;
  9119. if (right_symbol.next >= 0) {
  9120. symbols[right_symbol.next].prev = bigram.left;
  9121. }
  9122. add_new_bigram(left_symbol.prev, bigram.left); // left side of current symbol
  9123. add_new_bigram(bigram.left, left_symbol.next); // right side of current symbol
  9124. }
  9125. // add the fnished tokens to the final list keeping correct order for next and prev
  9126. for (auto & sym : symbols) {
  9127. if (sym.n > 0) {
  9128. sym.prev = final_prev_index;
  9129. sym.next = -1;
  9130. if (final_prev_index != -1) {
  9131. symbols_final[final_prev_index].next = symbols_final.size();
  9132. }
  9133. symbols_final.emplace_back(sym);
  9134. final_prev_index = symbols_final.size() - 1;
  9135. }
  9136. }
  9137. }
  9138. symbols = symbols_final;
  9139. if (!symbols.empty()) {
  9140. for (int i = 0; i != -1; i = symbols[i].next) {
  9141. auto & symbol = symbols[i];
  9142. if (symbol.n == 0) {
  9143. continue;
  9144. }
  9145. const std::string str = std::string(symbol.text, symbol.n);
  9146. const auto token = vocab.token_to_id.find(str);
  9147. if (token == vocab.token_to_id.end()) {
  9148. for (auto j = str.begin(); j != str.end(); ++j) {
  9149. std::string byte_str(1, *j);
  9150. auto token_multibyte = vocab.token_to_id.find(byte_str);
  9151. if (token_multibyte == vocab.token_to_id.end()) {
  9152. throw std::runtime_error("ERROR: byte not found in vocab");
  9153. }
  9154. output.push_back((*token_multibyte).second);
  9155. }
  9156. } else {
  9157. output.push_back((*token).second);
  9158. }
  9159. }
  9160. }
  9161. }
  9162. private:
  9163. void add_new_bigram(int left, int right) {
  9164. if (left == -1 || right == -1) {
  9165. return;
  9166. }
  9167. std::string left_token = std::string(symbols[left].text, symbols[left].n);
  9168. std::string right_token = std::string(symbols[right].text, symbols[right].n);
  9169. int rank_found = -1;
  9170. rank_found = vocab.find_bpe_rank(left_token, right_token);
  9171. if (rank_found < 0) {
  9172. return;
  9173. }
  9174. llm_bigram_bpe bigram;
  9175. bigram.left = left;
  9176. bigram.right = right;
  9177. bigram.text = left_token + right_token;
  9178. bigram.size = left_token.size() + right_token.size();
  9179. bigram.rank = rank_found;
  9180. work_queue.push(bigram);
  9181. }
  9182. std::vector<std::string> bpe_gpt2_preprocess(const std::string & text) {
  9183. std::vector<std::string> bpe_words;
  9184. std::vector<std::string> bpe_encoded_words;
  9185. std::string token = "";
  9186. // GPT2 system regex: 's|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+
  9187. bool collecting_numeric = false;
  9188. bool collecting_letter = false;
  9189. bool collecting_special = false;
  9190. bool collecting_whitespace_lookahead = false;
  9191. bool collecting = false;
  9192. std::vector<std::string> text_utf;
  9193. text_utf.reserve(text.size());
  9194. bpe_words.reserve(text.size());
  9195. bpe_encoded_words.reserve(text.size());
  9196. const auto cpts = unicode_cpts_from_utf8(text);
  9197. for (size_t i = 0; i < cpts.size(); ++i)
  9198. text_utf.emplace_back(unicode_cpt_to_utf8(cpts[i]));
  9199. for (int i = 0; i < (int)text_utf.size(); i++) {
  9200. const std::string & utf_char = text_utf[i];
  9201. bool split_condition = false;
  9202. int bytes_remain = text_utf.size() - i;
  9203. // forward backward lookups
  9204. const std::string & utf_char_next = (i + 1 < (int)text_utf.size()) ? text_utf[i + 1] : "";
  9205. const std::string & utf_char_next_next = (i + 2 < (int)text_utf.size()) ? text_utf[i + 2] : "";
  9206. // handling contractions
  9207. if (!split_condition && bytes_remain >= 2) {
  9208. // 's|'t|'m|'d
  9209. if (utf_char == "\'" && (utf_char_next == "s" || utf_char_next == "t" || utf_char_next == "m" || utf_char_next == "d")) {
  9210. split_condition = true;
  9211. }
  9212. if (split_condition) {
  9213. if (token.size()) {
  9214. bpe_words.emplace_back(token); // push previous content as token
  9215. }
  9216. token = utf_char + utf_char_next;
  9217. bpe_words.emplace_back(token);
  9218. token = "";
  9219. i++;
  9220. continue;
  9221. }
  9222. }
  9223. if (!split_condition && bytes_remain >= 3) {
  9224. // 're|'ve|'ll
  9225. if (utf_char == "\'" && (
  9226. (utf_char_next == "r" && utf_char_next_next == "e") ||
  9227. (utf_char_next == "v" && utf_char_next_next == "e") ||
  9228. (utf_char_next == "l" && utf_char_next_next == "l"))
  9229. ) {
  9230. split_condition = true;
  9231. }
  9232. if (split_condition) {
  9233. // current token + next token can be defined
  9234. if (token.size()) {
  9235. bpe_words.emplace_back(token); // push previous content as token
  9236. }
  9237. token = utf_char + utf_char_next + utf_char_next_next;
  9238. bpe_words.emplace_back(token); // the contraction
  9239. token = "";
  9240. i += 2;
  9241. continue;
  9242. }
  9243. }
  9244. if (!split_condition && !collecting) {
  9245. if (unicode_cpt_type(utf_char) == CODEPOINT_TYPE_LETTER || (!token.size() && utf_char == " " && unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_LETTER)) {
  9246. collecting_letter = true;
  9247. collecting = true;
  9248. }
  9249. else if (unicode_cpt_type(utf_char) == CODEPOINT_TYPE_DIGIT || (!token.size() && utf_char == " " && unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  9250. collecting_numeric = true;
  9251. collecting = true;
  9252. }
  9253. else if (
  9254. ((unicode_cpt_type(utf_char) != CODEPOINT_TYPE_LETTER && unicode_cpt_type(utf_char) != CODEPOINT_TYPE_DIGIT) && (unicode_cpt_type(utf_char) != CODEPOINT_TYPE_WHITESPACE)) ||
  9255. (!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)
  9256. ) {
  9257. collecting_special = true;
  9258. collecting = true;
  9259. }
  9260. else if (unicode_cpt_type(utf_char) == CODEPOINT_TYPE_WHITESPACE && unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_WHITESPACE) {
  9261. collecting_whitespace_lookahead = true;
  9262. collecting = true;
  9263. }
  9264. else if (unicode_cpt_type(utf_char) == CODEPOINT_TYPE_WHITESPACE) {
  9265. split_condition = true;
  9266. }
  9267. }
  9268. else if (!split_condition && collecting) {
  9269. if (collecting_letter && unicode_cpt_type(utf_char) != CODEPOINT_TYPE_LETTER) {
  9270. split_condition = true;
  9271. }
  9272. else if (collecting_numeric && unicode_cpt_type(utf_char) != CODEPOINT_TYPE_DIGIT) {
  9273. split_condition = true;
  9274. }
  9275. 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)) {
  9276. split_condition = true;
  9277. }
  9278. else if (collecting_whitespace_lookahead && (unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_LETTER || unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  9279. split_condition = true;
  9280. }
  9281. }
  9282. if (utf_char_next == "") {
  9283. split_condition = true; // final
  9284. token += utf_char;
  9285. }
  9286. if (split_condition) {
  9287. if (token.size()) {
  9288. bpe_words.emplace_back(token);
  9289. }
  9290. token = utf_char;
  9291. collecting = false;
  9292. collecting_letter = false;
  9293. collecting_numeric = false;
  9294. collecting_special = false;
  9295. collecting_whitespace_lookahead = false;
  9296. }
  9297. else {
  9298. token += utf_char;
  9299. }
  9300. }
  9301. for (std::string & word : bpe_words) {
  9302. std::string encoded_token = "";
  9303. for (char & c : word) {
  9304. encoded_token += unicode_byte_to_utf8(c);
  9305. }
  9306. bpe_encoded_words.emplace_back(encoded_token);
  9307. }
  9308. return bpe_encoded_words;
  9309. }
  9310. const llama_vocab & vocab;
  9311. std::vector<llm_symbol> symbols;
  9312. std::vector<llm_symbol> symbols_final;
  9313. llm_bigram_bpe::queue work_queue;
  9314. };
  9315. struct llm_tokenizer_wpm {
  9316. llm_tokenizer_wpm(const llama_vocab & vocab): vocab(vocab) {}
  9317. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  9318. auto * token_map = &vocab.token_to_id;
  9319. // normalize and split by whitespace
  9320. std::vector<std::string> words = preprocess(text);
  9321. // bos token prepended already
  9322. // find the longest tokens that form the words
  9323. for (const std::string &word : words) {
  9324. // skip empty words
  9325. if (word.size() == 0) {
  9326. continue;
  9327. }
  9328. // prepend phantom space
  9329. std::string word1 = "\xe2\x96\x81" + word;
  9330. int n = word1.size();
  9331. // we're at the start of a new word
  9332. int i = 0;
  9333. bool match_any = false;
  9334. // move through character position in word
  9335. while (i < n) {
  9336. // loop through possible match length
  9337. bool match = false;
  9338. for (int j = n; j > i; j--) {
  9339. auto it = token_map->find(word1.substr(i, j - i));
  9340. if (it != token_map->end()) {
  9341. output.push_back(it->second);
  9342. match = true;
  9343. match_any = true;
  9344. i = j;
  9345. break;
  9346. }
  9347. }
  9348. // must be an unknown character
  9349. if (!match) {
  9350. i++;
  9351. }
  9352. }
  9353. // we didn't find any matches for this word
  9354. if (!match_any) {
  9355. output.push_back(vocab.special_unk_id);
  9356. }
  9357. }
  9358. // append eos token
  9359. output.push_back(vocab.special_eos_id);
  9360. }
  9361. std::vector<std::string> preprocess(const std::string & text) {
  9362. std::vector<uint32_t> cpts_nfd = unicode_cpts_normalize_nfd(unicode_cpts_from_utf8(text));
  9363. // strip accents, strip control, uniformize whitespace,
  9364. // to lowercase, pad chinese characters, pad punctuation
  9365. std::string new_str = "";
  9366. for (uint32_t code : cpts_nfd) {
  9367. int type = unicode_cpt_type(code);
  9368. if (type == CODEPOINT_TYPE_ACCENT_MARK || type == CODEPOINT_TYPE_CONTROL) {
  9369. continue;
  9370. }
  9371. code = unicode_tolower(code);
  9372. if (type == CODEPOINT_TYPE_WHITESPACE) {
  9373. code = ' ';
  9374. }
  9375. std::string s = unicode_cpt_to_utf8(code);
  9376. if (type == CODEPOINT_TYPE_PUNCTUATION || is_ascii_punct(code) || is_chinese_char(code)) {
  9377. new_str += " ";
  9378. new_str += s;
  9379. new_str += " ";
  9380. } else {
  9381. new_str += s;
  9382. }
  9383. }
  9384. // split by whitespace
  9385. uint64_t l = 0;
  9386. uint64_t r = 0;
  9387. std::vector<std::string> words;
  9388. while (r < new_str.size()) {
  9389. // if is whitespace
  9390. if (isspace(new_str[r], std::locale::classic())) {
  9391. if (r > l) words.push_back(new_str.substr(l, (r - l)));
  9392. l = r + 1;
  9393. r = l;
  9394. } else {
  9395. r += 1;
  9396. }
  9397. }
  9398. if (r > l) {
  9399. words.push_back(new_str.substr(l, (r - l)));
  9400. }
  9401. return words;
  9402. }
  9403. bool is_ascii_punct(uint32_t code) {
  9404. if (code > 0xFF) {
  9405. return false;
  9406. }
  9407. auto c = char(static_cast<unsigned char>(code));
  9408. return ispunct(c, std::locale::classic());
  9409. }
  9410. bool is_chinese_char(uint32_t cpt) {
  9411. if ((cpt >= 0x4E00 && cpt <= 0x9FFF) ||
  9412. (cpt >= 0x3400 && cpt <= 0x4DBF) ||
  9413. (cpt >= 0x20000 && cpt <= 0x2A6DF) ||
  9414. (cpt >= 0x2A700 && cpt <= 0x2B73F) ||
  9415. (cpt >= 0x2B740 && cpt <= 0x2B81F) ||
  9416. (cpt >= 0x2B920 && cpt <= 0x2CEAF) || // this should be 0x2B820 but in hf rust code it is 0x2B920
  9417. (cpt >= 0xF900 && cpt <= 0xFAFF) ||
  9418. (cpt >= 0x2F800 && cpt <= 0x2FA1F) ||
  9419. (cpt >= 0x3000 && cpt <= 0x303F) ||
  9420. (cpt >= 0xFF00 && cpt <= 0xFFEF)) {
  9421. return true; // NOLINT
  9422. }
  9423. return false;
  9424. }
  9425. const llama_vocab & vocab;
  9426. };
  9427. typedef enum FRAGMENT_BUFFER_VARIANT_TYPE {
  9428. FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN,
  9429. FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT
  9430. } FRAGMENT_BUFFER_VARIANT_TYPE;
  9431. struct fragment_buffer_variant {
  9432. fragment_buffer_variant(llama_vocab::id _token)
  9433. :
  9434. type(FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN),
  9435. token(_token),
  9436. raw_text(_dummy),
  9437. offset(0),
  9438. length(0) {}
  9439. fragment_buffer_variant(const std::string & _raw_text, int64_t _offset, int64_t _length)
  9440. :
  9441. type(FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT),
  9442. token((llama_vocab::id) - 1),
  9443. raw_text(_raw_text),
  9444. offset(_offset),
  9445. length(_length){
  9446. GGML_ASSERT(_offset >= 0);
  9447. GGML_ASSERT(_length >= 1);
  9448. GGML_ASSERT(offset + length <= raw_text.length());
  9449. }
  9450. const FRAGMENT_BUFFER_VARIANT_TYPE type;
  9451. const llama_vocab::id token;
  9452. const std::string _dummy;
  9453. const std::string & raw_text;
  9454. const uint64_t offset;
  9455. const uint64_t length;
  9456. };
  9457. // #define PRETOKENIZERDEBUG
  9458. static void tokenizer_st_partition(const llama_vocab & vocab, std::forward_list<fragment_buffer_variant> & buffer) {
  9459. // for each special token
  9460. for (const auto & st: vocab.special_tokens_cache) {
  9461. const auto & special_token = st.first;
  9462. const auto & special_id = st.second;
  9463. // for each text fragment
  9464. std::forward_list<fragment_buffer_variant>::iterator it = buffer.begin();
  9465. while (it != buffer.end()) {
  9466. auto & fragment = (*it);
  9467. // if a fragment is text ( not yet processed )
  9468. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  9469. auto * raw_text = &(fragment.raw_text);
  9470. auto raw_text_base_offset = fragment.offset;
  9471. auto raw_text_base_length = fragment.length;
  9472. // loop over the text
  9473. while (true) {
  9474. // find the first occurrence of a given special token in this fragment
  9475. // passing offset argument only limit the "search area" but match coordinates
  9476. // are still relative to the source full raw_text
  9477. auto match = raw_text->find(special_token, raw_text_base_offset);
  9478. // no occurrences found, stop processing this fragment for a given special token
  9479. if (match == std::string::npos) break;
  9480. // check if match is within bounds of offset <-> length
  9481. if (match + special_token.length() > raw_text_base_offset + raw_text_base_length) break;
  9482. #ifdef PRETOKENIZERDEBUG
  9483. 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());
  9484. #endif
  9485. auto source = std::distance(buffer.begin(), it);
  9486. // if match is further than base offset
  9487. // then we have some text to the left of it
  9488. if (match > raw_text_base_offset) {
  9489. // left
  9490. const int64_t left_reminder_offset = raw_text_base_offset + 0;
  9491. const int64_t left_reminder_length = match - raw_text_base_offset;
  9492. buffer.emplace_after(it, (*raw_text), left_reminder_offset, left_reminder_length);
  9493. #ifdef PRETOKENIZERDEBUG
  9494. 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());
  9495. #endif
  9496. it++;
  9497. }
  9498. // special token
  9499. buffer.emplace_after(it, special_id);
  9500. it++;
  9501. // right
  9502. if (match + special_token.length() < raw_text_base_offset + raw_text_base_length) {
  9503. const int64_t right_reminder_offset = match + special_token.length();
  9504. const int64_t right_reminder_length = raw_text_base_length - ((match - raw_text_base_offset) + special_token.length());
  9505. buffer.emplace_after(it, (*raw_text), right_reminder_offset, right_reminder_length);
  9506. #ifdef PRETOKENIZERDEBUG
  9507. 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());
  9508. #endif
  9509. it++;
  9510. if (source == 0) {
  9511. buffer.erase_after(buffer.before_begin());
  9512. } else {
  9513. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  9514. }
  9515. // repeat for the right side
  9516. raw_text_base_offset = right_reminder_offset;
  9517. raw_text_base_length = right_reminder_length;
  9518. #ifdef PRETOKENIZERDEBUG
  9519. 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());
  9520. #endif
  9521. } else {
  9522. if (source == 0) {
  9523. buffer.erase_after(buffer.before_begin());
  9524. } else {
  9525. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  9526. }
  9527. break;
  9528. }
  9529. }
  9530. }
  9531. it++;
  9532. }
  9533. }
  9534. }
  9535. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special) {
  9536. std::vector<llama_vocab::id> output;
  9537. // OG tokenizer behavior:
  9538. //
  9539. // tokenizer.encode('', add_bos=True) returns [1]
  9540. // tokenizer.encode('', add_bos=False) returns []
  9541. if (bos && vocab.special_bos_id != -1) {
  9542. output.push_back(vocab.special_bos_id);
  9543. }
  9544. if (raw_text.empty()) {
  9545. return output;
  9546. }
  9547. std::forward_list<fragment_buffer_variant> fragment_buffer;
  9548. fragment_buffer.emplace_front(raw_text, 0, raw_text.length());
  9549. if (special) tokenizer_st_partition(vocab, fragment_buffer);
  9550. switch (vocab.type) {
  9551. case LLAMA_VOCAB_TYPE_SPM:
  9552. {
  9553. for (const auto & fragment : fragment_buffer) {
  9554. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  9555. // without adding this leading whitespace, we do not get the same results as the original tokenizer
  9556. // TODO: It's likely possible to get rid of this string copy entirely
  9557. // by modifying llm_tokenizer_x to operate with string offsets like pre-tokenizer
  9558. // and passing 'add space prefix' as bool argument
  9559. //
  9560. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  9561. if (&fragment == &fragment_buffer.front()) {
  9562. if (vocab.add_space_prefix) {
  9563. raw_text = " " + raw_text; // prefix with space if the first token is not special
  9564. }
  9565. }
  9566. #ifdef PRETOKENIZERDEBUG
  9567. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  9568. #endif
  9569. llm_tokenizer_spm tokenizer(vocab);
  9570. llama_escape_whitespace(raw_text);
  9571. tokenizer.tokenize(raw_text, output);
  9572. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  9573. output.push_back(fragment.token);
  9574. }
  9575. }
  9576. } break;
  9577. case LLAMA_VOCAB_TYPE_BPE:
  9578. {
  9579. for (const auto & fragment : fragment_buffer) {
  9580. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  9581. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  9582. #ifdef PRETOKENIZERDEBUG
  9583. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  9584. #endif
  9585. llm_tokenizer_bpe tokenizer(vocab);
  9586. tokenizer.tokenize(raw_text, output);
  9587. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  9588. output.push_back(fragment.token);
  9589. }
  9590. }
  9591. } break;
  9592. case LLAMA_VOCAB_TYPE_WPM:
  9593. {
  9594. for (const auto & fragment : fragment_buffer) {
  9595. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  9596. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  9597. #ifdef PRETOKENIZERDEBUG
  9598. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  9599. #endif
  9600. llm_tokenizer_wpm tokenizer(vocab);
  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. } break;
  9607. case LLAMA_VOCAB_TYPE_NONE:
  9608. GGML_ASSERT(false);
  9609. }
  9610. return output;
  9611. }
  9612. //
  9613. // grammar - internal
  9614. //
  9615. // Decodes a UTF-8 string which may end in an incomplete sequence. Adds a terminating 0 for use as
  9616. // pointer. If an invalid sequence is encountered, returns `llama_partial_utf8.n_remain == -1`.
  9617. std::pair<std::vector<uint32_t>, llama_partial_utf8> decode_utf8(
  9618. const std::string & src,
  9619. llama_partial_utf8 partial_start) {
  9620. static const int lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 3, 4 };
  9621. const char * pos = src.c_str();
  9622. std::vector<uint32_t> code_points;
  9623. // common english strings have the same number of codepoints and bytes. `+ 1` for the terminating 0.
  9624. code_points.reserve(src.size() + 1);
  9625. uint32_t value = partial_start.value;
  9626. int n_remain = partial_start.n_remain;
  9627. // continue previous decode, if applicable
  9628. while (*pos != 0 && n_remain > 0) {
  9629. uint8_t next_byte = static_cast<uint8_t>(*pos);
  9630. if ((next_byte >> 6) != 2) {
  9631. // invalid sequence, abort
  9632. code_points.push_back(0);
  9633. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, -1 });
  9634. }
  9635. value = (value << 6) + (next_byte & 0x3F);
  9636. ++pos;
  9637. --n_remain;
  9638. }
  9639. if (partial_start.n_remain > 0 && n_remain == 0) {
  9640. code_points.push_back(value);
  9641. }
  9642. // decode any subsequent utf-8 sequences, which may end in an incomplete one
  9643. while (*pos != 0) {
  9644. uint8_t first_byte = static_cast<uint8_t>(*pos);
  9645. uint8_t highbits = first_byte >> 4;
  9646. n_remain = lookup[highbits] - 1;
  9647. if (n_remain < 0) {
  9648. // invalid sequence, abort
  9649. code_points.clear();
  9650. code_points.push_back(0);
  9651. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, n_remain });
  9652. }
  9653. uint8_t mask = (1 << (7 - n_remain)) - 1;
  9654. value = first_byte & mask;
  9655. ++pos;
  9656. while (*pos != 0 && n_remain > 0) {
  9657. value = (value << 6) + (static_cast<uint8_t>(*pos) & 0x3F);
  9658. ++pos;
  9659. --n_remain;
  9660. }
  9661. if (n_remain == 0) {
  9662. code_points.push_back(value);
  9663. }
  9664. }
  9665. code_points.push_back(0);
  9666. return std::make_pair(std::move(code_points), llama_partial_utf8{ value, n_remain });
  9667. }
  9668. // returns true iff pos points to the end of one of the definitions of a rule
  9669. static bool llama_grammar_is_end_of_sequence(const llama_grammar_element * pos) {
  9670. switch (pos->type) {
  9671. case LLAMA_GRETYPE_END: return true; // NOLINT
  9672. case LLAMA_GRETYPE_ALT: return true; // NOLINT
  9673. default: return false;
  9674. }
  9675. }
  9676. // returns true iff chr satisfies the char range at pos (regular or inverse range)
  9677. // asserts that pos is pointing to a char range element
  9678. static std::pair<bool, const llama_grammar_element *> llama_grammar_match_char(
  9679. const llama_grammar_element * pos,
  9680. const uint32_t chr) {
  9681. bool found = false;
  9682. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  9683. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT); // NOLINT
  9684. do {
  9685. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  9686. // inclusive range, e.g. [a-z]
  9687. found = found || (pos->value <= chr && chr <= pos[1].value);
  9688. pos += 2;
  9689. } else {
  9690. // exact char match, e.g. [a] or "a"
  9691. found = found || pos->value == chr;
  9692. pos += 1;
  9693. }
  9694. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  9695. return std::make_pair(found == is_positive_char, pos);
  9696. }
  9697. // returns true iff some continuation of the given partial UTF-8 sequence could satisfy the char
  9698. // range at pos (regular or inverse range)
  9699. // asserts that pos is pointing to a char range element
  9700. static bool llama_grammar_match_partial_char(
  9701. const llama_grammar_element * pos,
  9702. const llama_partial_utf8 partial_utf8) {
  9703. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  9704. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT);
  9705. uint32_t partial_value = partial_utf8.value;
  9706. int n_remain = partial_utf8.n_remain;
  9707. // invalid sequence or 7-bit char split across 2 bytes (overlong)
  9708. if (n_remain < 0 || (n_remain == 1 && partial_value < 2)) {
  9709. return false;
  9710. }
  9711. // range of possible code points this partial UTF-8 sequence could complete to
  9712. uint32_t low = partial_value << (n_remain * 6);
  9713. uint32_t high = low | ((1 << (n_remain * 6)) - 1);
  9714. if (low == 0) {
  9715. if (n_remain == 2) {
  9716. low = 1 << 11;
  9717. } else if (n_remain == 3) {
  9718. low = 1 << 16;
  9719. }
  9720. }
  9721. do {
  9722. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  9723. // inclusive range, e.g. [a-z]
  9724. if (pos->value <= high && low <= pos[1].value) {
  9725. return is_positive_char;
  9726. }
  9727. pos += 2;
  9728. } else {
  9729. // exact char match, e.g. [a] or "a"
  9730. if (low <= pos->value && pos->value <= high) {
  9731. return is_positive_char;
  9732. }
  9733. pos += 1;
  9734. }
  9735. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  9736. return !is_positive_char;
  9737. }
  9738. // transforms a grammar pushdown stack into N possible stacks, all ending
  9739. // at a character range (terminal element)
  9740. static void llama_grammar_advance_stack(
  9741. const std::vector<std::vector<llama_grammar_element>> & rules,
  9742. const std::vector<const llama_grammar_element *> & stack,
  9743. std::vector<std::vector<const llama_grammar_element *>> & new_stacks) {
  9744. if (stack.empty()) {
  9745. new_stacks.emplace_back(stack);
  9746. return;
  9747. }
  9748. const llama_grammar_element * pos = stack.back();
  9749. switch (pos->type) {
  9750. case LLAMA_GRETYPE_RULE_REF: {
  9751. const size_t rule_id = static_cast<size_t>(pos->value);
  9752. const llama_grammar_element * subpos = rules[rule_id].data();
  9753. do {
  9754. // init new stack without the top (pos)
  9755. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  9756. if (!llama_grammar_is_end_of_sequence(pos + 1)) {
  9757. // if this rule ref is followed by another element, add that to stack
  9758. new_stack.push_back(pos + 1);
  9759. }
  9760. if (!llama_grammar_is_end_of_sequence(subpos)) {
  9761. // if alternate is nonempty, add to stack
  9762. new_stack.push_back(subpos);
  9763. }
  9764. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  9765. while (!llama_grammar_is_end_of_sequence(subpos)) {
  9766. // scan to end of alternate def
  9767. subpos++;
  9768. }
  9769. if (subpos->type == LLAMA_GRETYPE_ALT) {
  9770. // there's another alternate def of this rule to process
  9771. subpos++;
  9772. } else {
  9773. break;
  9774. }
  9775. } while (true);
  9776. break;
  9777. }
  9778. case LLAMA_GRETYPE_CHAR:
  9779. case LLAMA_GRETYPE_CHAR_NOT:
  9780. new_stacks.emplace_back(stack);
  9781. break;
  9782. default:
  9783. // end of alternate (LLAMA_GRETYPE_END, LLAMA_GRETYPE_ALT) or middle of char range
  9784. // (LLAMA_GRETYPE_CHAR_ALT, LLAMA_GRETYPE_CHAR_RNG_UPPER); stack should never be left on
  9785. // those
  9786. GGML_ASSERT(false);
  9787. }
  9788. }
  9789. // takes a set of possible pushdown stacks on a grammar, which are required to
  9790. // be positioned at a character range (see `llama_grammar_advance_stack`), and
  9791. // produces the N possible stacks if the given char is accepted at those
  9792. // positions
  9793. std::vector<std::vector<const llama_grammar_element *>> llama_grammar_accept(
  9794. const std::vector<std::vector<llama_grammar_element>> & rules,
  9795. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  9796. const uint32_t chr) {
  9797. std::vector<std::vector<const llama_grammar_element *>> new_stacks;
  9798. for (const auto & stack : stacks) {
  9799. if (stack.empty()) {
  9800. continue;
  9801. }
  9802. auto match = llama_grammar_match_char(stack.back(), chr);
  9803. if (match.first) {
  9804. const llama_grammar_element * pos = match.second;
  9805. // update top of stack to next element, if any
  9806. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  9807. if (!llama_grammar_is_end_of_sequence(pos)) {
  9808. new_stack.push_back(pos);
  9809. }
  9810. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  9811. }
  9812. }
  9813. return new_stacks;
  9814. }
  9815. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  9816. const std::vector<std::vector<llama_grammar_element>> & rules,
  9817. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  9818. const std::vector<llama_grammar_candidate> & candidates);
  9819. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates_for_stack(
  9820. const std::vector<std::vector<llama_grammar_element>> & rules,
  9821. const std::vector<const llama_grammar_element *> & stack,
  9822. const std::vector<llama_grammar_candidate> & candidates) {
  9823. std::vector<llama_grammar_candidate> rejects;
  9824. if (stack.empty()) {
  9825. for (const auto & tok : candidates) {
  9826. if (*tok.code_points != 0 || tok.partial_utf8.n_remain != 0) {
  9827. rejects.push_back(tok);
  9828. }
  9829. }
  9830. return rejects;
  9831. }
  9832. const llama_grammar_element * stack_pos = stack.back();
  9833. std::vector<llama_grammar_candidate> next_candidates;
  9834. for (const auto & tok : candidates) {
  9835. if (*tok.code_points == 0) {
  9836. // reached end of full codepoints in token, reject iff it ended in a partial sequence
  9837. // that cannot satisfy this position in grammar
  9838. if (tok.partial_utf8.n_remain != 0 &&
  9839. !llama_grammar_match_partial_char(stack_pos, tok.partial_utf8)) {
  9840. rejects.push_back(tok);
  9841. }
  9842. } else if (llama_grammar_match_char(stack_pos, *tok.code_points).first) {
  9843. next_candidates.push_back({ tok.index, tok.code_points + 1, tok.partial_utf8 });
  9844. } else {
  9845. rejects.push_back(tok);
  9846. }
  9847. }
  9848. const auto * stack_pos_after = llama_grammar_match_char(stack_pos, 0).second;
  9849. // update top of stack to next element, if any
  9850. std::vector<const llama_grammar_element *> stack_after(stack.begin(), stack.end() - 1);
  9851. if (!llama_grammar_is_end_of_sequence(stack_pos_after)) {
  9852. stack_after.push_back(stack_pos_after);
  9853. }
  9854. std::vector<std::vector<const llama_grammar_element *>> next_stacks;
  9855. llama_grammar_advance_stack(rules, stack_after, next_stacks);
  9856. auto next_rejects = llama_grammar_reject_candidates(rules, next_stacks, next_candidates);
  9857. for (const auto & tok : next_rejects) {
  9858. rejects.push_back({ tok.index, tok.code_points - 1, tok.partial_utf8 });
  9859. }
  9860. return rejects;
  9861. }
  9862. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  9863. const std::vector<std::vector<llama_grammar_element>> & rules,
  9864. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  9865. const std::vector<llama_grammar_candidate> & candidates) {
  9866. GGML_ASSERT(!stacks.empty()); // REVIEW
  9867. if (candidates.empty()) {
  9868. return std::vector<llama_grammar_candidate>();
  9869. }
  9870. auto rejects = llama_grammar_reject_candidates_for_stack(rules, stacks.front(), candidates);
  9871. for (size_t i = 1, size = stacks.size(); i < size; ++i) {
  9872. rejects = llama_grammar_reject_candidates_for_stack(rules, stacks[i], rejects);
  9873. }
  9874. return rejects;
  9875. }
  9876. //
  9877. // grammar - external
  9878. //
  9879. struct llama_grammar * llama_grammar_init(
  9880. const llama_grammar_element ** rules,
  9881. size_t n_rules,
  9882. size_t start_rule_index) {
  9883. const llama_grammar_element * pos;
  9884. // copy rule definitions into vectors
  9885. std::vector<std::vector<llama_grammar_element>> vec_rules(n_rules);
  9886. for (size_t i = 0; i < n_rules; i++) {
  9887. for (pos = rules[i]; pos->type != LLAMA_GRETYPE_END; pos++) {
  9888. vec_rules[i].push_back(*pos);
  9889. }
  9890. vec_rules[i].push_back({LLAMA_GRETYPE_END, 0});
  9891. }
  9892. // loop over alternates of start rule to build initial stacks
  9893. std::vector<std::vector<const llama_grammar_element *>> stacks;
  9894. pos = vec_rules[start_rule_index].data();
  9895. do {
  9896. std::vector<const llama_grammar_element *> stack;
  9897. if (!llama_grammar_is_end_of_sequence(pos)) {
  9898. // if alternate is nonempty, add to stack
  9899. stack.push_back(pos);
  9900. }
  9901. llama_grammar_advance_stack(vec_rules, stack, stacks);
  9902. while (!llama_grammar_is_end_of_sequence(pos)) {
  9903. // scan to end of alternate def
  9904. pos++;
  9905. }
  9906. if (pos->type == LLAMA_GRETYPE_ALT) {
  9907. // there's another alternate def of this rule to process
  9908. pos++;
  9909. } else {
  9910. break;
  9911. }
  9912. } while (true);
  9913. return new llama_grammar{ std::move(vec_rules), std::move(stacks), {} };
  9914. }
  9915. void llama_grammar_free(struct llama_grammar * grammar) {
  9916. delete grammar;
  9917. }
  9918. struct llama_grammar * llama_grammar_copy(const struct llama_grammar * grammar) {
  9919. llama_grammar * result = new llama_grammar{ grammar->rules, grammar->stacks, grammar->partial_utf8 };
  9920. // redirect elements in stacks to point to new rules
  9921. for (size_t is = 0; is < result->stacks.size(); is++) {
  9922. for (size_t ie = 0; ie < result->stacks[is].size(); ie++) {
  9923. for (size_t ir0 = 0; ir0 < grammar->rules.size(); ir0++) {
  9924. for (size_t ir1 = 0; ir1 < grammar->rules[ir0].size(); ir1++) {
  9925. if (grammar->stacks[is][ie] == &grammar->rules[ir0][ir1]) {
  9926. result->stacks[is][ie] = &result->rules[ir0][ir1];
  9927. }
  9928. }
  9929. }
  9930. }
  9931. }
  9932. return result;
  9933. }
  9934. //
  9935. // sampling
  9936. //
  9937. void llama_set_rng_seed(struct llama_context * ctx, uint32_t seed) {
  9938. if (seed == LLAMA_DEFAULT_SEED) {
  9939. seed = time(NULL);
  9940. }
  9941. ctx->rng.seed(seed);
  9942. }
  9943. void llama_sample_softmax(struct llama_context * ctx, llama_token_data_array * candidates) {
  9944. GGML_ASSERT(candidates->size > 0);
  9945. const int64_t t_start_sample_us = ggml_time_us();
  9946. // Sort the logits in descending order
  9947. if (!candidates->sorted) {
  9948. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  9949. return a.logit > b.logit;
  9950. });
  9951. candidates->sorted = true;
  9952. }
  9953. float max_l = candidates->data[0].logit;
  9954. float cum_sum = 0.0f;
  9955. for (size_t i = 0; i < candidates->size; ++i) {
  9956. float p = expf(candidates->data[i].logit - max_l);
  9957. candidates->data[i].p = p;
  9958. cum_sum += p;
  9959. }
  9960. for (size_t i = 0; i < candidates->size; ++i) {
  9961. candidates->data[i].p /= cum_sum;
  9962. }
  9963. if (ctx) {
  9964. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9965. }
  9966. }
  9967. void llama_sample_top_k(struct llama_context * ctx, llama_token_data_array * candidates, int32_t k, size_t min_keep) {
  9968. // TODO: move bucket sort to separate function so that top_p/tail_free/typical/softmax first is equally fast
  9969. // if (k >= (int32_t)candidates->size) {
  9970. // return;
  9971. // }
  9972. const int64_t t_start_sample_us = ggml_time_us();
  9973. if (k <= 0) {
  9974. k = candidates->size;
  9975. }
  9976. k = std::max(k, (int) min_keep);
  9977. k = std::min(k, (int) candidates->size);
  9978. // Sort scores in descending order
  9979. if (!candidates->sorted) {
  9980. auto comp = [](const llama_token_data & a, const llama_token_data & b) {
  9981. return a.logit > b.logit;
  9982. };
  9983. if (k <= 128) {
  9984. std::partial_sort(candidates->data, candidates->data + k, candidates->data + candidates->size, comp);
  9985. } else {
  9986. constexpr int nbuckets = 128;
  9987. constexpr float bucket_low = -10.0f;
  9988. constexpr float bucket_high = 10.0f;
  9989. constexpr float bucket_scale = nbuckets/(bucket_high - bucket_low);
  9990. constexpr float bucker_inter = -bucket_low * bucket_scale;
  9991. std::vector<int> bucket_idx(candidates->size);
  9992. std::vector<int> histo(nbuckets, 0);
  9993. for (int i = 0; i < (int)candidates->size; ++i) {
  9994. const float val = candidates->data[i].logit;
  9995. int ib = int(bucket_scale * val + bucker_inter); //nbuckets * (val - bucket_low) / (bucket_high - bucket_low);
  9996. ib = std::max(0, std::min(nbuckets-1, ib));
  9997. bucket_idx[i] = ib;
  9998. ++histo[ib];
  9999. }
  10000. int nhave = 0;
  10001. int ib = nbuckets - 1;
  10002. for ( ; ib >= 0; --ib) {
  10003. nhave += histo[ib];
  10004. if (nhave >= k) break;
  10005. }
  10006. std::vector<llama_token_data> tmp_tokens(nhave);
  10007. auto ptr = tmp_tokens.data();
  10008. std::vector<llama_token_data*> bucket_ptrs;
  10009. bucket_ptrs.reserve(nbuckets - ib);
  10010. for (int j = nbuckets - 1; j >= ib; --j) {
  10011. bucket_ptrs.push_back(ptr);
  10012. ptr += histo[j];
  10013. }
  10014. for (int i = 0; i < (int)candidates->size; ++i) {
  10015. int j = bucket_idx[i];
  10016. if (j >= ib) {
  10017. *bucket_ptrs[nbuckets-1-j]++ = candidates->data[i];
  10018. }
  10019. }
  10020. ptr = tmp_tokens.data();
  10021. int ndone = 0;
  10022. for (int j = nbuckets-1; j > ib; --j) {
  10023. std::sort(ptr, ptr + histo[j], comp);
  10024. ptr += histo[j];
  10025. ndone += histo[j];
  10026. }
  10027. std::partial_sort(ptr, ptr + k - ndone, ptr + histo[ib], comp);
  10028. std::memcpy(candidates->data, tmp_tokens.data(), k*sizeof(llama_token_data));
  10029. }
  10030. candidates->sorted = true;
  10031. }
  10032. candidates->size = k;
  10033. if (ctx) {
  10034. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10035. }
  10036. }
  10037. void llama_sample_top_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  10038. if (p >= 1.0f) {
  10039. return;
  10040. }
  10041. llama_sample_softmax(ctx, candidates);
  10042. const int64_t t_start_sample_us = ggml_time_us();
  10043. // Compute the cumulative probabilities
  10044. float cum_sum = 0.0f;
  10045. size_t last_idx = candidates->size;
  10046. for (size_t i = 0; i < candidates->size; ++i) {
  10047. cum_sum += candidates->data[i].p;
  10048. // Check if the running sum is at least p or if we have kept at least min_keep tokens
  10049. // we set the last index to i+1 to indicate that the current iterate should be included in the set
  10050. if (cum_sum >= p && i + 1 >= min_keep) {
  10051. last_idx = i + 1;
  10052. break;
  10053. }
  10054. }
  10055. // Resize the output vector to keep only the top-p tokens
  10056. candidates->size = last_idx;
  10057. if (ctx) {
  10058. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10059. }
  10060. }
  10061. void llama_sample_min_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  10062. if (p <= 0.0f || !candidates->size) {
  10063. return;
  10064. }
  10065. const int64_t t_start_sample_us = ggml_time_us();
  10066. bool min_p_applied = false;
  10067. // if the candidates aren't sorted, try the unsorted implementation first
  10068. if (!candidates->sorted) {
  10069. std::vector<llama_token_data> filtered_tokens;
  10070. float max_logit = -FLT_MAX;
  10071. for (size_t i = 0; i < candidates->size; ++i) {
  10072. max_logit = std::max(max_logit, candidates->data[i].logit);
  10073. }
  10074. const float min_logit = max_logit + logf(p); // min logit for p_i >= p * p_max
  10075. for (size_t i = 0; i < candidates->size; ++i) {
  10076. if (candidates->data[i].logit >= min_logit) {
  10077. filtered_tokens.push_back(candidates->data[i]);
  10078. }
  10079. }
  10080. // if we have enough values the operation was a success
  10081. if (filtered_tokens.size() >= min_keep) {
  10082. memcpy(candidates->data, filtered_tokens.data(), filtered_tokens.size()*sizeof(llama_token_data));
  10083. candidates->size = filtered_tokens.size();
  10084. min_p_applied = true;
  10085. }
  10086. }
  10087. // if the candidates are sorted or the unsorted implementation failed, use this implementation
  10088. if (!min_p_applied) {
  10089. // Sort the logits in descending order
  10090. if (!candidates->sorted) {
  10091. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  10092. return a.logit > b.logit;
  10093. });
  10094. candidates->sorted = true;
  10095. }
  10096. const float min_logit = candidates->data[0].logit + logf(p); // min logit for p_i >= p * p_max
  10097. size_t i = 1; // first token always matches
  10098. for (; i < candidates->size; ++i) {
  10099. if (candidates->data[i].logit < min_logit && i >= min_keep) {
  10100. break; // prob too small
  10101. }
  10102. }
  10103. // Resize the output vector to keep only the matching tokens
  10104. candidates->size = i;
  10105. }
  10106. if (ctx) {
  10107. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10108. }
  10109. }
  10110. void llama_sample_tail_free(struct llama_context * ctx, llama_token_data_array * candidates, float z, size_t min_keep) {
  10111. if (z >= 1.0f || candidates->size <= 2) {
  10112. return;
  10113. }
  10114. llama_sample_softmax(nullptr, candidates);
  10115. const int64_t t_start_sample_us = ggml_time_us();
  10116. // Compute the first and second derivatives
  10117. std::vector<float> first_derivatives(candidates->size - 1);
  10118. std::vector<float> second_derivatives(candidates->size - 2);
  10119. for (size_t i = 0; i < first_derivatives.size(); ++i) {
  10120. first_derivatives[i] = candidates->data[i].p - candidates->data[i + 1].p;
  10121. }
  10122. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  10123. second_derivatives[i] = first_derivatives[i] - first_derivatives[i + 1];
  10124. }
  10125. // Calculate absolute value of second derivatives
  10126. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  10127. second_derivatives[i] = std::abs(second_derivatives[i]);
  10128. }
  10129. // Normalize the second derivatives
  10130. {
  10131. const float second_derivatives_sum = std::accumulate(second_derivatives.begin(), second_derivatives.end(), 0.0f);
  10132. if (second_derivatives_sum > 1e-6f) {
  10133. for (float & value : second_derivatives) {
  10134. value /= second_derivatives_sum;
  10135. }
  10136. } else {
  10137. for (float & value : second_derivatives) {
  10138. value = 1.0f / second_derivatives.size();
  10139. }
  10140. }
  10141. }
  10142. float cum_sum = 0.0f;
  10143. size_t last_idx = candidates->size;
  10144. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  10145. cum_sum += second_derivatives[i];
  10146. // Check if the running sum is greater than z or if we have kept at least min_keep tokens
  10147. if (cum_sum > z && i >= min_keep) {
  10148. last_idx = i;
  10149. break;
  10150. }
  10151. }
  10152. // Resize the output vector to keep only the tokens above the tail location
  10153. candidates->size = last_idx;
  10154. if (ctx) {
  10155. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10156. }
  10157. }
  10158. void llama_sample_typical(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  10159. // Reference implementation:
  10160. // https://github.com/huggingface/transformers/compare/main...cimeister:typical-sampling:typical-pr
  10161. if (p >= 1.0f) {
  10162. return;
  10163. }
  10164. // Compute the softmax of logits and calculate entropy
  10165. llama_sample_softmax(nullptr, candidates);
  10166. const int64_t t_start_sample_us = ggml_time_us();
  10167. float entropy = 0.0f;
  10168. for (size_t i = 0; i < candidates->size; ++i) {
  10169. entropy += -candidates->data[i].p * logf(candidates->data[i].p);
  10170. }
  10171. // Compute the absolute difference between negative log probability and entropy for each candidate
  10172. std::vector<float> shifted_scores;
  10173. for (size_t i = 0; i < candidates->size; ++i) {
  10174. float shifted_score = fabsf(-logf(candidates->data[i].p) - entropy);
  10175. shifted_scores.push_back(shifted_score);
  10176. }
  10177. // Sort tokens based on the shifted_scores and their corresponding indices
  10178. std::vector<size_t> indices(candidates->size);
  10179. std::iota(indices.begin(), indices.end(), 0);
  10180. std::sort(indices.begin(), indices.end(), [&](size_t a, size_t b) {
  10181. return shifted_scores[a] < shifted_scores[b];
  10182. });
  10183. // Compute the cumulative probabilities
  10184. float cum_sum = 0.0f;
  10185. size_t last_idx = indices.size();
  10186. for (size_t i = 0; i < indices.size(); ++i) {
  10187. size_t idx = indices[i];
  10188. cum_sum += candidates->data[idx].p;
  10189. // Check if the running sum is greater than typical or if we have kept at least min_keep tokens
  10190. if (cum_sum > p && i >= min_keep - 1) {
  10191. last_idx = i + 1;
  10192. break;
  10193. }
  10194. }
  10195. // Resize the output vector to keep only the locally typical tokens
  10196. std::vector<llama_token_data> new_candidates;
  10197. for (size_t i = 0; i < last_idx; ++i) {
  10198. size_t idx = indices[i];
  10199. new_candidates.push_back(candidates->data[idx]);
  10200. }
  10201. // Replace the data in candidates with the new_candidates data
  10202. std::copy(new_candidates.begin(), new_candidates.end(), candidates->data);
  10203. candidates->size = new_candidates.size();
  10204. candidates->sorted = false;
  10205. if (ctx) {
  10206. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10207. }
  10208. }
  10209. void llama_sample_entropy(struct llama_context * ctx, llama_token_data_array * candidates_p, float min_temp, float max_temp, float exponent_val) {
  10210. const int64_t t_start_sample_us = ggml_time_us();
  10211. // no need to do anything if there is only one (or zero) candidates
  10212. if(candidates_p->size <= 1) {
  10213. return;
  10214. }
  10215. // Calculate maximum possible entropy
  10216. float max_entropy = -logf(1.0f / candidates_p->size);
  10217. llama_sample_softmax(nullptr, candidates_p);
  10218. // Calculate entropy of the softmax probabilities
  10219. float entropy = 0.0f;
  10220. for (size_t i = 0; i < candidates_p->size; ++i) {
  10221. float prob = candidates_p->data[i].p;
  10222. if (prob > 0.0f) { // Ensure no log(0)
  10223. entropy -= prob * logf(prob);
  10224. }
  10225. }
  10226. // Normalize the entropy (max_entropy cannot be 0 here because we checked candidates_p->size != 1 above)
  10227. float normalized_entropy = entropy / max_entropy;
  10228. // Map the normalized entropy to the desired temperature range using the power function
  10229. float dyn_temp = min_temp + (max_temp - min_temp) * powf(normalized_entropy, exponent_val);
  10230. #ifdef DEBUG
  10231. LLAMA_LOG_INFO("Your text maxtemp value is: %f\n", max_temp);
  10232. LLAMA_LOG_INFO("Entropy: %f\n", entropy);
  10233. LLAMA_LOG_INFO("Max Possible Entropy: %f\n", max_entropy);
  10234. LLAMA_LOG_INFO("Normalized Entropy: %f\n", normalized_entropy);
  10235. LLAMA_LOG_INFO("Exponent: %f\n", exponent_val);
  10236. LLAMA_LOG_INFO("Dynamic Temperature (dyn_temp): %f\n", dyn_temp);
  10237. #endif
  10238. // Apply the dynamically calculated temperature scaling
  10239. for (size_t i = 0; i < candidates_p->size; ++i) {
  10240. candidates_p->data[i].logit /= dyn_temp;
  10241. }
  10242. // Re-compute softmax probabilities after scaling logits with dynamic temperature
  10243. double max_l_double = candidates_p->data[0].logit;
  10244. double cum_sum_double = 0.0;
  10245. for (size_t i = 0; i < candidates_p->size; ++i) {
  10246. double p = exp(candidates_p->data[i].logit - max_l_double);
  10247. candidates_p->data[i].p = p; // Store the scaled probability
  10248. cum_sum_double += p;
  10249. }
  10250. for (size_t i = 0; i < candidates_p->size; ++i) {
  10251. candidates_p->data[i].p /= cum_sum_double; // Re-normalize the probabilities
  10252. }
  10253. #ifdef DEBUG
  10254. // Print the updated top 25 probabilities after temperature scaling
  10255. LLAMA_LOG_INFO("\nUpdated Top 25 Probabilities After Dynamic Temperature Scaling (in percentages):\n");
  10256. for (size_t i = 0; i < 25 && i < candidates_p->size; ++i) {
  10257. LLAMA_LOG_INFO("Token %zu: %f%%\n", i + 1, candidates_p->data[i].p * 100.0f);
  10258. }
  10259. #endif
  10260. if (ctx) {
  10261. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10262. }
  10263. }
  10264. void llama_sample_temp(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  10265. const int64_t t_start_sample_us = ggml_time_us();
  10266. for (size_t i = 0; i < candidates_p->size; ++i) {
  10267. candidates_p->data[i].logit /= temp;
  10268. }
  10269. if (ctx) {
  10270. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10271. }
  10272. }
  10273. void llama_sample_repetition_penalties(
  10274. struct llama_context * ctx,
  10275. llama_token_data_array * candidates,
  10276. const llama_token * last_tokens,
  10277. size_t penalty_last_n,
  10278. float penalty_repeat,
  10279. float penalty_freq,
  10280. float penalty_present) {
  10281. if (penalty_last_n == 0 || (penalty_repeat == 1.0f && penalty_freq == 0.0f && penalty_present == 0.0f)) {
  10282. return;
  10283. }
  10284. const int64_t t_start_sample_us = ggml_time_us();
  10285. // Create a frequency map to count occurrences of each token in last_tokens
  10286. std::unordered_map<llama_token, int> token_count;
  10287. for (size_t i = 0; i < penalty_last_n; ++i) {
  10288. token_count[last_tokens[i]]++;
  10289. }
  10290. // Apply frequency and presence penalties to the candidates
  10291. for (size_t i = 0; i < candidates->size; ++i) {
  10292. const auto token_iter = token_count.find(candidates->data[i].id);
  10293. if (token_iter == token_count.end()) {
  10294. continue;
  10295. }
  10296. const int count = token_iter->second;
  10297. // 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.
  10298. // This is common fix for this problem, which is to multiply by the penalty instead of dividing.
  10299. if (candidates->data[i].logit <= 0) {
  10300. candidates->data[i].logit *= penalty_repeat;
  10301. } else {
  10302. candidates->data[i].logit /= penalty_repeat;
  10303. }
  10304. candidates->data[i].logit -= float(count) * penalty_freq + float(count > 0) * penalty_present;
  10305. }
  10306. candidates->sorted = false;
  10307. if (ctx) {
  10308. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10309. }
  10310. }
  10311. void llama_sample_grammar(struct llama_context * ctx, llama_token_data_array * candidates, const struct llama_grammar * grammar) {
  10312. GGML_ASSERT(ctx);
  10313. const int64_t t_start_sample_us = ggml_time_us();
  10314. bool allow_eos = false;
  10315. for (const auto & stack : grammar->stacks) {
  10316. if (stack.empty()) {
  10317. allow_eos = true;
  10318. break;
  10319. }
  10320. }
  10321. const llama_token eos = llama_token_eos(&ctx->model);
  10322. std::vector<std::pair<std::vector<uint32_t>, llama_partial_utf8>> candidates_decoded;
  10323. candidates_decoded.reserve(candidates->size);
  10324. std::vector<llama_grammar_candidate> candidates_grammar;
  10325. candidates_grammar.reserve(candidates->size);
  10326. for (size_t i = 0; i < candidates->size; ++i) {
  10327. const llama_token id = candidates->data[i].id;
  10328. const std::string piece = llama_token_to_piece(ctx, id);
  10329. if (id == eos) {
  10330. if (!allow_eos) {
  10331. candidates->data[i].logit = -INFINITY;
  10332. }
  10333. } else if (piece.empty() || piece[0] == 0) {
  10334. candidates->data[i].logit = -INFINITY;
  10335. } else {
  10336. candidates_decoded.push_back(decode_utf8(piece, grammar->partial_utf8));
  10337. candidates_grammar.push_back({ i, candidates_decoded.back().first.data(), candidates_decoded.back().second });
  10338. }
  10339. }
  10340. const auto rejects = llama_grammar_reject_candidates(grammar->rules, grammar->stacks, candidates_grammar);
  10341. for (const auto & reject : rejects) {
  10342. candidates->data[reject.index].logit = -INFINITY;
  10343. }
  10344. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10345. }
  10346. static void llama_log_softmax(float * array, size_t size) {
  10347. float max_l = *std::max_element(array, array + size);
  10348. float sum = 0.f;
  10349. for (size_t i = 0; i < size; ++i) {
  10350. float p = expf(array[i] - max_l);
  10351. sum += p;
  10352. array[i] = p;
  10353. }
  10354. for (size_t i = 0; i < size; ++i) {
  10355. array[i] = logf(array[i] / sum);
  10356. }
  10357. }
  10358. void llama_sample_apply_guidance(
  10359. struct llama_context * ctx,
  10360. float * logits,
  10361. float * logits_guidance,
  10362. float scale) {
  10363. GGML_ASSERT(ctx);
  10364. const auto t_start_sample_us = ggml_time_us();
  10365. const auto n_vocab = llama_n_vocab(llama_get_model(ctx));
  10366. llama_log_softmax(logits, n_vocab);
  10367. llama_log_softmax(logits_guidance, n_vocab);
  10368. for (int i = 0; i < n_vocab; ++i) {
  10369. auto & l = logits[i];
  10370. const auto & g = logits_guidance[i];
  10371. l = scale * (l - g) + g;
  10372. }
  10373. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10374. }
  10375. llama_token llama_sample_token_mirostat(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, int32_t m, float * mu) {
  10376. GGML_ASSERT(ctx);
  10377. auto N = float(llama_n_vocab(llama_get_model(ctx)));
  10378. int64_t t_start_sample_us;
  10379. t_start_sample_us = ggml_time_us();
  10380. llama_sample_softmax(nullptr, candidates);
  10381. // Estimate s_hat using the most probable m tokens
  10382. float s_hat = 0.0;
  10383. float sum_ti_bi = 0.0;
  10384. float sum_ti_sq = 0.0;
  10385. for (size_t i = 0; i < size_t(m - 1) && i < candidates->size - 1; ++i) {
  10386. float t_i = logf(float(i + 2) / float(i + 1));
  10387. float b_i = logf(candidates->data[i].p / candidates->data[i + 1].p);
  10388. sum_ti_bi += t_i * b_i;
  10389. sum_ti_sq += t_i * t_i;
  10390. }
  10391. s_hat = sum_ti_bi / sum_ti_sq;
  10392. // Compute k from the estimated s_hat and target surprise value
  10393. float epsilon_hat = s_hat - 1;
  10394. float k = powf((epsilon_hat * powf(2, *mu)) / (1 - powf(N, -epsilon_hat)), 1 / s_hat);
  10395. // Sample the next word X using top-k sampling
  10396. llama_sample_top_k(nullptr, candidates, int(k), 1);
  10397. if (ctx) {
  10398. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10399. }
  10400. llama_token X = llama_sample_token(ctx, candidates);
  10401. t_start_sample_us = ggml_time_us();
  10402. // Compute error as the difference between observed surprise and target surprise value
  10403. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  10404. return candidate.id == X;
  10405. }));
  10406. float observed_surprise = -log2f(candidates->data[X_idx].p);
  10407. float e = observed_surprise - tau;
  10408. // Update mu using the learning rate and error
  10409. *mu = *mu - eta * e;
  10410. if (ctx) {
  10411. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10412. }
  10413. return X;
  10414. }
  10415. llama_token llama_sample_token_mirostat_v2(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, float * mu) {
  10416. int64_t t_start_sample_us;
  10417. t_start_sample_us = ggml_time_us();
  10418. llama_sample_softmax(ctx, candidates);
  10419. // Truncate the words with surprise values greater than mu
  10420. candidates->size = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  10421. return -log2f(candidate.p) > *mu;
  10422. }));
  10423. if (candidates->size == 0) {
  10424. candidates->size = 1;
  10425. }
  10426. if (ctx) {
  10427. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10428. }
  10429. // Normalize the probabilities of the remaining words
  10430. llama_sample_softmax(ctx, candidates);
  10431. // Sample the next word X from the remaining words
  10432. llama_token X = llama_sample_token(ctx, candidates);
  10433. t_start_sample_us = ggml_time_us();
  10434. // Compute error as the difference between observed surprise and target surprise value
  10435. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  10436. return candidate.id == X;
  10437. }));
  10438. float observed_surprise = -log2f(candidates->data[X_idx].p);
  10439. float e = observed_surprise - tau;
  10440. // Update mu using the learning rate and error
  10441. *mu = *mu - eta * e;
  10442. if (ctx) {
  10443. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10444. }
  10445. return X;
  10446. }
  10447. llama_token llama_sample_token_greedy(struct llama_context * ctx, llama_token_data_array * candidates) {
  10448. const int64_t t_start_sample_us = ggml_time_us();
  10449. // Find max element
  10450. auto * max_iter = std::max_element(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  10451. return a.logit < b.logit;
  10452. });
  10453. llama_token result = max_iter->id;
  10454. if (ctx) {
  10455. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10456. ctx->n_sample++;
  10457. }
  10458. return result;
  10459. }
  10460. llama_token llama_sample_token(struct llama_context * ctx, llama_token_data_array * candidates) {
  10461. GGML_ASSERT(ctx);
  10462. const int64_t t_start_sample_us = ggml_time_us();
  10463. llama_sample_softmax(nullptr, candidates);
  10464. std::vector<float> probs;
  10465. probs.reserve(candidates->size);
  10466. for (size_t i = 0; i < candidates->size; ++i) {
  10467. probs.push_back(candidates->data[i].p);
  10468. }
  10469. std::discrete_distribution<> dist(probs.begin(), probs.end());
  10470. auto & rng = ctx->rng;
  10471. int idx = dist(rng);
  10472. llama_token result = candidates->data[idx].id;
  10473. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10474. ctx->n_sample++;
  10475. return result;
  10476. }
  10477. void llama_grammar_accept_token(struct llama_context * ctx, struct llama_grammar * grammar, llama_token token) {
  10478. const int64_t t_start_sample_us = ggml_time_us();
  10479. if (token == llama_token_eos(&ctx->model)) {
  10480. for (const auto & stack : grammar->stacks) {
  10481. if (stack.empty()) {
  10482. return;
  10483. }
  10484. }
  10485. GGML_ASSERT(false);
  10486. }
  10487. const std::string piece = llama_token_to_piece(ctx, token);
  10488. // Note terminating 0 in decoded string
  10489. const auto decoded = decode_utf8(piece, grammar->partial_utf8);
  10490. const auto & code_points = decoded.first;
  10491. for (auto it = code_points.begin(), end = code_points.end() - 1; it != end; ++it) {
  10492. grammar->stacks = llama_grammar_accept(grammar->rules, grammar->stacks, *it);
  10493. }
  10494. grammar->partial_utf8 = decoded.second;
  10495. GGML_ASSERT(!grammar->stacks.empty());
  10496. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10497. }
  10498. //
  10499. // Beam search
  10500. //
  10501. struct llama_beam {
  10502. std::vector<llama_token> tokens;
  10503. float p; // Cumulative beam probability (renormalized relative to all beams)
  10504. bool eob; // Initialize end-of-beam to false. Callback sets this to true.
  10505. // Sort beams by probability. In case of ties, prefer beams at eob.
  10506. bool operator<(const llama_beam & rhs) const {
  10507. return std::make_pair(p, eob) < std::make_pair(rhs.p, rhs.eob);
  10508. }
  10509. // Shift off first n tokens and discard them.
  10510. void shift_tokens(const size_t n) {
  10511. if (n) {
  10512. std::copy(tokens.begin() + n, tokens.end(), tokens.begin());
  10513. tokens.resize(tokens.size() - n);
  10514. }
  10515. }
  10516. llama_beam_view view() const { return {tokens.data(), tokens.size(), p, eob}; }
  10517. };
  10518. // A struct for calculating logit-related info.
  10519. struct llama_logit_info {
  10520. const float * const logits;
  10521. const int n_vocab;
  10522. const float max_l;
  10523. const float normalizer;
  10524. struct sum_exp {
  10525. float max_l;
  10526. float operator()(float sum, float l) const { return sum + std::exp(l - max_l); }
  10527. };
  10528. llama_logit_info(llama_context * ctx)
  10529. : logits(llama_get_logits(ctx))
  10530. , n_vocab(llama_n_vocab(llama_get_model(ctx)))
  10531. , max_l(*std::max_element(logits, logits + n_vocab))
  10532. , normalizer(1.0f / std::accumulate(logits, logits + n_vocab, 0.0f, sum_exp{max_l}))
  10533. { }
  10534. llama_token_data get_token_data(const llama_token token_id) const {
  10535. constexpr auto p = std::numeric_limits<float>::quiet_NaN(); // never used
  10536. return {token_id, logits[token_id], p};
  10537. }
  10538. // Return top k token_data by logit.
  10539. std::vector<llama_token_data> top_k(size_t k) {
  10540. std::vector<llama_token_data> min_heap; // min-heap by logit
  10541. const llama_token k_min = std::min(static_cast<llama_token>(k), n_vocab);
  10542. min_heap.reserve(k_min);
  10543. for (llama_token token_id = 0 ; token_id < k_min ; ++token_id) {
  10544. min_heap.push_back(get_token_data(token_id));
  10545. }
  10546. auto comp = [](const llama_token_data & a, const llama_token_data & b) { return a.logit > b.logit; };
  10547. std::make_heap(min_heap.begin(), min_heap.end(), comp);
  10548. for (llama_token token_id = k_min ; token_id < n_vocab ; ++token_id) {
  10549. if (min_heap.front().logit < logits[token_id]) {
  10550. std::pop_heap(min_heap.begin(), min_heap.end(), comp);
  10551. min_heap.back().id = token_id;
  10552. min_heap.back().logit = logits[token_id];
  10553. std::push_heap(min_heap.begin(), min_heap.end(), comp);
  10554. }
  10555. }
  10556. return min_heap;
  10557. }
  10558. float probability_from_logit(float logit) const {
  10559. return normalizer * std::exp(logit - max_l);
  10560. }
  10561. };
  10562. struct llama_beam_search_data {
  10563. llama_context * ctx;
  10564. size_t n_beams;
  10565. int n_past;
  10566. int n_predict;
  10567. std::vector<llama_beam> beams;
  10568. std::vector<llama_beam> next_beams;
  10569. // Re-calculated on each loop iteration
  10570. size_t common_prefix_length;
  10571. // Used to communicate to/from callback on beams state.
  10572. std::vector<llama_beam_view> beam_views;
  10573. llama_beam_search_data(llama_context * ctx, size_t n_beams, int n_past, int n_predict)
  10574. : ctx(ctx)
  10575. , n_beams(n_beams)
  10576. , n_past(n_past)
  10577. , n_predict(n_predict)
  10578. , beam_views(n_beams) {
  10579. beams.reserve(n_beams);
  10580. next_beams.reserve(n_beams);
  10581. }
  10582. // Collapse beams to a single beam given by index.
  10583. void collapse_beams(const size_t beam_idx) {
  10584. if (0u < beam_idx) {
  10585. std::swap(beams[0], beams[beam_idx]);
  10586. }
  10587. beams.resize(1);
  10588. }
  10589. // Min-heaps are used to efficiently collect the top-k elements (k=n_beams).
  10590. // The repetitive patterns below reflect the 2 stages of heaps:
  10591. // * Gather elements until the vector is full, then call std::make_heap() on it.
  10592. // * If the heap is full and a new element is found that should be included, pop the
  10593. // least element to the back(), replace it with the new, then push it into the heap.
  10594. void fill_next_beams_by_top_probabilities(llama_beam & beam) {
  10595. // Min-heaps use a greater-than comparator.
  10596. const auto comp = [](const llama_beam & a, const llama_beam & b) { return a.p > b.p; };
  10597. if (beam.eob) {
  10598. // beam is at end-of-sentence, so just copy it to next_beams if its probability is high enough.
  10599. if (next_beams.size() < n_beams) {
  10600. next_beams.push_back(std::move(beam));
  10601. if (next_beams.size() == n_beams) {
  10602. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  10603. }
  10604. } else if (next_beams.front().p < beam.p) {
  10605. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  10606. next_beams.back() = std::move(beam);
  10607. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  10608. }
  10609. } else {
  10610. // beam is not at end-of-sentence, so branch with next top_k tokens.
  10611. if (!beam.tokens.empty()) {
  10612. llama_decode(ctx, llama_batch_get_one(beam.tokens.data(), beam.tokens.size(), n_past, 0));
  10613. }
  10614. llama_logit_info logit_info(ctx);
  10615. std::vector<llama_token_data> next_tokens = logit_info.top_k(n_beams);
  10616. size_t i=0;
  10617. if (next_beams.size() < n_beams) {
  10618. for (; next_beams.size() < n_beams ; ++i) {
  10619. llama_beam next_beam = beam;
  10620. next_beam.tokens.push_back(next_tokens[i].id);
  10621. next_beam.p *= logit_info.probability_from_logit(next_tokens[i].logit);
  10622. next_beams.push_back(std::move(next_beam));
  10623. }
  10624. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  10625. } else {
  10626. for (; next_beams.front().p == 0.0f ; ++i) {
  10627. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  10628. next_beams.back() = beam;
  10629. next_beams.back().tokens.push_back(next_tokens[i].id);
  10630. next_beams.back().p *= logit_info.probability_from_logit(next_tokens[i].logit);
  10631. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  10632. }
  10633. }
  10634. for (; i < n_beams ; ++i) {
  10635. const float next_p = beam.p * logit_info.probability_from_logit(next_tokens[i].logit);
  10636. if (next_beams.front().p < next_p) {
  10637. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  10638. next_beams.back() = beam;
  10639. next_beams.back().tokens.push_back(next_tokens[i].id);
  10640. next_beams.back().p = next_p;
  10641. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  10642. }
  10643. }
  10644. }
  10645. }
  10646. // Find common_prefix_length based on beams.
  10647. // Requires beams is not empty.
  10648. size_t find_common_prefix_length() {
  10649. size_t common_prefix_length = beams[0].tokens.size();
  10650. for (size_t i = 1 ; i < beams.size() ; ++i) {
  10651. common_prefix_length = std::min(common_prefix_length, beams[i].tokens.size());
  10652. for (size_t j = 0 ; j < common_prefix_length ; ++j) {
  10653. if (beams[0].tokens[j] != beams[i].tokens[j]) {
  10654. common_prefix_length = j;
  10655. break;
  10656. }
  10657. }
  10658. }
  10659. return common_prefix_length;
  10660. }
  10661. // Construct beams_state to send back to caller via the callback function.
  10662. // Side effect: set common_prefix_length = find_common_prefix_length();
  10663. llama_beams_state get_beams_state(const bool last_call) {
  10664. for (size_t i = 0 ; i < beams.size() ; ++i) {
  10665. beam_views[i] = beams[i].view();
  10666. }
  10667. common_prefix_length = find_common_prefix_length();
  10668. return {beam_views.data(), beams.size(), common_prefix_length, last_call};
  10669. }
  10670. // Loop:
  10671. // * while i < n_predict, AND
  10672. // * any of the beams have not yet reached end-of-beam (eob), AND
  10673. // * the highest probability beam(s) (plural in case of ties) are not at end-of-sentence
  10674. // (since all other beam probabilities can only decrease)
  10675. void loop(const llama_beam_search_callback_fn_t callback, void * const callback_data) {
  10676. beams.push_back({{}, 1.0f, false}); // Start with one empty beam w/ probability = 1.0 and !eob.
  10677. const auto not_eob = [](const llama_beam & beam) { return !beam.eob; };
  10678. for (int i = 0 ; i < n_predict && std::any_of(beams.begin(),beams.end(),not_eob) &&
  10679. !beams[top_beam_index()].eob ; ++i) {
  10680. callback(callback_data, get_beams_state(false)); // Sets common_prefix_length
  10681. update_beams_from_beam_views(); // Update values (p,eob) that callback may have changed.
  10682. if (common_prefix_length) {
  10683. llama_decode(ctx, llama_batch_get_one(beams[0].tokens.data(), common_prefix_length, n_past, 0));
  10684. n_past += common_prefix_length;
  10685. }
  10686. // Zero-out next_beam probabilities to place them last in following min-heap.
  10687. std::for_each(next_beams.begin(), next_beams.end(), [](llama_beam & beam) { beam.p = 0.0f; });
  10688. for (llama_beam & beam : beams) {
  10689. beam.shift_tokens(common_prefix_length);
  10690. fill_next_beams_by_top_probabilities(beam);
  10691. }
  10692. // next_beams become the beams of next/final iteration. Swap them to re-use memory.
  10693. beams.swap(next_beams);
  10694. renormalize_beam_probabilities(beams);
  10695. }
  10696. collapse_beams(top_beam_index());
  10697. callback(callback_data, get_beams_state(true));
  10698. }
  10699. // As beams grow, the cumulative probabilities decrease.
  10700. // Renormalize them to avoid floating point underflow.
  10701. static void renormalize_beam_probabilities(std::vector<llama_beam> & beams) {
  10702. const auto sum_p = [](float sum, llama_beam & beam) { return sum + beam.p; };
  10703. const float inv_sum = 1.0f / std::accumulate(beams.begin(), beams.end(), 0.0f, sum_p);
  10704. std::for_each(beams.begin(), beams.end(), [=](llama_beam & beam) { beam.p *= inv_sum; });
  10705. }
  10706. // Assumes beams is non-empty. Uses llama_beam::operator<() for ordering.
  10707. size_t top_beam_index() {
  10708. return std::max_element(beams.begin(), beams.end()) - beams.begin();
  10709. }
  10710. // Copy (p,eob) for each beam which may have been changed by the callback.
  10711. void update_beams_from_beam_views() {
  10712. for (size_t i = 0 ; i < beams.size() ; ++i) {
  10713. beams[i].p = beam_views[i].p;
  10714. beams[i].eob = beam_views[i].eob;
  10715. }
  10716. }
  10717. };
  10718. void llama_beam_search(llama_context * ctx,
  10719. llama_beam_search_callback_fn_t callback, void * callback_data,
  10720. size_t n_beams, int n_past, int n_predict) {
  10721. assert(ctx);
  10722. const int64_t t_start_sample_us = ggml_time_us();
  10723. llama_beam_search_data beam_search_data(ctx, n_beams, n_past, n_predict);
  10724. beam_search_data.loop(callback, callback_data);
  10725. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10726. ctx->n_sample++;
  10727. }
  10728. //
  10729. // quantization
  10730. //
  10731. struct quantize_state_internal {
  10732. const llama_model & model;
  10733. const llama_model_quantize_params * params;
  10734. int n_attention_wv = 0;
  10735. int n_ffn_down = 0;
  10736. int n_ffn_gate = 0;
  10737. int n_ffn_up = 0;
  10738. int i_attention_wv = 0;
  10739. int i_ffn_down = 0;
  10740. int i_ffn_gate = 0;
  10741. int i_ffn_up = 0;
  10742. int n_k_quantized = 0;
  10743. int n_fallback = 0;
  10744. bool has_imatrix = false;
  10745. // used to figure out if a model shares tok_embd with the output weight
  10746. bool has_output = false;
  10747. quantize_state_internal(const llama_model & model, const llama_model_quantize_params * params)
  10748. : model(model)
  10749. , params(params)
  10750. {}
  10751. };
  10752. static void llama_tensor_dequantize_internal(
  10753. struct ggml_tensor * tensor, std::vector<no_init<float>> & output, std::vector<std::thread> & workers,
  10754. const size_t nelements, const int nthread
  10755. ) {
  10756. if (output.size() < nelements) {
  10757. output.resize(nelements);
  10758. }
  10759. float * f32_output = (float *) output.data();
  10760. ggml_type_traits_t qtype;
  10761. if (ggml_is_quantized(tensor->type)) {
  10762. qtype = ggml_internal_get_type_traits(tensor->type);
  10763. if (qtype.to_float == NULL) {
  10764. throw std::runtime_error(format("type %s unsupported for integer quantization: no dequantization available", ggml_type_name(tensor->type)));
  10765. }
  10766. } else if (tensor->type != GGML_TYPE_F16) {
  10767. throw std::runtime_error(format("cannot dequantize/convert tensor type %s", ggml_type_name(tensor->type)));
  10768. }
  10769. if (nthread < 2) {
  10770. if (tensor->type == GGML_TYPE_F16) {
  10771. ggml_fp16_to_fp32_row((ggml_fp16_t *)tensor->data, f32_output, nelements);
  10772. } else if (ggml_is_quantized(tensor->type)) {
  10773. qtype.to_float(tensor->data, f32_output, nelements);
  10774. } else {
  10775. GGML_ASSERT(false); // unreachable
  10776. }
  10777. return;
  10778. }
  10779. size_t block_size = tensor->type == GGML_TYPE_F16 ? 1 : (size_t)ggml_blck_size(tensor->type);
  10780. size_t block_size_bytes = ggml_type_size(tensor->type);
  10781. GGML_ASSERT(nelements % block_size == 0);
  10782. size_t nblocks = nelements / block_size;
  10783. size_t blocks_per_thread = nblocks / nthread;
  10784. size_t spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count
  10785. size_t in_buff_offs = 0;
  10786. size_t out_buff_offs = 0;
  10787. for (int tnum = 0; tnum < nthread; tnum++) {
  10788. size_t thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread
  10789. size_t thr_elems = thr_blocks * block_size; // number of elements for this thread
  10790. size_t thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread
  10791. auto compute = [qtype] (ggml_type typ, uint8_t * inbuf, float * outbuf, int nels) {
  10792. if (typ == GGML_TYPE_F16) {
  10793. ggml_fp16_to_fp32_row((ggml_fp16_t *)inbuf, outbuf, nels);
  10794. } else {
  10795. qtype.to_float(inbuf, outbuf, nels);
  10796. }
  10797. };
  10798. workers.emplace_back(compute, tensor->type, (uint8_t *) tensor->data + in_buff_offs, f32_output + out_buff_offs, thr_elems);
  10799. in_buff_offs += thr_block_bytes;
  10800. out_buff_offs += thr_elems;
  10801. }
  10802. for (auto & w : workers) { w.join(); }
  10803. workers.clear();
  10804. }
  10805. static ggml_type llama_tensor_get_type(quantize_state_internal & qs, ggml_type new_type, const ggml_tensor * tensor, llama_ftype ftype) {
  10806. const std::string name = ggml_get_name(tensor);
  10807. // TODO: avoid hardcoded tensor names - use the TN_* constants
  10808. const llm_arch arch = qs.model.arch;
  10809. const auto tn = LLM_TN(arch);
  10810. auto use_more_bits = [](int i_layer, int num_layers) -> bool {
  10811. return i_layer < num_layers/8 || i_layer >= 7*num_layers/8 || (i_layer - num_layers/8)%3 == 2;
  10812. };
  10813. const int n_expert = std::max(1, (int)qs.model.hparams.n_expert);
  10814. auto layer_info = [n_expert] (int i_layer, int n_layer, const char * name) {
  10815. if (n_expert > 1) {
  10816. // Believe it or not, "experts" in the FFN of Mixtral-8x7B are not consecutive, but iccasionally randomly
  10817. // sprinkled in the model. Hence, simply dividing i_ffn_down by n_expert does not work
  10818. // for getting the current layer as I initially thought, and we need to resort to parsing the
  10819. // tensor name.
  10820. if (sscanf(name, "blk.%d.", &i_layer) != 1) {
  10821. throw std::runtime_error(format("Failed to determine layer for tensor %s", name));
  10822. }
  10823. if (i_layer < 0 || i_layer >= n_layer) {
  10824. throw std::runtime_error(format("Bad layer %d for tensor %s. Must be in [0, %d)", i_layer, name, n_layer));
  10825. }
  10826. }
  10827. return std::make_pair(i_layer, n_layer);
  10828. };
  10829. // for arches that share the same tensor between the token embeddings and the output, we quantize the token embeddings
  10830. // with the quantization of the output tensor
  10831. if (name == tn(LLM_TENSOR_OUTPUT, "weight") || (!qs.has_output && name == tn(LLM_TENSOR_TOKEN_EMBD, "weight"))) {
  10832. if (qs.params->output_tensor_type < GGML_TYPE_COUNT) {
  10833. new_type = qs.params->output_tensor_type;
  10834. } else {
  10835. int nx = tensor->ne[0];
  10836. if (arch == LLM_ARCH_FALCON || nx % QK_K != 0) {
  10837. new_type = GGML_TYPE_Q8_0;
  10838. }
  10839. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  10840. ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ||
  10841. ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  10842. new_type = GGML_TYPE_Q5_K;
  10843. }
  10844. else if (new_type != GGML_TYPE_Q8_0) {
  10845. new_type = GGML_TYPE_Q6_K;
  10846. }
  10847. }
  10848. } else if (name == "token_embd.weight") {
  10849. if (qs.params->token_embedding_type < GGML_TYPE_COUNT) {
  10850. new_type = qs.params->token_embedding_type;
  10851. } else {
  10852. if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS ||
  10853. ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  10854. new_type = GGML_TYPE_Q2_K;
  10855. }
  10856. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) {
  10857. new_type = GGML_TYPE_IQ3_S;
  10858. }
  10859. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  10860. new_type = GGML_TYPE_IQ3_S;
  10861. }
  10862. }
  10863. } else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S ||
  10864. ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  10865. if (name.find("attn_v.weight") != std::string::npos) {
  10866. if (qs.model.hparams.n_gqa() >= 4 || qs.model.hparams.n_expert >= 4) new_type = GGML_TYPE_Q4_K;
  10867. else new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  10868. ++qs.i_attention_wv;
  10869. }
  10870. else if (qs.model.hparams.n_expert == 8 && name.find("attn_k.weight") != std::string::npos) {
  10871. new_type = GGML_TYPE_Q4_K;
  10872. }
  10873. else if (name.find("ffn_down") != std::string::npos) {
  10874. if (qs.i_ffn_down < qs.n_ffn_down/8) {
  10875. new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  10876. }
  10877. ++qs.i_ffn_down;
  10878. }
  10879. else if (name.find("attn_output.weight") != std::string::npos) {
  10880. if (qs.model.hparams.n_expert == 8) {
  10881. new_type = GGML_TYPE_Q5_K;
  10882. } else {
  10883. if (ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) new_type = GGML_TYPE_IQ2_XXS;
  10884. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) new_type = GGML_TYPE_IQ3_S;
  10885. }
  10886. }
  10887. } else if (name.find("attn_v.weight") != std::string::npos) {
  10888. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) {
  10889. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  10890. }
  10891. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && qs.model.hparams.n_gqa() >= 4) {
  10892. new_type = GGML_TYPE_Q4_K;
  10893. }
  10894. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  10895. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : !qs.has_imatrix ? GGML_TYPE_IQ3_S : GGML_TYPE_IQ3_XXS;
  10896. }
  10897. else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S) && qs.model.hparams.n_gqa() >= 4) {
  10898. new_type = GGML_TYPE_Q4_K;
  10899. }
  10900. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  10901. new_type = GGML_TYPE_Q4_K;
  10902. }
  10903. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  10904. new_type = qs.i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  10905. }
  10906. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  10907. else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && qs.model.hparams.n_gqa() >= 4) {
  10908. new_type = GGML_TYPE_Q5_K;
  10909. }
  10910. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
  10911. use_more_bits(qs.i_attention_wv, qs.n_attention_wv)) new_type = GGML_TYPE_Q6_K;
  10912. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && qs.i_attention_wv < 4) new_type = GGML_TYPE_Q5_K;
  10913. else if (QK_K == 64 && (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S) &&
  10914. (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;
  10915. if (qs.model.type == MODEL_70B) {
  10916. // In the 70B model we have 8 heads sharing the same attn_v weights. As a result, the attn_v.weight tensor is
  10917. // 8x smaller compared to attn_q.weight. Hence, we can get a nice boost in quantization accuracy with
  10918. // nearly negligible increase in model size by quantizing this tensor with more bits:
  10919. if (new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K) new_type = GGML_TYPE_Q5_K;
  10920. }
  10921. if (qs.model.hparams.n_expert == 8) {
  10922. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  10923. // TODO: explore better strategies
  10924. new_type = GGML_TYPE_Q8_0;
  10925. }
  10926. ++qs.i_attention_wv;
  10927. } else if (name.find("attn_k.weight") != std::string::npos) {
  10928. if (qs.model.hparams.n_expert == 8) {
  10929. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  10930. // TODO: explore better strategies
  10931. new_type = GGML_TYPE_Q8_0;
  10932. }
  10933. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  10934. new_type = GGML_TYPE_IQ3_XXS;
  10935. }
  10936. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  10937. new_type = GGML_TYPE_IQ2_S;
  10938. }
  10939. } else if (name.find("attn_q.weight") != std::string::npos) {
  10940. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  10941. new_type = GGML_TYPE_IQ3_XXS;
  10942. }
  10943. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  10944. new_type = GGML_TYPE_IQ2_S;
  10945. }
  10946. } else if (name.find("ffn_down") != std::string::npos) {
  10947. auto info = layer_info(qs.i_ffn_down, qs.n_ffn_down, name.c_str());
  10948. int i_layer = info.first, n_layer = info.second;
  10949. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  10950. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S) {
  10951. if (i_layer < n_layer/8) new_type = GGML_TYPE_Q4_K;
  10952. }
  10953. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS && !qs.has_imatrix) {
  10954. new_type = i_layer < n_layer/8 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  10955. }
  10956. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  10957. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q5_K
  10958. : arch != LLM_ARCH_FALCON || use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q4_K
  10959. : GGML_TYPE_Q3_K;
  10960. }
  10961. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M && (i_layer < n_layer/8 ||
  10962. (qs.model.hparams.n_expert == 8 && use_more_bits(i_layer, n_layer)))) {
  10963. new_type = GGML_TYPE_Q4_K;
  10964. }
  10965. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) {
  10966. new_type = arch == LLM_ARCH_FALCON ? GGML_TYPE_Q4_K : GGML_TYPE_Q5_K;
  10967. }
  10968. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  10969. if (arch == LLM_ARCH_FALCON) {
  10970. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q6_K :
  10971. use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  10972. } else {
  10973. if (use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  10974. }
  10975. }
  10976. else if (i_layer < n_layer/8 && (ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && !qs.has_imatrix) {
  10977. new_type = GGML_TYPE_Q5_K;
  10978. }
  10979. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M && use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  10980. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && arch != LLM_ARCH_FALCON && i_layer < n_layer/8) {
  10981. new_type = GGML_TYPE_Q5_K;
  10982. }
  10983. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_0 || ftype == LLAMA_FTYPE_MOSTLY_Q5_0)
  10984. && qs.has_imatrix && i_layer < n_layer/8) {
  10985. // Guard against craziness in the first few ffn_down layers that can happen even with imatrix for Q4_0/Q5_0.
  10986. // We only do it when an imatrix is provided because a) we want to make sure that one can always get the
  10987. // same quantization as before imatrix stuff, and b) Q4_1/Q5_1 do go crazy on ffn_down without an imatrix.
  10988. new_type = ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ? GGML_TYPE_Q4_1 : GGML_TYPE_Q5_1;
  10989. }
  10990. ++qs.i_ffn_down;
  10991. } else if (name.find("attn_output.weight") != std::string::npos) {
  10992. if (arch != LLM_ARCH_FALCON) {
  10993. if (qs.model.hparams.n_expert == 8) {
  10994. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  10995. ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL ||
  10996. ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S ||
  10997. ftype == LLAMA_FTYPE_MOSTLY_IQ3_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) {
  10998. new_type = GGML_TYPE_Q5_K;
  10999. }
  11000. } else {
  11001. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K ) new_type = GGML_TYPE_Q3_K;
  11002. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) new_type = GGML_TYPE_IQ3_S;
  11003. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M ) new_type = GGML_TYPE_Q4_K;
  11004. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L ) new_type = GGML_TYPE_Q5_K;
  11005. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M ) new_type = GGML_TYPE_Q4_K;
  11006. }
  11007. } else {
  11008. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  11009. }
  11010. }
  11011. else if (name.find("attn_qkv.weight") != std::string::npos) {
  11012. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L || ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  11013. new_type = GGML_TYPE_Q4_K;
  11014. }
  11015. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) new_type = GGML_TYPE_Q5_K;
  11016. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) new_type = GGML_TYPE_Q6_K;
  11017. }
  11018. else if (name.find("ffn_gate") != std::string::npos) {
  11019. auto info = layer_info(qs.i_ffn_gate, qs.n_ffn_gate, name.c_str());
  11020. int i_layer = info.first, n_layer = info.second;
  11021. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  11022. new_type = GGML_TYPE_IQ3_XXS;
  11023. }
  11024. ++qs.i_ffn_gate;
  11025. }
  11026. else if (name.find("ffn_up") != std::string::npos) {
  11027. auto info = layer_info(qs.i_ffn_up, qs.n_ffn_up, name.c_str());
  11028. int i_layer = info.first, n_layer = info.second;
  11029. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  11030. new_type = GGML_TYPE_IQ3_XXS;
  11031. }
  11032. ++qs.i_ffn_up;
  11033. }
  11034. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  11035. //}
  11036. // IK: let's remove this, else Q2_K is almost the same as Q3_K_S
  11037. //else if (name.find("ffn_gate") != std::string::npos || name.find("ffn_up") != std::string::npos) {
  11038. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  11039. //}
  11040. // This can be used to reduce the size of the Q5_K_S model.
  11041. // The associated PPL increase is fully in line with the size reduction
  11042. //else {
  11043. // if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_S) new_type = GGML_TYPE_Q4_K;
  11044. //}
  11045. bool convert_incompatible_tensor = false;
  11046. if (new_type == GGML_TYPE_Q2_K || new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K ||
  11047. new_type == GGML_TYPE_Q5_K || new_type == GGML_TYPE_Q6_K || new_type == GGML_TYPE_IQ4_XS ||
  11048. new_type == GGML_TYPE_IQ2_XS || new_type == GGML_TYPE_IQ2_XXS || new_type == GGML_TYPE_IQ2_S ||
  11049. new_type == GGML_TYPE_IQ3_XXS || new_type == GGML_TYPE_IQ1_S || new_type == GGML_TYPE_IQ3_S ||
  11050. new_type == GGML_TYPE_IQ1_M) {
  11051. int nx = tensor->ne[0];
  11052. int ny = tensor->ne[1];
  11053. if (nx % QK_K != 0) {
  11054. 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));
  11055. convert_incompatible_tensor = true;
  11056. } else {
  11057. ++qs.n_k_quantized;
  11058. }
  11059. }
  11060. if (convert_incompatible_tensor) {
  11061. switch (new_type) {
  11062. case GGML_TYPE_IQ2_XXS:
  11063. case GGML_TYPE_IQ2_XS:
  11064. case GGML_TYPE_IQ2_S:
  11065. case GGML_TYPE_IQ3_XXS:
  11066. case GGML_TYPE_IQ3_S:
  11067. case GGML_TYPE_IQ1_S:
  11068. case GGML_TYPE_IQ1_M:
  11069. case GGML_TYPE_Q2_K:
  11070. case GGML_TYPE_Q3_K:
  11071. case GGML_TYPE_IQ4_XS: new_type = GGML_TYPE_IQ4_NL; break;
  11072. case GGML_TYPE_Q4_K: new_type = GGML_TYPE_Q5_0; break;
  11073. case GGML_TYPE_Q5_K: new_type = GGML_TYPE_Q5_1; break;
  11074. case GGML_TYPE_Q6_K: new_type = GGML_TYPE_Q8_0; break;
  11075. default: throw std::runtime_error("\nUnsupported tensor size encountered\n");
  11076. }
  11077. LLAMA_LOG_WARN(" - using fallback quantization %s\n", ggml_type_name(new_type));
  11078. ++qs.n_fallback;
  11079. }
  11080. return new_type;
  11081. }
  11082. 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) {
  11083. std::mutex mutex;
  11084. int64_t counter = 0;
  11085. size_t new_size = 0;
  11086. if (nthread < 2) {
  11087. // single-thread
  11088. return ggml_quantize_chunk(new_type, f32_data, new_data, 0, nrows, n_per_row, imatrix);
  11089. }
  11090. auto compute = [&mutex, &counter, &new_size, new_type, f32_data, new_data, chunk_size,
  11091. nrows, n_per_row, imatrix]() {
  11092. const int64_t nrows_per_chunk = chunk_size / n_per_row;
  11093. size_t local_size = 0;
  11094. while (true) {
  11095. std::unique_lock<std::mutex> lock(mutex);
  11096. int64_t first_row = counter; counter += nrows_per_chunk;
  11097. if (first_row >= nrows) {
  11098. if (local_size > 0) {
  11099. new_size += local_size;
  11100. }
  11101. break;
  11102. }
  11103. lock.unlock();
  11104. const int64_t this_nrow = std::min(nrows - first_row, nrows_per_chunk);
  11105. local_size += ggml_quantize_chunk(new_type, f32_data, new_data, first_row * n_per_row, this_nrow, n_per_row, imatrix);
  11106. }
  11107. };
  11108. for (int it = 0; it < nthread - 1; ++it) {
  11109. workers.emplace_back(compute);
  11110. }
  11111. compute();
  11112. for (auto & w : workers) { w.join(); }
  11113. workers.clear();
  11114. return new_size;
  11115. }
  11116. static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) {
  11117. ggml_type default_type;
  11118. llama_ftype ftype = params->ftype;
  11119. switch (params->ftype) {
  11120. case LLAMA_FTYPE_MOSTLY_Q4_0: default_type = GGML_TYPE_Q4_0; break;
  11121. case LLAMA_FTYPE_MOSTLY_Q4_1: default_type = GGML_TYPE_Q4_1; break;
  11122. case LLAMA_FTYPE_MOSTLY_Q5_0: default_type = GGML_TYPE_Q5_0; break;
  11123. case LLAMA_FTYPE_MOSTLY_Q5_1: default_type = GGML_TYPE_Q5_1; break;
  11124. case LLAMA_FTYPE_MOSTLY_Q8_0: default_type = GGML_TYPE_Q8_0; break;
  11125. case LLAMA_FTYPE_MOSTLY_F16: default_type = GGML_TYPE_F16; break;
  11126. case LLAMA_FTYPE_ALL_F32: default_type = GGML_TYPE_F32; break;
  11127. // K-quants
  11128. case LLAMA_FTYPE_MOSTLY_Q2_K_S:
  11129. case LLAMA_FTYPE_MOSTLY_Q2_K: default_type = GGML_TYPE_Q2_K; break;
  11130. case LLAMA_FTYPE_MOSTLY_IQ3_XS: default_type = GGML_TYPE_IQ3_S; break;
  11131. case LLAMA_FTYPE_MOSTLY_Q3_K_S:
  11132. case LLAMA_FTYPE_MOSTLY_Q3_K_M:
  11133. case LLAMA_FTYPE_MOSTLY_Q3_K_L: default_type = GGML_TYPE_Q3_K; break;
  11134. case LLAMA_FTYPE_MOSTLY_Q4_K_S:
  11135. case LLAMA_FTYPE_MOSTLY_Q4_K_M: default_type = GGML_TYPE_Q4_K; break;
  11136. case LLAMA_FTYPE_MOSTLY_Q5_K_S:
  11137. case LLAMA_FTYPE_MOSTLY_Q5_K_M: default_type = GGML_TYPE_Q5_K; break;
  11138. case LLAMA_FTYPE_MOSTLY_Q6_K: default_type = GGML_TYPE_Q6_K; break;
  11139. case LLAMA_FTYPE_MOSTLY_IQ2_XXS: default_type = GGML_TYPE_IQ2_XXS; break;
  11140. case LLAMA_FTYPE_MOSTLY_IQ2_XS: default_type = GGML_TYPE_IQ2_XS; break;
  11141. case LLAMA_FTYPE_MOSTLY_IQ2_S: default_type = GGML_TYPE_IQ2_XS; break;
  11142. case LLAMA_FTYPE_MOSTLY_IQ2_M: default_type = GGML_TYPE_IQ2_S; break;
  11143. case LLAMA_FTYPE_MOSTLY_IQ3_XXS: default_type = GGML_TYPE_IQ3_XXS; break;
  11144. case LLAMA_FTYPE_MOSTLY_IQ1_S: default_type = GGML_TYPE_IQ1_S; break;
  11145. case LLAMA_FTYPE_MOSTLY_IQ1_M: default_type = GGML_TYPE_IQ1_M; break;
  11146. case LLAMA_FTYPE_MOSTLY_IQ4_NL: default_type = GGML_TYPE_IQ4_NL; break;
  11147. case LLAMA_FTYPE_MOSTLY_IQ4_XS: default_type = GGML_TYPE_IQ4_XS; break;
  11148. case LLAMA_FTYPE_MOSTLY_IQ3_S: default_type = GGML_TYPE_IQ3_S; break;
  11149. case LLAMA_FTYPE_MOSTLY_IQ3_M: default_type = GGML_TYPE_IQ3_S; break;
  11150. default: throw std::runtime_error(format("invalid output file type %d\n", ftype));
  11151. }
  11152. int nthread = params->nthread;
  11153. if (nthread <= 0) {
  11154. nthread = std::thread::hardware_concurrency();
  11155. }
  11156. // mmap consistently increases speed Linux, and also increases speed on Windows with
  11157. // hot cache. It may cause a slowdown on macOS, possibly related to free memory.
  11158. #if defined(__linux__) || defined(_WIN32)
  11159. constexpr bool use_mmap = true;
  11160. #else
  11161. constexpr bool use_mmap = false;
  11162. #endif
  11163. llama_model_kv_override * kv_overrides = nullptr;
  11164. if (params->kv_overrides) {
  11165. auto v = (std::vector<llama_model_kv_override>*)params->kv_overrides;
  11166. kv_overrides = v->data();
  11167. }
  11168. llama_model_loader ml(fname_inp, use_mmap, kv_overrides);
  11169. ml.init_mappings(false); // no prefetching
  11170. llama_model model;
  11171. llm_load_arch(ml, model);
  11172. llm_load_hparams(ml, model);
  11173. struct quantize_state_internal qs(model, params);
  11174. if (params->only_copy) {
  11175. ftype = model.ftype;
  11176. }
  11177. const std::unordered_map<std::string, std::vector<float>> * imatrix_data = nullptr;
  11178. if (params->imatrix) {
  11179. imatrix_data = static_cast<const std::unordered_map<std::string, std::vector<float>>*>(params->imatrix);
  11180. if (imatrix_data) {
  11181. LLAMA_LOG_INFO("================================ Have weights data with %d entries\n",int(imatrix_data->size()));
  11182. qs.has_imatrix = true;
  11183. }
  11184. }
  11185. const size_t align = GGUF_DEFAULT_ALIGNMENT;
  11186. struct gguf_context * ctx_out = gguf_init_empty();
  11187. // copy the KV pairs from the input file
  11188. gguf_set_kv (ctx_out, ml.meta);
  11189. gguf_set_val_u32(ctx_out, "general.quantization_version", GGML_QNT_VERSION);
  11190. gguf_set_val_u32(ctx_out, "general.file_type", ftype);
  11191. if (params->kv_overrides) {
  11192. const std::vector<llama_model_kv_override> & overrides = *(const std::vector<llama_model_kv_override> *)params->kv_overrides;
  11193. for (auto & o : overrides) {
  11194. if (o.key[0] == 0) break;
  11195. if (o.tag == LLAMA_KV_OVERRIDE_TYPE_FLOAT) {
  11196. gguf_set_val_f32(ctx_out, o.key, o.float_value);
  11197. } else if (o.tag == LLAMA_KV_OVERRIDE_TYPE_INT) {
  11198. gguf_set_val_i32(ctx_out, o.key, o.int_value);
  11199. } else if (o.tag == LLAMA_KV_OVERRIDE_TYPE_BOOL) {
  11200. gguf_set_val_bool(ctx_out, o.key, o.bool_value);
  11201. } else {
  11202. LLAMA_LOG_WARN("%s: unknown KV override type for key %s\n", __func__, o.key);
  11203. }
  11204. }
  11205. }
  11206. for (int i = 0; i < ml.n_tensors; ++i) {
  11207. const struct ggml_tensor * meta = ml.get_tensor_meta(i);
  11208. const std::string name = ggml_get_name(meta);
  11209. // TODO: avoid hardcoded tensor names - use the TN_* constants
  11210. if (name.find("attn_v.weight") != std::string::npos ||
  11211. name.find("attn_qkv.weight") != std::string::npos) {
  11212. ++qs.n_attention_wv;
  11213. } else if (name == LLM_TN(model.arch)(LLM_TENSOR_OUTPUT, "weight")) {
  11214. qs.has_output = true;
  11215. }
  11216. }
  11217. qs.n_ffn_down = qs.n_ffn_gate = qs.n_ffn_up = (int)model.hparams.n_layer;
  11218. // sanity checks
  11219. //
  11220. // - qs.n_attention_wv == 0 for Mamba models
  11221. // - qs.n_attention_wv == model.hparams.n_layer for Transformer models
  11222. //
  11223. GGML_ASSERT((qs.n_attention_wv == 0 || qs.n_attention_wv == (int)model.hparams.n_layer) && "n_attention_wv is unexpected");
  11224. size_t total_size_org = 0;
  11225. size_t total_size_new = 0;
  11226. std::vector<std::thread> workers;
  11227. workers.reserve(nthread);
  11228. int idx = 0;
  11229. std::vector<no_init<uint8_t>> read_data;
  11230. std::vector<no_init<uint8_t>> work;
  11231. std::vector<no_init<float>> f32_conv_buf;
  11232. // populate the original tensors so we get an initial meta data
  11233. for (int i = 0; i < ml.n_tensors; ++i) {
  11234. const struct ggml_tensor * meta = ml.get_tensor_meta(i);
  11235. gguf_add_tensor(ctx_out, meta);
  11236. }
  11237. std::ofstream fout(fname_out, std::ios::binary);
  11238. fout.exceptions(std::ofstream::failbit); // fail fast on write errors
  11239. const size_t meta_size = gguf_get_meta_size(ctx_out);
  11240. LLAMA_LOG_INFO("%s: meta size = %zu bytes\n", __func__, meta_size);
  11241. // placeholder for the meta data
  11242. ::zeros(fout, meta_size);
  11243. const auto tn = LLM_TN(model.arch);
  11244. for (int i = 0; i < ml.n_tensors; ++i) {
  11245. struct ggml_tensor * tensor = ml.get_tensor_meta(i);
  11246. const std::string name = ggml_get_name(tensor);
  11247. if (!ml.use_mmap) {
  11248. if (read_data.size() < ggml_nbytes(tensor)) {
  11249. read_data.resize(ggml_nbytes(tensor));
  11250. }
  11251. tensor->data = read_data.data();
  11252. }
  11253. ml.load_data_for(tensor);
  11254. LLAMA_LOG_INFO("[%4d/%4d] %36s - [%s], type = %6s, ",
  11255. ++idx, ml.n_tensors,
  11256. ggml_get_name(tensor),
  11257. llama_format_tensor_shape(tensor).c_str(),
  11258. ggml_type_name(tensor->type));
  11259. // This used to be a regex, but <regex> has an extreme cost to compile times.
  11260. bool quantize = name.rfind("weight") == name.size() - 6; // ends with 'weight'?
  11261. // quantize only 2D and 3D tensors (experts)
  11262. quantize &= (ggml_n_dims(tensor) >= 2);
  11263. // do not quantize norm tensors
  11264. quantize &= name.find("_norm.weight") == std::string::npos;
  11265. quantize &= params->quantize_output_tensor || name != "output.weight";
  11266. quantize &= !params->only_copy;
  11267. // do not quantize expert gating tensors
  11268. // NOTE: can't use LLM_TN here because the layer number is not known
  11269. quantize &= name.find("ffn_gate_inp.weight") == std::string::npos;
  11270. // do not quantize positional embeddings and token types (BERT)
  11271. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_POS_EMBD, "weight");
  11272. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_TOKEN_TYPES, "weight");
  11273. // do not quantize Mamba's small yet 2D weights
  11274. // NOTE: can't use LLM_TN here because the layer number is not known
  11275. quantize &= name.find("ssm_conv1d.weight") == std::string::npos;
  11276. quantize &= name.find("ssm_x.weight") == std::string::npos;
  11277. quantize &= name.find("ssm_dt.weight") == std::string::npos;
  11278. enum ggml_type new_type;
  11279. void * new_data;
  11280. size_t new_size;
  11281. if (quantize) {
  11282. new_type = default_type;
  11283. // get more optimal quantization type based on the tensor shape, layer, etc.
  11284. if (!params->pure && ggml_is_quantized(default_type)) {
  11285. new_type = llama_tensor_get_type(qs, new_type, tensor, ftype);
  11286. }
  11287. if (params->token_embedding_type < GGML_TYPE_COUNT && strcmp(tensor->name, "token_embd.weight") == 0) {
  11288. new_type = params->token_embedding_type;
  11289. }
  11290. if (params->output_tensor_type < GGML_TYPE_COUNT && strcmp(tensor->name, "output.weight") == 0) {
  11291. new_type = params->output_tensor_type;
  11292. }
  11293. // If we've decided to quantize to the same type the tensor is already
  11294. // in then there's nothing to do.
  11295. quantize = tensor->type != new_type;
  11296. }
  11297. if (!quantize) {
  11298. new_type = tensor->type;
  11299. new_data = tensor->data;
  11300. new_size = ggml_nbytes(tensor);
  11301. LLAMA_LOG_INFO("size = %8.3f MB\n", ggml_nbytes(tensor)/1024.0/1024.0);
  11302. } else {
  11303. const int64_t nelements = ggml_nelements(tensor);
  11304. const float * imatrix = nullptr;
  11305. if (imatrix_data) {
  11306. auto it = imatrix_data->find(tensor->name);
  11307. if (it == imatrix_data->end()) {
  11308. LLAMA_LOG_INFO("\n====== %s: did not find weights for %s\n", __func__, tensor->name);
  11309. } else {
  11310. if (it->second.size() == (size_t)tensor->ne[0]*tensor->ne[2]) {
  11311. imatrix = it->second.data();
  11312. } else {
  11313. LLAMA_LOG_INFO("\n====== %s: imatrix size %d is different from tensor size %d for %s\n", __func__,
  11314. int(it->second.size()), int(tensor->ne[0]*tensor->ne[2]), tensor->name);
  11315. // this can happen when quantizing an old mixtral model with split tensors with a new incompatible imatrix
  11316. // this is a significant error and it may be good idea to abort the process if this happens,
  11317. // since many people will miss the error and not realize that most of the model is being quantized without an imatrix
  11318. // tok_embd should be ignored in this case, since it always causes this warning
  11319. if (name != tn(LLM_TENSOR_TOKEN_EMBD, "weight")) {
  11320. throw std::runtime_error(format("imatrix size %d is different from tensor size %d for %s",
  11321. int(it->second.size()), int(tensor->ne[0]*tensor->ne[2]), tensor->name));
  11322. }
  11323. }
  11324. }
  11325. }
  11326. if ((new_type == GGML_TYPE_IQ2_XXS ||
  11327. new_type == GGML_TYPE_IQ2_XS ||
  11328. new_type == GGML_TYPE_IQ2_S ||
  11329. new_type == GGML_TYPE_IQ1_S ||
  11330. (new_type == GGML_TYPE_IQ1_M && strcmp(tensor->name, "token_embd.weight") && strcmp(tensor->name, "output.weight")) ||
  11331. (new_type == GGML_TYPE_Q2_K && params->ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && strcmp(tensor->name, "token_embd.weight") != 0)) && !imatrix) {
  11332. LLAMA_LOG_ERROR("\n\n============================================================\n");
  11333. LLAMA_LOG_ERROR("Missing importance matrix for tensor %s in a very low-bit quantization\n", tensor->name);
  11334. LLAMA_LOG_ERROR("The result will be garbage, so bailing out\n");
  11335. LLAMA_LOG_ERROR("============================================================\n\n");
  11336. throw std::runtime_error(format("Missing importance matrix for tensor %s in a very low-bit quantization", tensor->name));
  11337. }
  11338. float * f32_data;
  11339. if (tensor->type == GGML_TYPE_F32) {
  11340. f32_data = (float *) tensor->data;
  11341. } else if (ggml_is_quantized(tensor->type) && !params->allow_requantize) {
  11342. throw std::runtime_error(format("requantizing from type %s is disabled", ggml_type_name(tensor->type)));
  11343. } else {
  11344. llama_tensor_dequantize_internal(tensor, f32_conv_buf, workers, nelements, nthread);
  11345. f32_data = (float *) f32_conv_buf.data();
  11346. }
  11347. LLAMA_LOG_INFO("converting to %s .. ", ggml_type_name(new_type));
  11348. fflush(stdout);
  11349. if (work.size() < (size_t)nelements * 4) {
  11350. work.resize(nelements * 4); // upper bound on size
  11351. }
  11352. new_data = work.data();
  11353. const int64_t n_per_row = tensor->ne[0];
  11354. const int64_t nrows = tensor->ne[1];
  11355. static const int64_t min_chunk_size = 32 * 512;
  11356. 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);
  11357. const int64_t nelements_matrix = tensor->ne[0] * tensor->ne[1];
  11358. const int64_t nchunk = (nelements_matrix + chunk_size - 1)/chunk_size;
  11359. const int64_t nthread_use = nthread > 1 ? std::max((int64_t)1, std::min((int64_t)nthread, nchunk)) : 1;
  11360. // quantize each expert separately since they have different importance matrices
  11361. new_size = 0;
  11362. for (int64_t i03 = 0; i03 < tensor->ne[2]; ++i03) {
  11363. const float * f32_data_03 = f32_data + i03 * nelements_matrix;
  11364. void * new_data_03 = (char *)new_data + ggml_row_size(new_type, n_per_row) * i03 * nrows;
  11365. const float * imatrix_03 = imatrix ? imatrix + i03 * n_per_row : nullptr;
  11366. 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);
  11367. }
  11368. LLAMA_LOG_INFO("size = %8.2f MiB -> %8.2f MiB\n", ggml_nbytes(tensor)/1024.0/1024.0, new_size/1024.0/1024.0);
  11369. }
  11370. total_size_org += ggml_nbytes(tensor);
  11371. total_size_new += new_size;
  11372. // update the gguf meta data as we go
  11373. gguf_set_tensor_type(ctx_out, name.c_str(), new_type);
  11374. gguf_set_tensor_data(ctx_out, name.c_str(), new_data, new_size);
  11375. // write tensor data + padding
  11376. fout.write((const char *) new_data, new_size);
  11377. zeros(fout, GGML_PAD(new_size, align) - new_size);
  11378. }
  11379. // go back to beginning of file and write the updated meta data
  11380. {
  11381. fout.seekp(0);
  11382. std::vector<uint8_t> data(gguf_get_meta_size(ctx_out));
  11383. gguf_get_meta_data(ctx_out, data.data());
  11384. fout.write((const char *) data.data(), data.size());
  11385. }
  11386. fout.close();
  11387. gguf_free(ctx_out);
  11388. LLAMA_LOG_INFO("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  11389. LLAMA_LOG_INFO("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  11390. if (qs.n_fallback > 0) {
  11391. LLAMA_LOG_WARN("%s: WARNING: %d of %d tensor(s) required fallback quantization\n",
  11392. __func__, qs.n_fallback, qs.n_k_quantized + qs.n_fallback);
  11393. }
  11394. }
  11395. static int llama_apply_lora_from_file_internal(
  11396. const struct llama_model & model, const char * path_lora, float scale, const char * path_base_model, int n_threads
  11397. ) {
  11398. LLAMA_LOG_INFO("%s: applying lora adapter from '%s' - please wait ...\n", __func__, path_lora);
  11399. const int64_t t_start_lora_us = ggml_time_us();
  11400. llama_file fin(path_lora, "rb");
  11401. // verify magic and version
  11402. {
  11403. uint32_t magic = fin.read_u32();
  11404. if (magic != LLAMA_FILE_MAGIC_GGLA) {
  11405. LLAMA_LOG_ERROR("%s: bad file magic\n", __func__);
  11406. return 1;
  11407. }
  11408. uint32_t format_version = fin.read_u32();
  11409. if (format_version != 1) {
  11410. LLAMA_LOG_ERROR("%s: unsupported file version\n", __func__ );
  11411. return 1;
  11412. }
  11413. }
  11414. int32_t lora_r = fin.read_u32();
  11415. int32_t lora_alpha = fin.read_u32();
  11416. float scaling = scale * (float)lora_alpha / (float)lora_r;
  11417. LLAMA_LOG_INFO("%s: r = %d, alpha = %d, scaling = %.2f\n", __func__, lora_r, lora_alpha, scaling);
  11418. // load base model
  11419. std::unique_ptr<llama_model_loader> ml;
  11420. if (path_base_model) {
  11421. LLAMA_LOG_INFO("%s: loading base model from '%s'\n", __func__, path_base_model);
  11422. ml.reset(new llama_model_loader(path_base_model, /*use_mmap*/ true, /*kv_overrides*/ nullptr));
  11423. ml->init_mappings(/*prefetch*/ false); // no prefetching
  11424. }
  11425. struct tensor_meta {
  11426. std::string name;
  11427. ggml_type type;
  11428. int32_t ne[2];
  11429. size_t offset;
  11430. };
  11431. std::map<std::string, tensor_meta> tensor_meta_map;
  11432. // load all tensor meta
  11433. while (true) {
  11434. if (fin.tell() == fin.size) {
  11435. // eof
  11436. break;
  11437. }
  11438. int32_t n_dims;
  11439. int32_t name_len;
  11440. int32_t ftype;
  11441. fin.read_raw(&n_dims, sizeof(n_dims));
  11442. fin.read_raw(&name_len, sizeof(name_len));
  11443. fin.read_raw(&ftype, sizeof(ftype));
  11444. if (n_dims != 1 && n_dims != 2) {
  11445. LLAMA_LOG_ERROR("%s: unsupported tensor dimension %d\n", __func__, n_dims);
  11446. return 1;
  11447. }
  11448. int32_t ne[2] = { 1, 1 };
  11449. for (int i = 0; i < n_dims; ++i) {
  11450. fin.read_raw(&ne[i], sizeof(ne[i]));
  11451. }
  11452. std::string name;
  11453. {
  11454. GGML_ASSERT(name_len < GGML_MAX_NAME);
  11455. char buf[GGML_MAX_NAME];
  11456. fin.read_raw(buf, name_len);
  11457. name = std::string(buf, name_len);
  11458. }
  11459. // check for lora suffix
  11460. std::string lora_suffix;
  11461. if (name.length() > 6) {
  11462. lora_suffix = name.substr(name.length() - 6);
  11463. }
  11464. if (lora_suffix != ".loraA" && lora_suffix != ".loraB") {
  11465. LLAMA_LOG_ERROR("%s: error: '%s' is not a lora tensor\n", __func__, name.c_str());
  11466. return 1;
  11467. }
  11468. // tensor type
  11469. ggml_type wtype;
  11470. switch (ftype) {
  11471. case 0: wtype = GGML_TYPE_F32; break;
  11472. case 1: wtype = GGML_TYPE_F16; break;
  11473. default:
  11474. {
  11475. LLAMA_LOG_ERROR("%s: invalid tensor data type '%d'\n",
  11476. __func__, ftype);
  11477. return 1;
  11478. }
  11479. }
  11480. // data offset
  11481. size_t offset = fin.tell();
  11482. offset = (offset + 31) & -32;
  11483. // skip tensor data
  11484. fin.seek(offset + ggml_row_size(wtype, ne[0]) * ne[1], SEEK_SET);
  11485. tensor_meta_map.emplace(name, tensor_meta{ name, wtype, { ne[0], ne[1] }, offset });
  11486. }
  11487. bool warned = false;
  11488. int n_tensors = 0;
  11489. // apply
  11490. ggml_backend_t backend_cpu = ggml_backend_cpu_init();
  11491. if (backend_cpu == nullptr) {
  11492. LLAMA_LOG_ERROR("%s: error: failed to initialize cpu backend\n", __func__);
  11493. return 1;
  11494. }
  11495. ggml_backend_cpu_set_n_threads(backend_cpu, n_threads);
  11496. std::vector<no_init<uint8_t>> read_buf;
  11497. for (const auto & it : model.tensors_by_name) {
  11498. const std::string & base_name = it.first;
  11499. ggml_tensor * model_t = it.second;
  11500. if (tensor_meta_map.find(base_name + ".loraA") == tensor_meta_map.end() ||
  11501. tensor_meta_map.find(base_name + ".loraB") == tensor_meta_map.end()) {
  11502. continue;
  11503. }
  11504. tensor_meta & metaA = tensor_meta_map.at(base_name + ".loraA");
  11505. tensor_meta & metaB = tensor_meta_map.at(base_name + ".loraB");
  11506. ggml_init_params lora_init_params = {
  11507. /* .mem_size */ ggml_tensor_overhead()*128 + ggml_graph_overhead(),
  11508. /* .mem_buffer */ nullptr,
  11509. /* .no_alloc */ true,
  11510. };
  11511. ggml_context * lora_ctx = ggml_init(lora_init_params);
  11512. if (lora_ctx == nullptr) {
  11513. LLAMA_LOG_ERROR("%s: error: failed to initialize lora context\n", __func__);
  11514. ggml_backend_free(backend_cpu);
  11515. return 1;
  11516. }
  11517. // create tensors
  11518. ggml_tensor * loraA = ggml_new_tensor_2d(lora_ctx, metaA.type, metaA.ne[0], metaA.ne[1]);
  11519. ggml_tensor * loraB = ggml_new_tensor_2d(lora_ctx, metaB.type, metaB.ne[0], metaB.ne[1]);
  11520. ggml_set_name(loraA, metaA.name.c_str());
  11521. ggml_set_name(loraB, metaB.name.c_str());
  11522. ggml_tensor * base_t;
  11523. if (ml) {
  11524. if (!ml->get_tensor_meta(base_name.c_str())) {
  11525. LLAMA_LOG_ERROR("%s: error: tensor '%s' not found in base model\n", __func__, base_name.c_str());
  11526. return 1;
  11527. }
  11528. base_t = ggml_dup_tensor(lora_ctx, ml->get_tensor_meta(base_name.c_str()));
  11529. } else {
  11530. base_t = ggml_dup_tensor(lora_ctx, model_t);
  11531. }
  11532. ggml_set_name(base_t, base_name.c_str());
  11533. // allocate in backend buffer
  11534. ggml_backend_buffer_t lora_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  11535. if (lora_buf == nullptr) {
  11536. LLAMA_LOG_ERROR("%s: error: failed to allocate lora tensors\n", __func__);
  11537. return 1;
  11538. }
  11539. // load tensor data
  11540. auto load_tensor = [&read_buf, &fin](const tensor_meta & tensor_meta, ggml_tensor * tensor) {
  11541. read_buf.resize(ggml_nbytes(tensor));
  11542. fin.seek(tensor_meta.offset, SEEK_SET);
  11543. fin.read_raw(read_buf.data(), ggml_nbytes(tensor));
  11544. ggml_backend_tensor_set(tensor, read_buf.data(), 0, read_buf.size());
  11545. };
  11546. load_tensor(metaA, loraA);
  11547. load_tensor(metaB, loraB);
  11548. // load base model tensor data
  11549. if (ml) {
  11550. ml->load_data_for(base_t);
  11551. } else {
  11552. ggml_backend_tensor_copy(model_t, base_t);
  11553. }
  11554. if (ggml_is_quantized(base_t->type) && !warned) {
  11555. LLAMA_LOG_WARN("%s: warning: using a lora adapter with a quantized model may result in poor quality, "
  11556. "use a f16 or f32 base model with --lora-base\n", __func__);
  11557. warned = true;
  11558. }
  11559. if (base_t->ne[0] != loraA->ne[1] || base_t->ne[1] != loraB->ne[1]) {
  11560. LLAMA_LOG_ERROR("%s: incompatible tensor dimensions (%" PRId64 " and %" PRId64 ");"
  11561. " are you sure that this adapter is for this model?\n", __func__, base_t->ne[0], loraA->ne[1]);
  11562. ggml_free(lora_ctx);
  11563. ggml_backend_buffer_free(lora_buf);
  11564. ggml_backend_free(backend_cpu);
  11565. return 1;
  11566. }
  11567. auto build_lora_graph = [&]() {
  11568. // w = w + BA*s
  11569. ggml_tensor * BA = ggml_mul_mat(lora_ctx, loraA, loraB);
  11570. ggml_set_name(BA, "BA");
  11571. if (scaling != 1.0f) {
  11572. BA = ggml_scale(lora_ctx, BA, scaling);
  11573. ggml_set_name(BA, "BA_scaled");
  11574. }
  11575. ggml_tensor * r;
  11576. r = ggml_add_inplace(lora_ctx, base_t, BA);
  11577. ggml_set_name(r, "r_add");
  11578. if (base_t->type != model_t->type) {
  11579. // convert the result to the model type
  11580. r = ggml_cast(lora_ctx, r, model_t->type);
  11581. ggml_set_name(r, "r_cast");
  11582. }
  11583. return r;
  11584. };
  11585. ggml_cgraph * gf = ggml_new_graph(lora_ctx);
  11586. ggml_tensor * r = build_lora_graph();
  11587. ggml_build_forward_expand(gf, r);
  11588. ggml_backend_buffer_t graph_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  11589. if (graph_buf == nullptr) {
  11590. LLAMA_LOG_ERROR("%s: error: failed to allocate graph tensors\n", __func__);
  11591. ggml_free(lora_ctx);
  11592. ggml_backend_buffer_free(lora_buf);
  11593. ggml_backend_free(backend_cpu);
  11594. return 1;
  11595. }
  11596. ggml_backend_graph_compute(backend_cpu, gf);
  11597. ggml_backend_tensor_set(model_t, r->data, 0, ggml_nbytes(r));
  11598. #if 0
  11599. // TODO: use scheduler with fallback to CPU for less copies between CPU and GPU
  11600. //ggml_backend_sched_t sched = ggml_backend_sched_new(backends.data(), backends.size(), GGML_DEFAULT_GRAPH_SIZE);
  11601. // sched compute
  11602. ggml_build_forward_expand(gf, build_graph());
  11603. ggml_backend_sched_init_measure(sched, gf);
  11604. // create the graph again, since the previous one was destroyed by the measure
  11605. ggml_graph_clear(gf);
  11606. ggml_build_forward_expand(gf, build_graph());
  11607. ggml_backend_sched_graph_compute(sched, gf);
  11608. ggml_backend_sched_free(sched);
  11609. #endif
  11610. ggml_backend_buffer_free(lora_buf);
  11611. ggml_backend_buffer_free(graph_buf);
  11612. ggml_free(lora_ctx);
  11613. n_tensors++;
  11614. if (n_tensors % 4 == 0) {
  11615. LLAMA_LOG_INFO(".");
  11616. }
  11617. }
  11618. ggml_backend_free(backend_cpu);
  11619. const int64_t t_lora_us = ggml_time_us() - t_start_lora_us;
  11620. LLAMA_LOG_INFO(" done (%.2f ms)\n", t_lora_us / 1000.0);
  11621. return 0;
  11622. }
  11623. //
  11624. // interface implementation
  11625. //
  11626. struct llama_model_params llama_model_default_params() {
  11627. struct llama_model_params result = {
  11628. /*.n_gpu_layers =*/ 0,
  11629. /*.split_mode =*/ LLAMA_SPLIT_MODE_LAYER,
  11630. /*.main_gpu =*/ 0,
  11631. /*.tensor_split =*/ nullptr,
  11632. /*.progress_callback =*/ nullptr,
  11633. /*.progress_callback_user_data =*/ nullptr,
  11634. /*.kv_overrides =*/ nullptr,
  11635. /*.vocab_only =*/ false,
  11636. /*.use_mmap =*/ true,
  11637. /*.use_mlock =*/ false,
  11638. };
  11639. #ifdef GGML_USE_METAL
  11640. // note: we usually have plenty of VRAM, so by default offload all layers to the GPU
  11641. result.n_gpu_layers = 999;
  11642. #endif
  11643. return result;
  11644. }
  11645. struct llama_context_params llama_context_default_params() {
  11646. struct llama_context_params result = {
  11647. /*.seed =*/ LLAMA_DEFAULT_SEED,
  11648. /*.n_ctx =*/ 512,
  11649. /*.n_batch =*/ 2048,
  11650. /*.n_ubatch =*/ 512,
  11651. /*.n_seq_max =*/ 1,
  11652. /*.n_threads =*/ GGML_DEFAULT_N_THREADS, // TODO: better default
  11653. /*.n_threads_batch =*/ GGML_DEFAULT_N_THREADS,
  11654. /*.rope_scaling_type =*/ LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED,
  11655. /*.pooling_type =*/ LLAMA_POOLING_TYPE_UNSPECIFIED,
  11656. /*.rope_freq_base =*/ 0.0f,
  11657. /*.rope_freq_scale =*/ 0.0f,
  11658. /*.yarn_ext_factor =*/ -1.0f,
  11659. /*.yarn_attn_factor =*/ 1.0f,
  11660. /*.yarn_beta_fast =*/ 32.0f,
  11661. /*.yarn_beta_slow =*/ 1.0f,
  11662. /*.yarn_orig_ctx =*/ 0,
  11663. /*.defrag_thold =*/ -1.0f,
  11664. /*.cb_eval =*/ nullptr,
  11665. /*.cb_eval_user_data =*/ nullptr,
  11666. /*.type_k =*/ GGML_TYPE_F16,
  11667. /*.type_v =*/ GGML_TYPE_F16,
  11668. /*.logits_all =*/ false,
  11669. /*.embeddings =*/ false,
  11670. /*.offload_kqv =*/ true,
  11671. /*.abort_callback =*/ nullptr,
  11672. /*.abort_callback_data =*/ nullptr,
  11673. };
  11674. return result;
  11675. }
  11676. struct llama_model_quantize_params llama_model_quantize_default_params() {
  11677. struct llama_model_quantize_params result = {
  11678. /*.nthread =*/ 0,
  11679. /*.ftype =*/ LLAMA_FTYPE_MOSTLY_Q5_1,
  11680. /*.output_tensor_type =*/ GGML_TYPE_COUNT,
  11681. /*.token_embedding_type =*/ GGML_TYPE_COUNT,
  11682. /*.allow_requantize =*/ false,
  11683. /*.quantize_output_tensor =*/ true,
  11684. /*.only_copy =*/ false,
  11685. /*.pure =*/ false,
  11686. /*.imatrix =*/ nullptr,
  11687. /*.kv_overrides =*/ nullptr,
  11688. };
  11689. return result;
  11690. }
  11691. size_t llama_max_devices(void) {
  11692. #if defined(GGML_USE_METAL)
  11693. return 1;
  11694. #elif defined(GGML_USE_CUDA)
  11695. return GGML_CUDA_MAX_DEVICES;
  11696. #elif defined(GGML_USE_SYCL)
  11697. return GGML_SYCL_MAX_DEVICES;
  11698. #elif defined(GGML_USE_VULKAN)
  11699. return GGML_VK_MAX_DEVICES;
  11700. #else
  11701. return 1;
  11702. #endif
  11703. }
  11704. bool llama_supports_mmap(void) {
  11705. return llama_mmap::SUPPORTED;
  11706. }
  11707. bool llama_supports_mlock(void) {
  11708. return llama_mlock::SUPPORTED;
  11709. }
  11710. bool llama_supports_gpu_offload(void) {
  11711. #if defined(GGML_USE_CUDA) || defined(GGML_USE_CLBLAST) || defined(GGML_USE_METAL) || defined(GGML_USE_VULKAN) || \
  11712. defined(GGML_USE_SYCL) || defined(GGML_USE_KOMPUTE)
  11713. // Defined when llama.cpp is compiled with support for offloading model layers to GPU.
  11714. return true;
  11715. #else
  11716. return false;
  11717. #endif
  11718. }
  11719. void llama_backend_init(void) {
  11720. ggml_time_init();
  11721. // needed to initialize f16 tables
  11722. {
  11723. struct ggml_init_params params = { 0, NULL, false };
  11724. struct ggml_context * ctx = ggml_init(params);
  11725. ggml_free(ctx);
  11726. }
  11727. #ifdef GGML_USE_MPI
  11728. ggml_mpi_backend_init();
  11729. #endif
  11730. }
  11731. void llama_numa_init(enum ggml_numa_strategy numa) {
  11732. if (numa != GGML_NUMA_STRATEGY_DISABLED) {
  11733. ggml_numa_init(numa);
  11734. }
  11735. }
  11736. void llama_backend_free(void) {
  11737. #ifdef GGML_USE_MPI
  11738. ggml_mpi_backend_free();
  11739. #endif
  11740. ggml_quantize_free();
  11741. }
  11742. int64_t llama_time_us(void) {
  11743. return ggml_time_us();
  11744. }
  11745. struct llama_model * llama_load_model_from_file(
  11746. const char * path_model,
  11747. struct llama_model_params params) {
  11748. ggml_time_init();
  11749. llama_model * model = new llama_model;
  11750. unsigned cur_percentage = 0;
  11751. if (params.progress_callback == NULL) {
  11752. params.progress_callback_user_data = &cur_percentage;
  11753. params.progress_callback = [](float progress, void * ctx) {
  11754. unsigned * cur_percentage_p = (unsigned *) ctx;
  11755. unsigned percentage = (unsigned) (100 * progress);
  11756. while (percentage > *cur_percentage_p) {
  11757. *cur_percentage_p = percentage;
  11758. LLAMA_LOG_INFO(".");
  11759. if (percentage >= 100) {
  11760. LLAMA_LOG_INFO("\n");
  11761. }
  11762. }
  11763. return true;
  11764. };
  11765. }
  11766. int status = llama_model_load(path_model, *model, params);
  11767. GGML_ASSERT(status <= 0);
  11768. if (status < 0) {
  11769. if (status == -1) {
  11770. LLAMA_LOG_ERROR("%s: failed to load model\n", __func__);
  11771. } else if (status == -2) {
  11772. LLAMA_LOG_INFO("%s: cancelled model load\n", __func__);
  11773. }
  11774. delete model;
  11775. return nullptr;
  11776. }
  11777. return model;
  11778. }
  11779. void llama_free_model(struct llama_model * model) {
  11780. delete model;
  11781. }
  11782. struct llama_context * llama_new_context_with_model(
  11783. struct llama_model * model,
  11784. struct llama_context_params params) {
  11785. if (!model) {
  11786. LLAMA_LOG_ERROR("%s: model cannot be NULL\n", __func__);
  11787. return nullptr;
  11788. }
  11789. if (params.n_batch == 0 && params.n_ubatch == 0) {
  11790. LLAMA_LOG_ERROR("%s: n_batch and n_ubatch cannot both be zero\n", __func__);
  11791. return nullptr;
  11792. }
  11793. if (params.n_ctx == 0 && model->hparams.n_ctx_train == 0) {
  11794. LLAMA_LOG_ERROR("%s: n_ctx and model->hparams.n_ctx_train cannot both be zero\n", __func__);
  11795. return nullptr;
  11796. }
  11797. llama_context * ctx = new llama_context(*model);
  11798. const auto & hparams = model->hparams;
  11799. auto & cparams = ctx->cparams;
  11800. cparams.n_seq_max = std::max(1u, params.n_seq_max);
  11801. cparams.n_threads = params.n_threads;
  11802. cparams.n_threads_batch = params.n_threads_batch;
  11803. cparams.yarn_ext_factor = params.yarn_ext_factor;
  11804. cparams.yarn_attn_factor = params.yarn_attn_factor;
  11805. cparams.yarn_beta_fast = params.yarn_beta_fast;
  11806. cparams.yarn_beta_slow = params.yarn_beta_slow;
  11807. cparams.defrag_thold = params.defrag_thold;
  11808. cparams.embeddings = params.embeddings;
  11809. cparams.offload_kqv = params.offload_kqv;
  11810. cparams.pooling_type = params.pooling_type;
  11811. cparams.n_ctx = params.n_ctx == 0 ? hparams.n_ctx_train : params.n_ctx;
  11812. cparams.rope_freq_base = params.rope_freq_base == 0.0f ? hparams.rope_freq_base_train : params.rope_freq_base;
  11813. cparams.rope_freq_scale = params.rope_freq_scale == 0.0f ? hparams.rope_freq_scale_train : params.rope_freq_scale;
  11814. // this is necessary due to kv_self.n being padded later during inference
  11815. cparams.n_ctx = GGML_PAD(cparams.n_ctx, 32);
  11816. // with causal attention, the batch size is limited by the context size
  11817. cparams.n_batch = hparams.causal_attn ? std::min(cparams.n_ctx, params.n_batch) : params.n_batch;
  11818. cparams.n_ubatch = std::min(cparams.n_batch, params.n_ubatch == 0 ? params.n_batch : params.n_ubatch);
  11819. cparams.n_yarn_orig_ctx = params.yarn_orig_ctx != 0 ? params.yarn_orig_ctx :
  11820. hparams.n_yarn_orig_ctx != 0 ? hparams.n_yarn_orig_ctx :
  11821. hparams.n_ctx_train;
  11822. cparams.cb_eval = params.cb_eval;
  11823. cparams.cb_eval_user_data = params.cb_eval_user_data;
  11824. auto rope_scaling_type = params.rope_scaling_type;
  11825. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED) {
  11826. rope_scaling_type = hparams.rope_scaling_type_train;
  11827. }
  11828. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_NONE) {
  11829. cparams.rope_freq_scale = 1.0f; // never scale if scaling type is none
  11830. }
  11831. if (cparams.yarn_ext_factor < 0.0f) { // negative indicates 'not set'
  11832. cparams.yarn_ext_factor = rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_YARN ? 1.0f : 0.0f;
  11833. }
  11834. cparams.causal_attn = hparams.causal_attn;
  11835. if (cparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  11836. if (hparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  11837. cparams.pooling_type = LLAMA_POOLING_TYPE_NONE;
  11838. } else {
  11839. cparams.pooling_type = hparams.pooling_type;
  11840. }
  11841. }
  11842. if (params.seed == LLAMA_DEFAULT_SEED) {
  11843. params.seed = time(NULL);
  11844. }
  11845. LLAMA_LOG_INFO("%s: n_ctx = %u\n", __func__, cparams.n_ctx);
  11846. LLAMA_LOG_INFO("%s: n_batch = %u\n", __func__, cparams.n_batch);
  11847. LLAMA_LOG_INFO("%s: n_ubatch = %u\n", __func__, cparams.n_ubatch);
  11848. LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, cparams.rope_freq_base);
  11849. LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, cparams.rope_freq_scale);
  11850. ctx->abort_callback = params.abort_callback;
  11851. ctx->abort_callback_data = params.abort_callback_data;
  11852. ctx->rng = std::mt19937(params.seed);
  11853. ctx->logits_all = params.logits_all;
  11854. uint32_t kv_size = cparams.n_ctx;
  11855. ggml_type type_k = params.type_k;
  11856. ggml_type type_v = params.type_v;
  11857. // Mamba only needs a constant number of KV cache cells per sequence
  11858. if (model->arch == LLM_ARCH_MAMBA) {
  11859. // Mamba needs at least as many KV cells as there are sequences kept at any time
  11860. kv_size = std::max((uint32_t) 1, params.n_seq_max);
  11861. // it's probably best to keep as much precision as possible for the states
  11862. type_k = GGML_TYPE_F32; // required by ggml_ssm_conv for Mamba's conv_states
  11863. type_v = GGML_TYPE_F32; // required by ggml_ssm_scan for Mamba's ssm_states
  11864. }
  11865. GGML_ASSERT(hparams.n_embd_head_k % ggml_blck_size(type_k) == 0);
  11866. GGML_ASSERT(hparams.n_embd_head_v % ggml_blck_size(type_v) == 0);
  11867. if (!hparams.vocab_only) {
  11868. // initialize backends
  11869. #ifdef GGML_USE_METAL
  11870. if (model->n_gpu_layers > 0) {
  11871. ctx->backend_metal = ggml_backend_metal_init();
  11872. if (ctx->backend_metal == nullptr) {
  11873. LLAMA_LOG_ERROR("%s: failed to initialize Metal backend\n", __func__);
  11874. llama_free(ctx);
  11875. return nullptr;
  11876. }
  11877. ctx->backends.push_back(ctx->backend_metal);
  11878. }
  11879. #elif defined(GGML_USE_CUDA)
  11880. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  11881. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  11882. ggml_backend_t backend = ggml_backend_cuda_init(model->main_gpu);
  11883. if (backend == nullptr) {
  11884. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, model->main_gpu);
  11885. llama_free(ctx);
  11886. return nullptr;
  11887. }
  11888. ctx->backends.push_back(backend);
  11889. } else {
  11890. // LLAMA_SPLIT_MODE_LAYER requires a backend for each GPU
  11891. for (int device = 0; device < ggml_backend_cuda_get_device_count(); ++device) {
  11892. ggml_backend_t backend = ggml_backend_cuda_init(device);
  11893. if (backend == nullptr) {
  11894. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, device);
  11895. llama_free(ctx);
  11896. return nullptr;
  11897. }
  11898. ctx->backends.push_back(backend);
  11899. }
  11900. }
  11901. #elif defined(GGML_USE_VULKAN)
  11902. if (model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  11903. LLAMA_LOG_ERROR("%s: Row split not supported. Failed to initialize Vulkan backend\n", __func__);
  11904. llama_free(ctx);
  11905. return nullptr;
  11906. }
  11907. if (model->split_mode == LLAMA_SPLIT_MODE_NONE) {
  11908. ggml_backend_t backend = ggml_backend_vk_init(0);
  11909. if (backend == nullptr) {
  11910. LLAMA_LOG_ERROR("%s: failed to initialize Vulkan backend\n", __func__);
  11911. llama_free(ctx);
  11912. return nullptr;
  11913. }
  11914. ctx->backends.push_back(backend);
  11915. } else {
  11916. for (int device = 0; device < ggml_backend_vk_get_device_count(); ++device) {
  11917. ggml_backend_t backend = ggml_backend_vk_init(device);
  11918. if (backend == nullptr) {
  11919. LLAMA_LOG_ERROR("%s: failed to initialize Vulkan%d backend\n", __func__, device);
  11920. llama_free(ctx);
  11921. return nullptr;
  11922. }
  11923. ctx->backends.push_back(backend);
  11924. }
  11925. }
  11926. #elif defined(GGML_USE_SYCL)
  11927. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  11928. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  11929. ggml_backend_t backend = ggml_backend_sycl_init(model->main_gpu);
  11930. if (backend == nullptr) {
  11931. int main_gpu_id = ggml_backend_sycl_get_device_id(model->main_gpu);
  11932. LLAMA_LOG_ERROR("%s: failed to initialize SYCL%d (index %d) backend\n", __func__, main_gpu_id, model->main_gpu);
  11933. llama_free(ctx);
  11934. return nullptr;
  11935. }
  11936. ctx->backends.push_back(backend);
  11937. } else {
  11938. // LLAMA_SPLIT_LAYER requires a backend for each GPU
  11939. for (int i = 0; i < ggml_backend_sycl_get_device_count(); ++i) {
  11940. ggml_backend_t backend = ggml_backend_sycl_init(i);
  11941. if (backend == nullptr) {
  11942. int id_list[GGML_SYCL_MAX_DEVICES];
  11943. ggml_sycl_get_gpu_list(id_list, GGML_SYCL_MAX_DEVICES);
  11944. LLAMA_LOG_ERROR("%s: failed to initialize SYCL%d (index %d) backend\n", __func__, id_list[i], i);
  11945. llama_free(ctx);
  11946. return nullptr;
  11947. }
  11948. ctx->backends.push_back(backend);
  11949. }
  11950. }
  11951. #elif defined(GGML_USE_KOMPUTE)
  11952. if (model->n_gpu_layers > 0) {
  11953. auto * backend = ggml_backend_kompute_init(model->main_gpu);
  11954. if (backend == nullptr) {
  11955. LLAMA_LOG_ERROR("%s: failed to initialize Kompute backend\n", __func__);
  11956. llama_free(ctx);
  11957. return nullptr;
  11958. }
  11959. ctx->backends.push_back(backend);
  11960. }
  11961. #endif
  11962. ctx->backend_cpu = ggml_backend_cpu_init();
  11963. if (ctx->backend_cpu == nullptr) {
  11964. LLAMA_LOG_ERROR("%s: failed to initialize CPU backend\n", __func__);
  11965. llama_free(ctx);
  11966. return nullptr;
  11967. }
  11968. ctx->backends.push_back(ctx->backend_cpu);
  11969. if (!llama_kv_cache_init(ctx->kv_self, ctx->model, type_k, type_v, kv_size, cparams.offload_kqv)) {
  11970. LLAMA_LOG_ERROR("%s: llama_kv_cache_init() failed for self-attention cache\n", __func__);
  11971. llama_free(ctx);
  11972. return nullptr;
  11973. }
  11974. {
  11975. size_t memory_size_k = 0;
  11976. size_t memory_size_v = 0;
  11977. for (auto & k : ctx->kv_self.k_l) {
  11978. memory_size_k += ggml_nbytes(k);
  11979. }
  11980. for (auto & v : ctx->kv_self.v_l) {
  11981. memory_size_v += ggml_nbytes(v);
  11982. }
  11983. LLAMA_LOG_INFO("%s: KV self size = %7.2f MiB, K (%s): %7.2f MiB, V (%s): %7.2f MiB\n", __func__,
  11984. (float)(memory_size_k + memory_size_v) / (1024.0f * 1024.0f),
  11985. ggml_type_name(type_k), (float)memory_size_k / (1024.0f * 1024.0f),
  11986. ggml_type_name(type_v), (float)memory_size_v / (1024.0f * 1024.0f));
  11987. }
  11988. // graph outputs buffer
  11989. {
  11990. // resized during inference when a batch uses more outputs
  11991. if (llama_output_reserve(*ctx, params.n_seq_max) < params.n_seq_max) {
  11992. LLAMA_LOG_ERROR("%s: failed to reserve initial output buffer\n", __func__);
  11993. llama_free(ctx);
  11994. return nullptr;
  11995. }
  11996. LLAMA_LOG_INFO("%s: %10s output buffer size = %8.2f MiB\n", __func__,
  11997. ggml_backend_buffer_name(ctx->buf_output),
  11998. ggml_backend_buffer_get_size(ctx->buf_output) / 1024.0 / 1024.0);
  11999. }
  12000. // scheduler and compute buffers
  12001. {
  12002. // buffer types used for the compute buffer of each backend
  12003. std::vector<ggml_backend_buffer_type_t> backend_buft;
  12004. for (auto * backend : ctx->backends) {
  12005. if (ggml_backend_is_cpu(backend)) {
  12006. // use host buffers for the CPU backend compute buffer
  12007. backend_buft.push_back(llama_default_buffer_type_cpu(true));
  12008. } else {
  12009. backend_buft.push_back(ggml_backend_get_default_buffer_type(backend));
  12010. }
  12011. }
  12012. // buffer used to store the computation graph and the tensor meta data
  12013. ctx->buf_compute_meta.resize(ggml_tensor_overhead()*LLAMA_MAX_NODES + ggml_graph_overhead_custom(LLAMA_MAX_NODES, false));
  12014. // enabling pipeline parallelism in the scheduler increases memory usage, so it is only done when necessary
  12015. bool pipeline_parallel = llama_get_device_count() > 1 && model->n_gpu_layers > (int)model->hparams.n_layer && model->split_mode == LLAMA_SPLIT_MODE_LAYER;
  12016. #ifndef GGML_USE_CUDA
  12017. // pipeline parallelism requires support for async compute and events
  12018. // currently this is only implemented in the CUDA backend
  12019. pipeline_parallel = false;
  12020. #endif
  12021. ctx->sched = ggml_backend_sched_new(ctx->backends.data(), backend_buft.data(), ctx->backends.size(), LLAMA_MAX_NODES, pipeline_parallel);
  12022. if (pipeline_parallel) {
  12023. LLAMA_LOG_INFO("%s: pipeline parallelism enabled (n_copies=%d)\n", __func__, ggml_backend_sched_get_n_copies(ctx->sched));
  12024. }
  12025. // build worst-case graph
  12026. int n_tokens = (int)std::min(cparams.n_ctx, cparams.n_ubatch);
  12027. int n_past = cparams.n_ctx - n_tokens;
  12028. 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
  12029. ggml_cgraph * gf = llama_build_graph(*ctx, llama_batch_get_one(&token, n_tokens, n_past, 0), true);
  12030. // initialize scheduler with the worst-case graph
  12031. if (!ggml_backend_sched_reserve(ctx->sched, gf)) {
  12032. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  12033. llama_free(ctx);
  12034. return nullptr;
  12035. }
  12036. for (size_t i = 0; i < ctx->backends.size(); i++) {
  12037. ggml_backend_t backend = ctx->backends[i];
  12038. ggml_backend_buffer_type_t buft = backend_buft[i];
  12039. size_t size = ggml_backend_sched_get_buffer_size(ctx->sched, backend);
  12040. if (size > 1) {
  12041. LLAMA_LOG_INFO("%s: %10s compute buffer size = %8.2f MiB\n", __func__,
  12042. ggml_backend_buft_name(buft),
  12043. size / 1024.0 / 1024.0);
  12044. }
  12045. }
  12046. // note: the number of splits during measure is higher than during inference due to the kv shift
  12047. int n_splits = ggml_backend_sched_get_n_splits(ctx->sched);
  12048. LLAMA_LOG_INFO("%s: graph nodes = %d\n", __func__, gf->n_nodes);
  12049. LLAMA_LOG_INFO("%s: graph splits = %d\n", __func__, n_splits);
  12050. }
  12051. }
  12052. #ifdef GGML_USE_MPI
  12053. ctx->ctx_mpi = ggml_mpi_init();
  12054. if (ggml_mpi_rank(ctx->ctx_mpi) > 0) {
  12055. // Enter a blocking eval loop with dummy input, letting rank=0 drive the process
  12056. // TODO: needs fix after #3228
  12057. GGML_ASSERT(false && "not implemented");
  12058. //const std::vector<llama_token> tmp(ctx->model.hparams.n_ctx, llama_token_bos(ctx));
  12059. //while (!llama_eval(ctx, tmp.data(), tmp.size(), 0, 0)) {};
  12060. llama_backend_free();
  12061. exit(1);
  12062. }
  12063. #endif
  12064. return ctx;
  12065. }
  12066. void llama_free(struct llama_context * ctx) {
  12067. delete ctx;
  12068. }
  12069. const llama_model * llama_get_model(const struct llama_context * ctx) {
  12070. return &ctx->model;
  12071. }
  12072. uint32_t llama_n_ctx(const struct llama_context * ctx) {
  12073. return ctx->cparams.n_ctx;
  12074. }
  12075. uint32_t llama_n_batch(const struct llama_context * ctx) {
  12076. return ctx->cparams.n_batch;
  12077. }
  12078. uint32_t llama_n_ubatch(const struct llama_context * ctx) {
  12079. return ctx->cparams.n_ubatch;
  12080. }
  12081. uint32_t llama_n_seq_max(const struct llama_context * ctx) {
  12082. return ctx->kv_self.size;
  12083. }
  12084. enum llama_vocab_type llama_vocab_type(const struct llama_model * model) {
  12085. return model->vocab.type;
  12086. }
  12087. enum llama_rope_type llama_rope_type(const struct llama_model * model) {
  12088. switch (model->arch) {
  12089. // these models do not use RoPE
  12090. case LLM_ARCH_GPT2:
  12091. case LLM_ARCH_GPTJ:
  12092. case LLM_ARCH_GPTNEOX:
  12093. case LLM_ARCH_MPT:
  12094. case LLM_ARCH_REFACT:
  12095. case LLM_ARCH_BLOOM:
  12096. case LLM_ARCH_MAMBA:
  12097. return LLAMA_ROPE_TYPE_NONE;
  12098. // use what we call a normal RoPE, operating on pairs of consecutive head values
  12099. case LLM_ARCH_LLAMA:
  12100. case LLM_ARCH_BAICHUAN:
  12101. case LLM_ARCH_STARCODER:
  12102. case LLM_ARCH_PLAMO:
  12103. case LLM_ARCH_CODESHELL:
  12104. case LLM_ARCH_ORION:
  12105. case LLM_ARCH_INTERNLM2:
  12106. case LLM_ARCH_MINICPM:
  12107. case LLM_ARCH_XVERSE:
  12108. case LLM_ARCH_COMMAND_R:
  12109. return LLAMA_ROPE_TYPE_NORM;
  12110. // the pairs of head values are offset by n_rot/2
  12111. case LLM_ARCH_FALCON:
  12112. case LLM_ARCH_GROK:
  12113. case LLM_ARCH_PERSIMMON:
  12114. case LLM_ARCH_BERT:
  12115. case LLM_ARCH_NOMIC_BERT:
  12116. case LLM_ARCH_STABLELM:
  12117. case LLM_ARCH_QWEN:
  12118. case LLM_ARCH_QWEN2:
  12119. case LLM_ARCH_PHI2:
  12120. case LLM_ARCH_GEMMA:
  12121. case LLM_ARCH_STARCODER2:
  12122. return LLAMA_ROPE_TYPE_NEOX;
  12123. // all model arches should be listed explicitly here
  12124. case LLM_ARCH_UNKNOWN:
  12125. GGML_ASSERT(false && "unknown architecture");
  12126. break;
  12127. }
  12128. return LLAMA_ROPE_TYPE_NONE;
  12129. }
  12130. int32_t llama_n_vocab(const struct llama_model * model) {
  12131. return model->hparams.n_vocab;
  12132. }
  12133. int32_t llama_n_ctx_train(const struct llama_model * model) {
  12134. return model->hparams.n_ctx_train;
  12135. }
  12136. int32_t llama_n_embd(const struct llama_model * model) {
  12137. return model->hparams.n_embd;
  12138. }
  12139. int32_t llama_n_layer(const struct llama_model * model) {
  12140. return model->hparams.n_layer;
  12141. }
  12142. float llama_rope_freq_scale_train(const struct llama_model * model) {
  12143. return model->hparams.rope_freq_scale_train;
  12144. }
  12145. int32_t llama_model_meta_val_str(const struct llama_model * model, const char * key, char * buf, size_t buf_size) {
  12146. const auto & it = model->gguf_kv.find(key);
  12147. if (it == model->gguf_kv.end()) {
  12148. if (buf_size > 0) {
  12149. buf[0] = '\0';
  12150. }
  12151. return -1;
  12152. }
  12153. return snprintf(buf, buf_size, "%s", it->second.c_str());
  12154. }
  12155. int32_t llama_model_meta_count(const struct llama_model * model) {
  12156. return (int)model->gguf_kv.size();
  12157. }
  12158. int32_t llama_model_meta_key_by_index(const struct llama_model * model, int i, char * buf, size_t buf_size) {
  12159. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  12160. if (buf_size > 0) {
  12161. buf[0] = '\0';
  12162. }
  12163. return -1;
  12164. }
  12165. auto it = model->gguf_kv.begin();
  12166. std::advance(it, i);
  12167. return snprintf(buf, buf_size, "%s", it->first.c_str());
  12168. }
  12169. int32_t llama_model_meta_val_str_by_index(const struct llama_model * model, int32_t i, char * buf, size_t buf_size) {
  12170. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  12171. if (buf_size > 0) {
  12172. buf[0] = '\0';
  12173. }
  12174. return -1;
  12175. }
  12176. auto it = model->gguf_kv.begin();
  12177. std::advance(it, i);
  12178. return snprintf(buf, buf_size, "%s", it->second.c_str());
  12179. }
  12180. int32_t llama_model_desc(const struct llama_model * model, char * buf, size_t buf_size) {
  12181. return snprintf(buf, buf_size, "%s %s %s",
  12182. llama_model_arch_name(model->arch),
  12183. llama_model_type_name(model->type),
  12184. llama_model_ftype_name(model->ftype).c_str());
  12185. }
  12186. uint64_t llama_model_size(const struct llama_model * model) {
  12187. uint64_t size = 0;
  12188. for (const auto & it : model->tensors_by_name) {
  12189. size += ggml_nbytes(it.second);
  12190. }
  12191. return size;
  12192. }
  12193. uint64_t llama_model_n_params(const struct llama_model * model) {
  12194. uint64_t nparams = 0;
  12195. for (const auto & it : model->tensors_by_name) {
  12196. nparams += ggml_nelements(it.second);
  12197. }
  12198. return nparams;
  12199. }
  12200. struct ggml_tensor * llama_get_model_tensor(struct llama_model * model, const char * name) {
  12201. auto it = std::find_if(model->tensors_by_name.begin(), model->tensors_by_name.end(),
  12202. [name](const std::pair<std::string, struct ggml_tensor *> & it) {
  12203. return it.first == name;
  12204. });
  12205. if (it == model->tensors_by_name.end()) {
  12206. return nullptr;
  12207. }
  12208. return it->second;
  12209. }
  12210. uint32_t llama_model_quantize(
  12211. const char * fname_inp,
  12212. const char * fname_out,
  12213. const llama_model_quantize_params * params) {
  12214. try {
  12215. llama_model_quantize_internal(fname_inp, fname_out, params);
  12216. return 0;
  12217. } catch (const std::exception & err) {
  12218. LLAMA_LOG_ERROR("%s: failed to quantize: %s\n", __func__, err.what());
  12219. return 1;
  12220. }
  12221. }
  12222. 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) {
  12223. try {
  12224. return llama_apply_lora_from_file_internal(*model, path_lora, scale, path_base_model, n_threads);
  12225. } catch (const std::exception & err) {
  12226. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  12227. return 1;
  12228. }
  12229. }
  12230. static bool llama_control_vector_init(struct llama_control_vector & cvec, const llama_model & model) {
  12231. GGML_ASSERT(cvec.tensors.empty());
  12232. GGML_ASSERT(cvec.ctxs.empty());
  12233. GGML_ASSERT(cvec.bufs.empty());
  12234. // count layer buffer types
  12235. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  12236. for (int64_t i = 0; i < model.hparams.n_layer; i++) {
  12237. buft_layer_count[model.buft_layer[i].buft]++;
  12238. }
  12239. // allocate contexts
  12240. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  12241. for (auto & it : buft_layer_count) {
  12242. int n_layers = it.second;
  12243. struct ggml_init_params params = {
  12244. /*.mem_size =*/ n_layers * ggml_tensor_overhead(),
  12245. /*.mem_buffer =*/ NULL,
  12246. /*.no_alloc =*/ true,
  12247. };
  12248. ggml_context * ctx = ggml_init(params);
  12249. if (!ctx) {
  12250. LLAMA_LOG_ERROR("%s: failed to allocate context for control vector\n", __func__);
  12251. return 1;
  12252. }
  12253. ctx_map[it.first] = ctx;
  12254. }
  12255. // make tensors
  12256. cvec.tensors.push_back(nullptr); // there's never a tensor for layer 0
  12257. for (size_t il = 1; il < model.hparams.n_layer; il++) {
  12258. struct ggml_context * ctx = ctx_map.at(model.buft_layer[il].buft);
  12259. ggml_tensor * tensor = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, model.hparams.n_embd);
  12260. cvec.tensors.push_back(tensor);
  12261. }
  12262. // allocate tensors / buffers and zero
  12263. for (auto it : ctx_map) {
  12264. ggml_backend_buffer_type_t buft = it.first;
  12265. ggml_context * ctx = it.second;
  12266. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  12267. if (!buf) {
  12268. LLAMA_LOG_ERROR("%s: failed to allocate buffer for control vector\n", __func__);
  12269. return false;
  12270. }
  12271. ggml_backend_buffer_clear(buf, 0);
  12272. cvec.ctxs.push_back(ctx);
  12273. cvec.bufs.push_back(buf);
  12274. }
  12275. return true;
  12276. }
  12277. 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) {
  12278. const llama_model & model = lctx->model;
  12279. llama_control_vector & cvec = lctx->cvec;
  12280. if (data == nullptr) {
  12281. // disable the current control vector (but leave allocated for later)
  12282. cvec.layer_start = -1;
  12283. cvec.layer_end = -1;
  12284. return 0;
  12285. }
  12286. if (n_embd != (int) model.hparams.n_embd) {
  12287. LLAMA_LOG_ERROR("%s: control vector n_embd does not match model\n", __func__);
  12288. return 1;
  12289. }
  12290. if (cvec.tensors.empty()) {
  12291. if (!llama_control_vector_init(cvec, model)) {
  12292. return 1;
  12293. }
  12294. }
  12295. cvec.layer_start = il_start;
  12296. cvec.layer_end = il_end;
  12297. for (size_t il = 1; il < model.hparams.n_layer; il++) {
  12298. assert(cvec.tensors[il] != nullptr);
  12299. const size_t off = n_embd * (il - 1); // buffer doesn't have data for layer 0, since it's never present
  12300. if (off + n_embd <= len) {
  12301. ggml_backend_tensor_set(cvec.tensors[il], data + off, 0, n_embd * ggml_element_size(cvec.tensors[il]));
  12302. }
  12303. }
  12304. return 0;
  12305. }
  12306. struct llama_kv_cache_view llama_kv_cache_view_init(const struct llama_context * ctx, int32_t n_seq_max) {
  12307. struct llama_kv_cache_view result = {
  12308. /*.n_cells = */ 0,
  12309. /*.n_seq_max = */ n_seq_max,
  12310. /*.token_count = */ 0,
  12311. /*.used_cells = */ llama_get_kv_cache_used_cells(ctx),
  12312. /*.max_contiguous = */ 0,
  12313. /*.max_contiguous_idx = */ -1,
  12314. /*.cells = */ nullptr,
  12315. /*.cells_sequences = */ nullptr,
  12316. };
  12317. return result;
  12318. }
  12319. void llama_kv_cache_view_free(struct llama_kv_cache_view * view) {
  12320. if (view->cells != nullptr) {
  12321. free(view->cells);
  12322. view->cells = nullptr;
  12323. }
  12324. if (view->cells_sequences != nullptr) {
  12325. free(view->cells_sequences);
  12326. view->cells_sequences = nullptr;
  12327. }
  12328. }
  12329. void llama_kv_cache_view_update(const struct llama_context * ctx, struct llama_kv_cache_view * view) {
  12330. if (uint32_t(view->n_cells) < ctx->kv_self.size || view->cells == nullptr) {
  12331. view->n_cells = int32_t(ctx->kv_self.size);
  12332. void * p = realloc(view->cells, sizeof(struct llama_kv_cache_view_cell) * view->n_cells);
  12333. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells");
  12334. view->cells = (struct llama_kv_cache_view_cell *)p;
  12335. p = realloc(view->cells_sequences, sizeof(llama_seq_id) * view->n_seq_max * view->n_cells);
  12336. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells sequences");
  12337. view->cells_sequences = (llama_seq_id *)p;
  12338. }
  12339. const std::vector<llama_kv_cell> & kv_cells = ctx->kv_self.cells;
  12340. llama_kv_cache_view_cell * c_curr = view->cells;
  12341. llama_seq_id * cs_curr = view->cells_sequences;
  12342. int32_t used_cells = 0;
  12343. int32_t token_count = 0;
  12344. int32_t curr_contig_idx = -1;
  12345. uint32_t max_contig = 0;
  12346. int32_t max_contig_idx = -1;
  12347. for (int32_t i = 0; i < int32_t(ctx->kv_self.size); i++, c_curr++, cs_curr += view->n_seq_max) {
  12348. const size_t curr_size = kv_cells[i].seq_id.size();
  12349. token_count += curr_size;
  12350. c_curr->pos = kv_cells[i].pos + kv_cells[i].delta;
  12351. if (curr_size > 0) {
  12352. if (curr_contig_idx >= 0 && uint32_t(i - curr_contig_idx) > max_contig) {
  12353. max_contig = i - curr_contig_idx;
  12354. max_contig_idx = curr_contig_idx;
  12355. }
  12356. curr_contig_idx = -1;
  12357. } else if (curr_contig_idx < 0) {
  12358. curr_contig_idx = i;
  12359. }
  12360. int seq_idx = 0;
  12361. for (const llama_seq_id it : kv_cells[i].seq_id) {
  12362. if (seq_idx >= view->n_seq_max) {
  12363. break;
  12364. }
  12365. cs_curr[seq_idx] = it;
  12366. seq_idx++;
  12367. }
  12368. if (seq_idx != 0) {
  12369. used_cells++;
  12370. }
  12371. for (; seq_idx < view->n_seq_max; seq_idx++) {
  12372. cs_curr[seq_idx] = -1;
  12373. }
  12374. }
  12375. if (curr_contig_idx >= 0 && kv_cells.size() - curr_contig_idx > max_contig) {
  12376. max_contig_idx = curr_contig_idx;
  12377. max_contig = kv_cells.size() - curr_contig_idx;
  12378. }
  12379. view->max_contiguous = max_contig;
  12380. view->max_contiguous_idx = max_contig_idx;
  12381. view->token_count = token_count;
  12382. view->used_cells = used_cells;
  12383. if (uint32_t(used_cells) != ctx->kv_self.used) {
  12384. LLAMA_LOG_ERROR("%s: used cells mismatch. kv_cache says %d but we calculated %d\n",
  12385. __func__, ctx->kv_self.used, used_cells);
  12386. }
  12387. }
  12388. int32_t llama_get_kv_cache_token_count(const struct llama_context * ctx) {
  12389. int result = 0;
  12390. for (uint32_t i = 0; i < ctx->kv_self.size; i++) {
  12391. result += ctx->kv_self.cells[i].seq_id.size();
  12392. }
  12393. return result;
  12394. }
  12395. int32_t llama_get_kv_cache_used_cells(const struct llama_context * ctx) {
  12396. return ctx->kv_self.used;
  12397. }
  12398. void llama_kv_cache_clear(struct llama_context * ctx) {
  12399. llama_kv_cache_clear(ctx->kv_self);
  12400. }
  12401. bool llama_kv_cache_seq_rm(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
  12402. return llama_kv_cache_seq_rm(ctx->kv_self, seq_id, p0, p1);
  12403. }
  12404. 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) {
  12405. if (seq_id_src == seq_id_dst) {
  12406. return;
  12407. }
  12408. llama_kv_cache_seq_cp(ctx->kv_self, seq_id_src, seq_id_dst, p0, p1);
  12409. }
  12410. void llama_kv_cache_seq_keep(struct llama_context * ctx, llama_seq_id seq_id) {
  12411. llama_kv_cache_seq_keep(ctx->kv_self, seq_id);
  12412. }
  12413. void llama_kv_cache_seq_add(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos delta) {
  12414. if (delta == 0) {
  12415. return;
  12416. }
  12417. llama_kv_cache_seq_add(ctx->kv_self, seq_id, p0, p1, delta);
  12418. }
  12419. void llama_kv_cache_seq_div(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) {
  12420. if (d == 1) {
  12421. return;
  12422. }
  12423. llama_kv_cache_seq_div(ctx->kv_self, seq_id, p0, p1, d);
  12424. }
  12425. llama_pos llama_kv_cache_seq_pos_max(struct llama_context * ctx, llama_seq_id seq_id) {
  12426. return llama_kv_cache_seq_pos_max(ctx->kv_self, seq_id);
  12427. }
  12428. void llama_kv_cache_defrag(struct llama_context * ctx) {
  12429. llama_kv_cache_defrag(ctx->kv_self);
  12430. }
  12431. void llama_kv_cache_update(struct llama_context * ctx) {
  12432. llama_kv_cache_update_internal(*ctx);
  12433. }
  12434. // deprecated
  12435. size_t llama_get_state_size(const struct llama_context * ctx) {
  12436. return llama_state_get_size(ctx);
  12437. }
  12438. // deprecated
  12439. size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dst) {
  12440. return llama_state_get_data(ctx, dst);
  12441. }
  12442. // deprecated
  12443. size_t llama_set_state_data(struct llama_context * ctx, const uint8_t * src) {
  12444. return llama_state_set_data(ctx, src);
  12445. }
  12446. // deprecated
  12447. 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) {
  12448. return llama_state_load_file(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  12449. }
  12450. // deprecated
  12451. bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  12452. return llama_state_save_file(ctx, path_session, tokens, n_token_count);
  12453. }
  12454. // Returns the *maximum* size of the state
  12455. size_t llama_state_get_size(const struct llama_context * ctx) {
  12456. const auto & cparams = ctx->cparams;
  12457. const auto & hparams = ctx->model.hparams;
  12458. // we don't know size of rng until we actually serialize it. so reserve more than enough memory for its serialized state.
  12459. // for reference, std::mt19937(1337) serializes to 6701 bytes.
  12460. const size_t s_rng_size = sizeof(size_t);
  12461. const size_t s_rng = LLAMA_MAX_RNG_STATE;
  12462. const size_t s_n_outputs = sizeof(size_t);
  12463. // assume worst case for outputs although only currently set ones are serialized
  12464. const size_t s_output_pos = ctx->cparams.n_batch * sizeof(int32_t);
  12465. const size_t s_logits_size = sizeof(size_t);
  12466. const size_t s_logits = ctx->logits_size ? cparams.n_batch * hparams.n_vocab * sizeof(float) : 0;
  12467. const size_t s_embedding_size = sizeof(size_t);
  12468. const size_t s_embedding = ctx->embd_size ? cparams.n_batch * hparams.n_embd * sizeof(float) : 0;
  12469. const size_t s_kv_buf_size = sizeof(size_t);
  12470. const size_t s_kv_head = sizeof(uint32_t);
  12471. const size_t s_kv_size = sizeof(uint32_t);
  12472. const size_t s_kv_used = sizeof(uint32_t);
  12473. const size_t s_kv = ctx->kv_self.total_size();
  12474. const size_t s_kv_cell = sizeof(llama_pos) + sizeof(size_t) + cparams.n_seq_max*sizeof(llama_seq_id);
  12475. const size_t s_kv_cells = ctx->kv_self.size * s_kv_cell;
  12476. const size_t s_total = (
  12477. + s_rng_size
  12478. + s_rng
  12479. + s_n_outputs
  12480. + s_output_pos
  12481. + s_logits_size
  12482. + s_logits
  12483. + s_embedding_size
  12484. + s_embedding
  12485. + s_kv_buf_size
  12486. + s_kv_head
  12487. + s_kv_size
  12488. + s_kv_used
  12489. + s_kv
  12490. + s_kv_cells
  12491. );
  12492. return s_total;
  12493. }
  12494. // llama_context_data
  12495. struct llama_data_context {
  12496. virtual void write(const void * src, size_t size) = 0;
  12497. virtual size_t get_size_written() = 0;
  12498. virtual ~llama_data_context() = default;
  12499. };
  12500. struct llama_data_buffer_context : llama_data_context {
  12501. uint8_t * ptr;
  12502. size_t size_written = 0;
  12503. llama_data_buffer_context(uint8_t * p) : ptr(p) {}
  12504. void write(const void * src, size_t size) override {
  12505. memcpy(ptr, src, size);
  12506. ptr += size;
  12507. size_written += size;
  12508. }
  12509. size_t get_size_written() override {
  12510. return size_written;
  12511. }
  12512. };
  12513. struct llama_data_file_context : llama_data_context {
  12514. llama_file * file;
  12515. size_t size_written = 0;
  12516. llama_data_file_context(llama_file * f) : file(f) {}
  12517. void write(const void * src, size_t size) override {
  12518. file->write_raw(src, size);
  12519. size_written += size;
  12520. }
  12521. size_t get_size_written() override {
  12522. return size_written;
  12523. }
  12524. };
  12525. /** copy state data into either a buffer or file depending on the passed in context
  12526. *
  12527. * file context:
  12528. * llama_file file("/path", "wb");
  12529. * llama_data_file_context data_ctx(&file);
  12530. * llama_state_get_data(ctx, &data_ctx);
  12531. *
  12532. * buffer context:
  12533. * std::vector<uint8_t> buf(max_size, 0);
  12534. * llama_data_buffer_context data_ctx(&buf.data());
  12535. * llama_state_get_data(ctx, &data_ctx);
  12536. *
  12537. */
  12538. static void llama_state_get_data_internal(struct llama_context * ctx, llama_data_context * data_ctx) {
  12539. // copy rng
  12540. {
  12541. std::ostringstream rng_ss;
  12542. rng_ss << ctx->rng;
  12543. const std::string & rng_str = rng_ss.str();
  12544. const size_t rng_size = rng_str.size();
  12545. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  12546. data_ctx->write(&rng_size, sizeof(rng_size));
  12547. data_ctx->write(rng_str.data(), rng_size);
  12548. }
  12549. // copy outputs
  12550. {
  12551. // Can't use ctx->n_outputs because it's not for the
  12552. // entire last batch when n_ubatch is smaller than n_batch
  12553. size_t n_outputs = 0;
  12554. // copy output ids
  12555. {
  12556. std::vector<int32_t> output_pos;
  12557. const size_t n_batch = ctx->cparams.n_batch;
  12558. const auto & output_ids = ctx->output_ids;
  12559. output_pos.resize(ctx->output_size);
  12560. // build a more compact representation of the output ids
  12561. for (size_t i = 0; i < n_batch; ++i) {
  12562. // map an output id to a position in the batch
  12563. int32_t pos = output_ids[i];
  12564. if (pos >= 0) {
  12565. if ((size_t) pos >= n_outputs) {
  12566. n_outputs = pos + 1;
  12567. }
  12568. GGML_ASSERT((size_t) pos < ctx->output_size);
  12569. output_pos[pos] = i;
  12570. }
  12571. }
  12572. data_ctx->write(&n_outputs, sizeof(n_outputs));
  12573. if (n_outputs) {
  12574. data_ctx->write(output_pos.data(), n_outputs * sizeof(int32_t));
  12575. }
  12576. }
  12577. // copy logits
  12578. {
  12579. const size_t logits_size = std::min(ctx->logits_size, n_outputs * ctx->model.hparams.n_vocab);
  12580. data_ctx->write(&logits_size, sizeof(logits_size));
  12581. if (logits_size) {
  12582. data_ctx->write(ctx->logits, logits_size * sizeof(float));
  12583. }
  12584. }
  12585. // copy embeddings
  12586. {
  12587. const size_t embeddings_size = std::min(ctx->embd_size, n_outputs * ctx->model.hparams.n_embd);
  12588. data_ctx->write(&embeddings_size, sizeof(embeddings_size));
  12589. if (embeddings_size) {
  12590. data_ctx->write(ctx->embd, embeddings_size * sizeof(float));
  12591. }
  12592. }
  12593. }
  12594. // copy kv cache
  12595. {
  12596. const auto & kv_self = ctx->kv_self;
  12597. const auto & hparams = ctx->model.hparams;
  12598. const uint32_t n_layer = hparams.n_layer;
  12599. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  12600. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  12601. // NOTE: kv_size and kv_buf_size are mostly used for sanity checks
  12602. const uint32_t kv_head = llama_kv_cache_cell_max(kv_self);
  12603. const uint32_t kv_size = kv_self.size;
  12604. const size_t kv_buf_size = kv_self.total_size() / (kv_size ? kv_size : 1) * kv_head;
  12605. const uint32_t kv_used = kv_self.used;
  12606. data_ctx->write(&kv_buf_size, sizeof(kv_buf_size));
  12607. data_ctx->write(&kv_head, sizeof(kv_head));
  12608. data_ctx->write(&kv_size, sizeof(kv_size));
  12609. data_ctx->write(&kv_used, sizeof(kv_used));
  12610. if (kv_buf_size) {
  12611. const size_t pre_kv_buf_size = data_ctx->get_size_written();
  12612. std::vector<uint8_t> tmp_buf;
  12613. for (int il = 0; il < (int) n_layer; ++il) {
  12614. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_head);
  12615. tmp_buf.resize(k_size);
  12616. ggml_backend_tensor_get(kv_self.k_l[il], tmp_buf.data(), 0, tmp_buf.size());
  12617. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  12618. if (kv_self.recurrent) {
  12619. // v is contiguous for recurrent models
  12620. // TODO: use other tensors for state models than k and v
  12621. const size_t v_size = ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa*kv_head);
  12622. tmp_buf.resize(v_size);
  12623. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), 0, tmp_buf.size());
  12624. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  12625. continue;
  12626. }
  12627. // v is not contiguous, copy row by row
  12628. const size_t v_row_size = ggml_row_size(kv_self.v_l[il]->type, kv_head);
  12629. const size_t v_row_stride = ggml_row_size(kv_self.v_l[il]->type, kv_size);
  12630. tmp_buf.resize(v_row_size);
  12631. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  12632. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), ir*v_row_stride, tmp_buf.size());
  12633. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  12634. }
  12635. }
  12636. GGML_ASSERT(kv_buf_size == data_ctx->get_size_written() - pre_kv_buf_size);
  12637. }
  12638. for (uint32_t i = 0; i < kv_head; ++i) {
  12639. const auto & cell = kv_self.cells[i];
  12640. const llama_pos pos = cell.pos;
  12641. const size_t seq_id_size = cell.seq_id.size();
  12642. data_ctx->write(&pos, sizeof(pos));
  12643. data_ctx->write(&seq_id_size, sizeof(seq_id_size));
  12644. for (auto seq_id : cell.seq_id) {
  12645. data_ctx->write(&seq_id, sizeof(seq_id));
  12646. }
  12647. }
  12648. }
  12649. }
  12650. size_t llama_state_get_data(struct llama_context * ctx, uint8_t * dst) {
  12651. llama_data_buffer_context data_ctx(dst);
  12652. llama_state_get_data_internal(ctx, &data_ctx);
  12653. return data_ctx.get_size_written();
  12654. }
  12655. // Sets the state reading from the specified source address
  12656. size_t llama_state_set_data(struct llama_context * ctx, const uint8_t * src) {
  12657. const uint8_t * inp = src;
  12658. // set rng
  12659. {
  12660. size_t rng_size;
  12661. memcpy(&rng_size, inp, sizeof(rng_size)); inp += sizeof(rng_size);
  12662. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  12663. std::string rng_str((const char *)inp, rng_size); inp += rng_size;
  12664. std::istringstream rng_ss(rng_str);
  12665. rng_ss >> ctx->rng;
  12666. GGML_ASSERT(!rng_ss.fail());
  12667. }
  12668. // set output ids
  12669. {
  12670. size_t n_outputs;
  12671. std::vector<int32_t> output_pos;
  12672. memcpy(&n_outputs, inp, sizeof(n_outputs)); inp += sizeof(n_outputs);
  12673. GGML_ASSERT(n_outputs <= llama_output_reserve(*ctx, n_outputs));
  12674. if (n_outputs) {
  12675. output_pos.resize(n_outputs);
  12676. memcpy(output_pos.data(), inp, n_outputs * sizeof(int32_t));
  12677. inp += n_outputs * sizeof(int32_t);
  12678. for (int32_t i = 0; i < (int32_t) output_pos.size(); ++i) {
  12679. int32_t id = output_pos[i];
  12680. GGML_ASSERT((uint32_t) id < ctx->cparams.n_batch);
  12681. ctx->output_ids[id] = i;
  12682. }
  12683. }
  12684. }
  12685. // set logits
  12686. {
  12687. size_t logits_size;
  12688. memcpy(&logits_size, inp, sizeof(logits_size)); inp += sizeof(logits_size);
  12689. GGML_ASSERT(ctx->logits_size >= logits_size);
  12690. if (logits_size) {
  12691. memcpy(ctx->logits, inp, logits_size * sizeof(float));
  12692. inp += logits_size * sizeof(float);
  12693. }
  12694. }
  12695. // set embeddings
  12696. {
  12697. size_t embeddings_size;
  12698. memcpy(&embeddings_size, inp, sizeof(embeddings_size)); inp += sizeof(embeddings_size);
  12699. GGML_ASSERT(ctx->embd_size >= embeddings_size);
  12700. if (embeddings_size) {
  12701. memcpy(ctx->embd, inp, embeddings_size * sizeof(float));
  12702. inp += embeddings_size * sizeof(float);
  12703. }
  12704. }
  12705. // set kv cache
  12706. {
  12707. const auto & kv_self = ctx->kv_self;
  12708. const auto & hparams = ctx->model.hparams;
  12709. const uint32_t n_layer = hparams.n_layer;
  12710. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  12711. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  12712. size_t kv_buf_size;
  12713. uint32_t kv_head;
  12714. uint32_t kv_size;
  12715. uint32_t kv_used;
  12716. memcpy(&kv_buf_size, inp, sizeof(kv_buf_size)); inp += sizeof(kv_buf_size);
  12717. memcpy(&kv_head, inp, sizeof(kv_head)); inp += sizeof(kv_head);
  12718. memcpy(&kv_size, inp, sizeof(kv_size)); inp += sizeof(kv_size);
  12719. memcpy(&kv_used, inp, sizeof(kv_used)); inp += sizeof(kv_used);
  12720. if (kv_self.size != kv_size) {
  12721. // the KV cache needs to be big enough to load all the KV cells from the saved state
  12722. GGML_ASSERT(kv_self.size >= kv_head);
  12723. 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",
  12724. __func__, kv_head, kv_size, kv_self.size);
  12725. }
  12726. if (kv_buf_size) {
  12727. const size_t pre_kv_buf_size = inp - src;
  12728. GGML_ASSERT(kv_self.total_size() >= kv_buf_size);
  12729. for (int il = 0; il < (int) n_layer; ++il) {
  12730. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_head);
  12731. ggml_backend_tensor_set(kv_self.k_l[il], inp, 0, k_size);
  12732. inp += k_size;
  12733. if (kv_self.recurrent) {
  12734. // v is contiguous for recurrent models
  12735. // TODO: use other tensors for state models than k and v
  12736. const size_t v_size = ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa*kv_head);
  12737. ggml_backend_tensor_set(kv_self.v_l[il], inp, 0, v_size);
  12738. inp += v_size;
  12739. continue;
  12740. }
  12741. // v is not contiguous, copy row by row
  12742. const size_t v_row_size = ggml_row_size(kv_self.v_l[il]->type, kv_head);
  12743. const size_t v_row_stride = ggml_row_size(kv_self.v_l[il]->type, kv_self.size);
  12744. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  12745. ggml_backend_tensor_set(kv_self.v_l[il], inp, ir*v_row_stride, v_row_size);
  12746. inp += v_row_size;
  12747. }
  12748. }
  12749. GGML_ASSERT(kv_buf_size == inp - src - pre_kv_buf_size);
  12750. }
  12751. llama_kv_cache_clear(ctx);
  12752. ctx->kv_self.head = kv_head;
  12753. ctx->kv_self.used = kv_used;
  12754. for (uint32_t i = 0; i < kv_head; ++i) {
  12755. llama_pos pos;
  12756. size_t seq_id_size;
  12757. memcpy(&pos, inp, sizeof(pos)); inp += sizeof(pos);
  12758. memcpy(&seq_id_size, inp, sizeof(seq_id_size)); inp += sizeof(seq_id_size);
  12759. ctx->kv_self.cells[i].pos = pos;
  12760. llama_seq_id seq_id;
  12761. for (size_t j = 0; j < seq_id_size; ++j) {
  12762. memcpy(&seq_id, inp, sizeof(seq_id)); inp += sizeof(seq_id);
  12763. ctx->kv_self.cells[i].seq_id.insert(seq_id);
  12764. }
  12765. }
  12766. }
  12767. const size_t nread = inp - src;
  12768. const size_t max_size = llama_state_get_size(ctx);
  12769. GGML_ASSERT(nread <= max_size);
  12770. return nread;
  12771. }
  12772. 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) {
  12773. llama_file file(path_session, "rb");
  12774. // sanity checks
  12775. {
  12776. const uint32_t magic = file.read_u32();
  12777. const uint32_t version = file.read_u32();
  12778. if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
  12779. LLAMA_LOG_ERROR("%s : unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
  12780. return false;
  12781. }
  12782. llama_hparams session_hparams;
  12783. file.read_raw(&session_hparams, sizeof(llama_hparams));
  12784. if (session_hparams != ctx->model.hparams) {
  12785. LLAMA_LOG_INFO("%s : model hparams didn't match from session file!\n", __func__);
  12786. return false;
  12787. }
  12788. }
  12789. // load the prompt
  12790. {
  12791. const uint32_t n_token_count = file.read_u32();
  12792. if (n_token_count > n_token_capacity) {
  12793. LLAMA_LOG_ERROR("%s : token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  12794. return false;
  12795. }
  12796. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  12797. *n_token_count_out = n_token_count;
  12798. }
  12799. // restore the context state
  12800. {
  12801. const size_t n_state_size_cur = file.size - file.tell();
  12802. const size_t n_state_size_max = llama_state_get_size(ctx);
  12803. if (n_state_size_cur > n_state_size_max) {
  12804. 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);
  12805. return false;
  12806. }
  12807. std::vector<uint8_t> state_data(n_state_size_max);
  12808. file.read_raw(state_data.data(), n_state_size_cur);
  12809. llama_state_set_data(ctx, state_data.data());
  12810. }
  12811. return true;
  12812. }
  12813. 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) {
  12814. try {
  12815. return llama_state_load_file_internal(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  12816. } catch (const std::exception & err) {
  12817. LLAMA_LOG_ERROR("error loading session file: %s\n", err.what());
  12818. return false;
  12819. }
  12820. }
  12821. static bool llama_state_save_file_internal(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  12822. llama_file file(path_session, "wb");
  12823. file.write_u32(LLAMA_SESSION_MAGIC);
  12824. file.write_u32(LLAMA_SESSION_VERSION);
  12825. file.write_raw(&ctx->model.hparams, sizeof(llama_hparams));
  12826. // save the prompt
  12827. file.write_u32((uint32_t) n_token_count);
  12828. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  12829. // save the context state using stream saving
  12830. llama_data_file_context data_ctx(&file);
  12831. llama_state_get_data_internal(ctx, &data_ctx);
  12832. return true;
  12833. }
  12834. bool llama_state_save_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  12835. try {
  12836. return llama_state_save_file_internal(ctx, path_session, tokens, n_token_count);
  12837. } catch (const std::exception & err) {
  12838. LLAMA_LOG_ERROR("error saving session file: %s\n", err.what());
  12839. return false;
  12840. }
  12841. }
  12842. size_t llama_state_seq_get_size(struct llama_context* ctx, llama_seq_id seq_id) {
  12843. // save the size of size_t as a uint32_t for safety check
  12844. const size_t size_t_size_size = sizeof(uint32_t);
  12845. // other values
  12846. const size_t s_cell_count_size = sizeof(uint32_t);
  12847. const size_t s_layer_count_size = sizeof(uint32_t);
  12848. const size_t n_embd_v_gqa_size = sizeof(uint32_t);
  12849. size_t s_cell_count = 0;
  12850. size_t s_cell_data_size = 0;
  12851. const auto & kv_self = ctx->kv_self;
  12852. const auto & hparams = ctx->model.hparams;
  12853. const uint32_t n_layer = hparams.n_layer;
  12854. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  12855. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  12856. for (uint32_t i = 0; i < kv_self.size; ++i) {
  12857. const auto & cell = kv_self.cells[i];
  12858. if (cell.seq_id.count(seq_id) > 0) {
  12859. ++s_cell_count;
  12860. s_cell_data_size += sizeof(llama_pos);
  12861. }
  12862. }
  12863. for (int il = 0; il < (int)n_layer; ++il) {
  12864. // types of keys and values
  12865. s_cell_data_size += sizeof(int32_t) * 2;
  12866. // k_size_row and v_size_el values of layer
  12867. s_cell_data_size += sizeof(size_t) * 2;
  12868. // keys
  12869. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  12870. s_cell_data_size += k_size_row * s_cell_count;
  12871. // values (transposed)
  12872. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  12873. s_cell_data_size += v_size_el * s_cell_count * n_embd_v_gqa;
  12874. }
  12875. const size_t s_total = (
  12876. size_t_size_size +
  12877. s_cell_count_size +
  12878. s_layer_count_size +
  12879. n_embd_v_gqa_size +
  12880. s_cell_data_size
  12881. );
  12882. return s_total;
  12883. }
  12884. static size_t llama_state_seq_get_data_internal(struct llama_context * ctx, llama_data_context & data_ctx, llama_seq_id seq_id) {
  12885. const auto & kv_self = ctx->kv_self;
  12886. GGML_ASSERT(!kv_self.recurrent); // not implemented
  12887. // Save the size of size_t as a uint32_t for safety check
  12888. const uint32_t size_t_size = sizeof(size_t);
  12889. data_ctx.write(&size_t_size, sizeof(size_t_size));
  12890. std::vector<std::pair<uint32_t, uint32_t>> cell_ranges; // ranges, from inclusive, to exclusive
  12891. uint32_t cell_count = 0;
  12892. // Count the number of cells with the specified seq_id
  12893. // Find all the ranges of cells with this seq id
  12894. {
  12895. uint32_t cell_range_begin = kv_self.size;
  12896. for (uint32_t i = 0; i < kv_self.size; ++i) {
  12897. const auto & cell = kv_self.cells[i];
  12898. if (cell.has_seq_id(seq_id)) {
  12899. ++cell_count;
  12900. if (cell_range_begin == kv_self.size) {
  12901. cell_range_begin = i;
  12902. }
  12903. }
  12904. else {
  12905. if (cell_range_begin != kv_self.size) {
  12906. cell_ranges.push_back({ cell_range_begin, i });
  12907. cell_range_begin = kv_self.size;
  12908. }
  12909. }
  12910. }
  12911. if (cell_range_begin != kv_self.size) {
  12912. cell_ranges.push_back({ cell_range_begin, kv_self.size });
  12913. }
  12914. // DEBUG CHECK: Sum of cell counts in ranges should equal the total cell count
  12915. uint32_t cell_count_check = 0;
  12916. for (const auto & range : cell_ranges) {
  12917. cell_count_check += range.second - range.first;
  12918. }
  12919. GGML_ASSERT(cell_count == cell_count_check);
  12920. }
  12921. // Write the cell count
  12922. data_ctx.write(&cell_count, sizeof(cell_count));
  12923. const auto & hparams = ctx->model.hparams;
  12924. const uint32_t n_layer = hparams.n_layer;
  12925. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  12926. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  12927. // Write the layer count
  12928. data_ctx.write(&n_layer, sizeof(n_layer));
  12929. // Write n_embd_v_gqa
  12930. data_ctx.write(&n_embd_v_gqa, sizeof(n_embd_v_gqa));
  12931. // Iterate the ranges and write all the pos (this is the token position in the prompt)
  12932. for (const auto & range : cell_ranges) {
  12933. for (uint32_t i = range.first; i < range.second; ++i) {
  12934. const auto & cell = kv_self.cells[i];
  12935. data_ctx.write(&cell.pos, sizeof(cell.pos));
  12936. }
  12937. }
  12938. // Iterate and write all the keys first, each row is a cell
  12939. // Get whole range at a time
  12940. std::vector<uint8_t> tmp_buf;
  12941. for (int il = 0; il < (int)n_layer; ++il) {
  12942. // Write key type
  12943. const int32_t k_type_i = (int32_t)kv_self.k_l[il]->type;
  12944. data_ctx.write(&k_type_i, sizeof(k_type_i));
  12945. // Write row size of key
  12946. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  12947. data_ctx.write(&k_size_row, sizeof(k_size_row));
  12948. // Read each range of cells of k_size length each into tmp_buf and write out
  12949. for (const auto & range : cell_ranges) {
  12950. const size_t range_size = range.second - range.first;
  12951. tmp_buf.resize(range_size * k_size_row);
  12952. ggml_backend_tensor_get(kv_self.k_l[il], tmp_buf.data(), range.first * k_size_row, range_size * k_size_row);
  12953. data_ctx.write(tmp_buf.data(), tmp_buf.size());
  12954. }
  12955. }
  12956. // For the values, they are transposed, so we also need the element size and get the element ranges from each row
  12957. const uint32_t kv_size = kv_self.size;
  12958. for (int il = 0; il < (int)n_layer; ++il) {
  12959. // Write value type
  12960. const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
  12961. data_ctx.write(&v_type_i, sizeof(v_type_i));
  12962. // Write element size
  12963. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  12964. data_ctx.write(&v_size_el, sizeof(v_size_el));
  12965. // For each row, we get the element values of each cell
  12966. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  12967. // Read each range of cells of v_size_el length each into tmp_buf and write out
  12968. for (const auto & range : cell_ranges) {
  12969. const size_t range_size = range.second - range.first;
  12970. const size_t src_offset = (range.first + j * kv_size) * v_size_el;
  12971. tmp_buf.resize(range_size * v_size_el);
  12972. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), src_offset, tmp_buf.size());
  12973. data_ctx.write(tmp_buf.data(), tmp_buf.size());
  12974. }
  12975. }
  12976. }
  12977. return data_ctx.get_size_written();
  12978. }
  12979. size_t llama_state_seq_get_data(struct llama_context* ctx, uint8_t* dst, llama_seq_id seq_id) {
  12980. llama_data_buffer_context data_ctx(dst);
  12981. return llama_state_seq_get_data_internal(ctx, data_ctx, seq_id);
  12982. }
  12983. size_t llama_state_seq_set_data(struct llama_context * ctx, const uint8_t * src, llama_seq_id dest_seq_id) {
  12984. auto & kv_self = ctx->kv_self;
  12985. GGML_ASSERT(!kv_self.recurrent); // not implemented
  12986. // Wipe the slot
  12987. llama_kv_cache_seq_rm(kv_self, dest_seq_id, -1, -1);
  12988. const uint8_t * inp = src;
  12989. // Read size of size_t
  12990. uint32_t size_t_size;
  12991. memcpy(&size_t_size, inp, sizeof(size_t_size));
  12992. inp += sizeof(size_t_size);
  12993. if (size_t_size != sizeof(size_t)) {
  12994. LLAMA_LOG_ERROR("%s: size_t size mismatch\n", __func__);
  12995. return 0;
  12996. }
  12997. // Read the cell count
  12998. uint32_t cell_count;
  12999. memcpy(&cell_count, inp, sizeof(cell_count));
  13000. inp += sizeof(cell_count);
  13001. // Read the layer count
  13002. uint32_t n_layer_ref;
  13003. memcpy(&n_layer_ref, inp, sizeof(n_layer_ref));
  13004. inp += sizeof(n_layer_ref);
  13005. // Read n_embd_v_gqa
  13006. uint32_t n_embd_v_gqa_ref;
  13007. memcpy(&n_embd_v_gqa_ref, inp, sizeof(n_embd_v_gqa_ref));
  13008. inp += sizeof(n_embd_v_gqa_ref);
  13009. // Sanity check model compatibility
  13010. const auto & hparams = ctx->model.hparams;
  13011. const uint32_t n_layer = hparams.n_layer;
  13012. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  13013. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  13014. if (n_layer != n_layer_ref) {
  13015. LLAMA_LOG_ERROR("%s: mismatched n_layer (%d != %d)\n", __func__, n_layer, n_layer_ref);
  13016. return 0;
  13017. }
  13018. if (n_embd_v_gqa != n_embd_v_gqa_ref) {
  13019. LLAMA_LOG_ERROR("%s: mismatched n_embd_v_gqa (%d != %d)\n", __func__, n_embd_v_gqa, n_embd_v_gqa_ref);
  13020. return 0;
  13021. }
  13022. // Allocate the new cells for the slot
  13023. if (cell_count) {
  13024. llama_batch batch = llama_batch_init(cell_count, 0, 1);
  13025. batch.n_tokens = cell_count;
  13026. for (uint32_t i = 0; i < cell_count; ++i) {
  13027. llama_pos pos;
  13028. memcpy(&pos, inp, sizeof(pos));
  13029. inp += sizeof(pos);
  13030. batch.pos[i] = pos;
  13031. batch.n_seq_id[i] = 1;
  13032. batch.seq_id[i][0] = dest_seq_id;
  13033. }
  13034. if (!llama_kv_cache_find_slot(kv_self, batch)) {
  13035. llama_batch_free(batch);
  13036. LLAMA_LOG_ERROR("%s: failed to find available cells in kv cache\n", __func__);
  13037. return 0;
  13038. }
  13039. // 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)
  13040. // Assume that this is one contiguous block of cells
  13041. GGML_ASSERT(kv_self.head + cell_count <= kv_self.size);
  13042. GGML_ASSERT(kv_self.cells[kv_self.head].pos == batch.pos[0]);
  13043. GGML_ASSERT(kv_self.cells[kv_self.head + cell_count - 1].pos == batch.pos[cell_count - 1]);
  13044. GGML_ASSERT(kv_self.cells[kv_self.head].has_seq_id(dest_seq_id));
  13045. GGML_ASSERT(kv_self.cells[kv_self.head + cell_count - 1].has_seq_id(dest_seq_id));
  13046. // Cleanup
  13047. llama_batch_free(batch);
  13048. }
  13049. const uint32_t kv_size = kv_self.size;
  13050. const uint32_t kv_head = kv_self.head;
  13051. // For each layer, read the keys for each cell, one row is one cell, read as one contiguous blo
  13052. for (int il = 0; il < (int)n_layer; ++il) {
  13053. // Read type of key
  13054. int32_t k_type_i_ref;
  13055. memcpy(&k_type_i_ref, inp, sizeof(k_type_i_ref));
  13056. inp += sizeof(k_type_i_ref);
  13057. const int32_t k_type_i = (int32_t)kv_self.k_l[il]->type;
  13058. if (k_type_i != k_type_i_ref) {
  13059. llama_kv_cache_seq_rm(kv_self, dest_seq_id, -1, -1);
  13060. LLAMA_LOG_ERROR("%s: mismatched key type (%d != %d, layer %d)\n", __func__, k_type_i, k_type_i_ref, il);
  13061. return 0;
  13062. }
  13063. // Read row size of key
  13064. size_t k_size_row_ref;
  13065. memcpy(&k_size_row_ref, inp, sizeof(k_size_row_ref));
  13066. inp += sizeof(k_size_row_ref);
  13067. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  13068. if (k_size_row != k_size_row_ref) {
  13069. llama_kv_cache_seq_rm(kv_self, dest_seq_id, -1, -1);
  13070. LLAMA_LOG_ERROR("%s: mismatched key row size (%zu != %zu, layer %d)\n", __func__, k_size_row, k_size_row_ref, il);
  13071. return 0;
  13072. }
  13073. if (cell_count) {
  13074. // Read and set the keys for the whole cell range
  13075. ggml_backend_tensor_set(kv_self.k_l[il], inp, kv_head * k_size_row, cell_count * k_size_row);
  13076. inp += cell_count * k_size_row;
  13077. }
  13078. }
  13079. // For each layer, read the values for each cell (transposed)
  13080. for (int il = 0; il < (int)n_layer; ++il) {
  13081. // Read type of value
  13082. int32_t v_type_i_ref;
  13083. memcpy(&v_type_i_ref, inp, sizeof(v_type_i_ref));
  13084. inp += sizeof(v_type_i_ref);
  13085. const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
  13086. if (v_type_i != v_type_i_ref) {
  13087. llama_kv_cache_seq_rm(kv_self, dest_seq_id, -1, -1);
  13088. LLAMA_LOG_ERROR("%s: mismatched value type (%d != %d, layer %d)\n", __func__, v_type_i, v_type_i_ref, il);
  13089. return 0;
  13090. }
  13091. // Read element size of value
  13092. size_t v_size_el_ref;
  13093. memcpy(&v_size_el_ref, inp, sizeof(v_size_el_ref));
  13094. inp += sizeof(v_size_el_ref);
  13095. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  13096. if (v_size_el != v_size_el_ref) {
  13097. llama_kv_cache_seq_rm(kv_self, dest_seq_id, -1, -1);
  13098. LLAMA_LOG_ERROR("%s: mismatched value element size (%zu != %zu, layer %d)\n", __func__, v_size_el, v_size_el_ref, il);
  13099. return 0;
  13100. }
  13101. if (cell_count) {
  13102. // For each row in the transposed matrix, read the values for the whole cell range
  13103. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  13104. const size_t dst_offset = (kv_head + j * kv_size) * v_size_el;
  13105. ggml_backend_tensor_set(kv_self.v_l[il], inp, dst_offset, cell_count * v_size_el);
  13106. inp += cell_count * v_size_el;
  13107. }
  13108. }
  13109. }
  13110. const size_t nread = inp - src;
  13111. return nread;
  13112. }
  13113. 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) {
  13114. llama_file file(filepath, "wb");
  13115. file.write_u32(LLAMA_STATE_SEQ_MAGIC);
  13116. file.write_u32(LLAMA_STATE_SEQ_VERSION);
  13117. // save the prompt
  13118. file.write_u32((uint32_t)n_token_count);
  13119. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  13120. // save the context state using stream saving
  13121. llama_data_file_context data_ctx(&file);
  13122. llama_state_seq_get_data_internal(ctx, data_ctx, seq_id);
  13123. const size_t res = file.tell();
  13124. GGML_ASSERT(res == sizeof(uint32_t) * 3 + sizeof(llama_token) * n_token_count + data_ctx.get_size_written());
  13125. return res;
  13126. }
  13127. 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) {
  13128. llama_file file(filepath, "rb");
  13129. // version checks
  13130. {
  13131. const uint32_t magic = file.read_u32();
  13132. const uint32_t version = file.read_u32();
  13133. if (magic != LLAMA_STATE_SEQ_MAGIC || version != LLAMA_STATE_SEQ_VERSION) {
  13134. LLAMA_LOG_ERROR("%s: unknown (magic, version) for sequence state file: %08x, %08x\n", __func__, magic, version);
  13135. return 0;
  13136. }
  13137. }
  13138. // load the prompt
  13139. {
  13140. const uint32_t n_token_count = file.read_u32();
  13141. if (n_token_count > n_token_capacity) {
  13142. LLAMA_LOG_ERROR("%s: token count in sequence state file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  13143. return 0;
  13144. }
  13145. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  13146. *n_token_count_out = n_token_count;
  13147. }
  13148. // restore the context state
  13149. {
  13150. const size_t state_size = file.size - file.tell();
  13151. std::vector<uint8_t> state_data(state_size);
  13152. file.read_raw(state_data.data(), state_size);
  13153. const size_t nread = llama_state_seq_set_data(ctx, state_data.data(), dest_seq_id);
  13154. if (!nread) {
  13155. LLAMA_LOG_ERROR("%s: failed to restore sequence state\n", __func__);
  13156. return 0;
  13157. }
  13158. GGML_ASSERT(nread <= state_size);
  13159. GGML_ASSERT(nread + sizeof(uint32_t) * 3 + sizeof(llama_token) * *n_token_count_out == file.tell());
  13160. }
  13161. return file.tell();
  13162. }
  13163. 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) {
  13164. try {
  13165. return llama_state_seq_save_file_internal(ctx, filepath, seq_id, tokens, n_token_count);
  13166. } catch (const std::exception & err) {
  13167. LLAMA_LOG_ERROR("error saving sequence state file: %s\n", err.what());
  13168. return 0;
  13169. }
  13170. }
  13171. 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) {
  13172. try {
  13173. return llama_state_seq_load_file_internal(ctx, filepath, dest_seq_id, tokens_out, n_token_capacity, n_token_count_out);
  13174. } catch (const std::exception & err) {
  13175. LLAMA_LOG_ERROR("error loading sequence state file: %s\n", err.what());
  13176. return 0;
  13177. }
  13178. }
  13179. void llama_set_n_threads(struct llama_context * ctx, uint32_t n_threads, uint32_t n_threads_batch) {
  13180. ctx->cparams.n_threads = n_threads;
  13181. ctx->cparams.n_threads_batch = n_threads_batch;
  13182. }
  13183. void llama_set_abort_callback(struct llama_context * ctx, bool (*abort_callback)(void * data), void * abort_callback_data) {
  13184. ctx->abort_callback = abort_callback;
  13185. ctx->abort_callback_data = abort_callback_data;
  13186. }
  13187. void llama_set_causal_attn(struct llama_context * ctx, bool causal_attn) {
  13188. ctx->cparams.causal_attn = causal_attn;
  13189. }
  13190. struct llama_batch llama_batch_get_one(
  13191. llama_token * tokens,
  13192. int32_t n_tokens,
  13193. llama_pos pos_0,
  13194. llama_seq_id seq_id) {
  13195. return {
  13196. /*n_tokens =*/ n_tokens,
  13197. /*tokens =*/ tokens,
  13198. /*embd =*/ nullptr,
  13199. /*pos =*/ nullptr,
  13200. /*n_seq_id =*/ nullptr,
  13201. /*seq_id =*/ nullptr,
  13202. /*logits =*/ nullptr,
  13203. /*all_pos_0 =*/ pos_0,
  13204. /*all_pos_1 =*/ 1,
  13205. /*all_seq_id =*/ seq_id,
  13206. };
  13207. }
  13208. struct llama_batch llama_batch_init(int32_t n_tokens_alloc, int32_t embd, int32_t n_seq_max) {
  13209. llama_batch batch = { 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, 0, 0, 0, };
  13210. if (embd) {
  13211. batch.embd = (float *) malloc(sizeof(float) * n_tokens_alloc * embd);
  13212. } else {
  13213. batch.token = (llama_token *) malloc(sizeof(llama_token) * n_tokens_alloc);
  13214. }
  13215. batch.pos = (llama_pos *) malloc(sizeof(llama_pos) * n_tokens_alloc);
  13216. batch.n_seq_id = (int32_t *) malloc(sizeof(int32_t) * n_tokens_alloc);
  13217. batch.seq_id = (llama_seq_id **) malloc(sizeof(llama_seq_id *) * (n_tokens_alloc + 1));
  13218. for (int i = 0; i < n_tokens_alloc; ++i) {
  13219. batch.seq_id[i] = (llama_seq_id *) malloc(sizeof(llama_seq_id) * n_seq_max);
  13220. }
  13221. batch.seq_id[n_tokens_alloc] = nullptr;
  13222. batch.logits = (int8_t *) malloc(sizeof(int8_t) * n_tokens_alloc);
  13223. return batch;
  13224. }
  13225. void llama_batch_free(struct llama_batch batch) {
  13226. if (batch.token) free(batch.token);
  13227. if (batch.embd) free(batch.embd);
  13228. if (batch.pos) free(batch.pos);
  13229. if (batch.n_seq_id) free(batch.n_seq_id);
  13230. if (batch.seq_id) {
  13231. for (int i = 0; batch.seq_id[i] != nullptr; ++i) {
  13232. free(batch.seq_id[i]);
  13233. }
  13234. free(batch.seq_id);
  13235. }
  13236. if (batch.logits) free(batch.logits);
  13237. }
  13238. int32_t llama_decode(
  13239. struct llama_context * ctx,
  13240. struct llama_batch batch) {
  13241. const int ret = llama_decode_internal(*ctx, batch);
  13242. if (ret < 0) {
  13243. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  13244. }
  13245. return ret;
  13246. }
  13247. void llama_synchronize(struct llama_context * ctx) {
  13248. ggml_backend_sched_synchronize(ctx->sched);
  13249. // FIXME: if multiple single tokens are evaluated without a synchronization,
  13250. // the stats will be added to the prompt evaluation stats
  13251. // this should only happen when using batch size 1 to evaluate a batch
  13252. // add the evaluation to the stats
  13253. if (ctx->n_queued_tokens == 1) {
  13254. ctx->t_eval_us += ggml_time_us() - ctx->t_compute_start_us;
  13255. ctx->n_eval++;
  13256. } else if (ctx->n_queued_tokens > 1) {
  13257. ctx->t_p_eval_us += ggml_time_us() - ctx->t_compute_start_us;
  13258. ctx->n_p_eval += ctx->n_queued_tokens;
  13259. }
  13260. // get a more accurate load time, upon first eval
  13261. if (ctx->n_queued_tokens > 0 && !ctx->has_evaluated_once) {
  13262. ctx->t_load_us = ggml_time_us() - ctx->t_start_us;
  13263. ctx->has_evaluated_once = true;
  13264. }
  13265. ctx->n_queued_tokens = 0;
  13266. ctx->t_compute_start_us = 0;
  13267. }
  13268. float * llama_get_logits(struct llama_context * ctx) {
  13269. llama_synchronize(ctx);
  13270. return ctx->logits;
  13271. }
  13272. float * llama_get_logits_ith(struct llama_context * ctx, int32_t i) {
  13273. int32_t j = -1;
  13274. llama_synchronize(ctx);
  13275. try {
  13276. if (ctx->logits == nullptr) {
  13277. throw std::runtime_error("no logits");
  13278. }
  13279. if (i < 0) {
  13280. j = ctx->n_outputs + i;
  13281. if (j < 0) {
  13282. throw std::runtime_error(format("negative index out of range [0, %d)", ctx->n_outputs));
  13283. }
  13284. } else if ((size_t) i >= ctx->output_ids.size()) {
  13285. throw std::runtime_error(format("out of range [0, %lu)", ctx->output_ids.size()));
  13286. } else {
  13287. j = ctx->output_ids[i];
  13288. }
  13289. if (j < 0) {
  13290. throw std::runtime_error(format("batch.logits[%d] != true", i));
  13291. }
  13292. if (j >= ctx->n_outputs) {
  13293. // This should not happen
  13294. throw std::runtime_error(format("corrupt output buffer (j=%d, n_outputs=%d)", j, ctx->n_outputs));
  13295. }
  13296. return ctx->logits + j*ctx->model.hparams.n_vocab;
  13297. } catch (const std::exception & err) {
  13298. LLAMA_LOG_ERROR("%s: invalid logits id %d, reason: %s\n", __func__, i, err.what());
  13299. #ifndef NDEBUG
  13300. GGML_ASSERT(false);
  13301. #endif
  13302. return nullptr;
  13303. }
  13304. }
  13305. float * llama_get_embeddings(struct llama_context * ctx) {
  13306. llama_synchronize(ctx);
  13307. return ctx->embd;
  13308. }
  13309. float * llama_get_embeddings_ith(struct llama_context * ctx, int32_t i) {
  13310. int32_t j = -1;
  13311. llama_synchronize(ctx);
  13312. try {
  13313. if (ctx->embd == nullptr) {
  13314. throw std::runtime_error("no embeddings");
  13315. }
  13316. if (i < 0) {
  13317. j = ctx->n_outputs + i;
  13318. if (j < 0) {
  13319. throw std::runtime_error(format("negative index out of range [0, %d)", ctx->n_outputs));
  13320. }
  13321. } else if ((size_t) i >= ctx->output_ids.size()) {
  13322. throw std::runtime_error(format("out of range [0, %lu)", ctx->output_ids.size()));
  13323. } else {
  13324. j = ctx->output_ids[i];
  13325. }
  13326. if (j < 0) {
  13327. throw std::runtime_error(format("batch.logits[%d] != true", i));
  13328. }
  13329. if (j >= ctx->n_outputs) {
  13330. // This should not happen
  13331. throw std::runtime_error(format("corrupt output buffer (j=%d, n_outputs=%d)", j, ctx->n_outputs));
  13332. }
  13333. return ctx->embd + j*ctx->model.hparams.n_embd;
  13334. } catch (const std::exception & err) {
  13335. LLAMA_LOG_ERROR("%s: invalid embeddings id %d, reason: %s\n", __func__, i, err.what());
  13336. #ifndef NDEBUG
  13337. GGML_ASSERT(false);
  13338. #endif
  13339. return nullptr;
  13340. }
  13341. }
  13342. float * llama_get_embeddings_seq(struct llama_context * ctx, llama_seq_id seq_id) {
  13343. llama_synchronize(ctx);
  13344. auto it = ctx->embd_seq.find(seq_id);
  13345. if (it == ctx->embd_seq.end()) {
  13346. return nullptr;
  13347. }
  13348. return it->second.data();
  13349. }
  13350. const char * llama_token_get_text(const struct llama_model * model, llama_token token) {
  13351. GGML_ASSERT(model->vocab.type != LLAMA_VOCAB_TYPE_NONE);
  13352. return model->vocab.id_to_token[token].text.c_str();
  13353. }
  13354. float llama_token_get_score(const struct llama_model * model, llama_token token) {
  13355. GGML_ASSERT(model->vocab.type != LLAMA_VOCAB_TYPE_NONE);
  13356. return model->vocab.id_to_token[token].score;
  13357. }
  13358. llama_token_type llama_token_get_type(const struct llama_model * model, llama_token token) {
  13359. GGML_ASSERT(model->vocab.type != LLAMA_VOCAB_TYPE_NONE);
  13360. return model->vocab.id_to_token[token].type;
  13361. }
  13362. llama_token llama_token_bos(const struct llama_model * model) {
  13363. return model->vocab.special_bos_id;
  13364. }
  13365. llama_token llama_token_eos(const struct llama_model * model) {
  13366. return model->vocab.special_eos_id;
  13367. }
  13368. llama_token llama_token_nl(const struct llama_model * model) {
  13369. return model->vocab.linefeed_id;
  13370. }
  13371. int32_t llama_add_bos_token(const struct llama_model * model) {
  13372. return model->vocab.special_add_bos;
  13373. }
  13374. int32_t llama_add_eos_token(const struct llama_model * model) {
  13375. return model->vocab.special_add_eos;
  13376. }
  13377. llama_token llama_token_prefix(const struct llama_model * model) {
  13378. return model->vocab.special_prefix_id;
  13379. }
  13380. llama_token llama_token_middle(const struct llama_model * model) {
  13381. return model->vocab.special_middle_id;
  13382. }
  13383. llama_token llama_token_suffix(const struct llama_model * model) {
  13384. return model->vocab.special_suffix_id;
  13385. }
  13386. llama_token llama_token_eot(const struct llama_model * model) {
  13387. return model->vocab.special_eot_id;
  13388. }
  13389. int32_t llama_tokenize(
  13390. const struct llama_model * model,
  13391. const char * text,
  13392. int32_t text_len,
  13393. llama_token * tokens,
  13394. int32_t n_tokens_max,
  13395. bool add_bos,
  13396. bool special) {
  13397. auto res = llama_tokenize_internal(model->vocab, std::string(text, text_len), add_bos, special);
  13398. if (n_tokens_max < (int) res.size()) {
  13399. // LLAMA_LOG_ERROR("%s: too many tokens\n", __func__);
  13400. return -((int) res.size());
  13401. }
  13402. for (size_t i = 0; i < res.size(); i++) {
  13403. tokens[i] = res[i];
  13404. }
  13405. return res.size();
  13406. }
  13407. static std::string llama_decode_text(const std::string & text) {
  13408. std::string decoded_text;
  13409. auto unicode_sequences = unicode_cpts_from_utf8(text);
  13410. for (auto & unicode_sequence : unicode_sequences) {
  13411. decoded_text += unicode_utf8_to_byte(unicode_cpt_to_utf8(unicode_sequence));
  13412. }
  13413. return decoded_text;
  13414. }
  13415. // does not write null-terminator to buf
  13416. int32_t llama_token_to_piece(const struct llama_model * model, llama_token token, char * buf, int32_t length) {
  13417. if (0 <= token && token < llama_n_vocab(model)) {
  13418. switch (llama_vocab_get_type(model->vocab)) {
  13419. case LLAMA_VOCAB_TYPE_WPM:
  13420. case LLAMA_VOCAB_TYPE_SPM: {
  13421. // NOTE: we accept all unsupported token types,
  13422. // suppressing them like CONTROL tokens.
  13423. if (llama_is_normal_token(model->vocab, token)) {
  13424. std::string result = model->vocab.id_to_token[token].text;
  13425. llama_unescape_whitespace(result);
  13426. if (length < (int) result.length()) {
  13427. return -(int) result.length();
  13428. }
  13429. memcpy(buf, result.c_str(), result.length());
  13430. return result.length();
  13431. } else if (llama_is_user_defined_token(model->vocab, token)) {
  13432. std::string result = model->vocab.id_to_token[token].text;
  13433. if (length < (int) result.length()) {
  13434. return -(int) result.length();
  13435. }
  13436. memcpy(buf, result.c_str(), result.length());
  13437. return result.length();
  13438. } else if (llama_is_unknown_token(model->vocab, token)) { // NOLINT
  13439. if (length < 3) {
  13440. return -3;
  13441. }
  13442. memcpy(buf, "\xe2\x96\x85", 3);
  13443. return 3;
  13444. } else if (llama_is_control_token(model->vocab, token)) {
  13445. ;
  13446. } else if (llama_is_byte_token(model->vocab, token)) {
  13447. if (length < 1) {
  13448. return -1;
  13449. }
  13450. buf[0] = llama_token_to_byte(model->vocab, token);
  13451. return 1;
  13452. }
  13453. break;
  13454. }
  13455. case LLAMA_VOCAB_TYPE_BPE: {
  13456. // NOTE: we accept all unsupported token types,
  13457. // suppressing them like CONTROL tokens.
  13458. if (llama_is_normal_token(model->vocab, token)) {
  13459. std::string result = model->vocab.id_to_token[token].text;
  13460. result = llama_decode_text(result);
  13461. if (length < (int) result.length()) {
  13462. return -(int) result.length();
  13463. }
  13464. memcpy(buf, result.c_str(), result.length());
  13465. return result.length();
  13466. } else if (llama_is_user_defined_token(model->vocab, token)) {
  13467. std::string result = model->vocab.id_to_token[token].text;
  13468. if (length < (int) result.length()) {
  13469. return -(int) result.length();
  13470. }
  13471. memcpy(buf, result.c_str(), result.length());
  13472. return result.length();
  13473. } else if (llama_is_control_token(model->vocab, token)) {
  13474. ;
  13475. }
  13476. break;
  13477. }
  13478. default:
  13479. GGML_ASSERT(false);
  13480. }
  13481. }
  13482. return 0;
  13483. }
  13484. // trim whitespace from the beginning and end of a string
  13485. static std::string trim(const std::string & str) {
  13486. size_t start = 0;
  13487. size_t end = str.size();
  13488. while (start < end && isspace(str[start])) {
  13489. start += 1;
  13490. }
  13491. while (end > start && isspace(str[end - 1])) {
  13492. end -= 1;
  13493. }
  13494. return str.substr(start, end - start);
  13495. }
  13496. // Simple version of "llama_apply_chat_template" that only works with strings
  13497. // This function uses heuristic checks to determine commonly used template. It is not a jinja parser.
  13498. static int32_t llama_chat_apply_template_internal(
  13499. const std::string & tmpl,
  13500. const std::vector<const llama_chat_message *> & chat,
  13501. std::string & dest, bool add_ass) {
  13502. // Taken from the research: https://github.com/ggerganov/llama.cpp/issues/5527
  13503. std::stringstream ss;
  13504. if (tmpl == "chatml" || tmpl.find("<|im_start|>") != std::string::npos) {
  13505. // chatml template
  13506. for (auto message : chat) {
  13507. ss << "<|im_start|>" << message->role << "\n" << message->content << "<|im_end|>\n";
  13508. }
  13509. if (add_ass) {
  13510. ss << "<|im_start|>assistant\n";
  13511. }
  13512. } else if (tmpl == "llama2" || tmpl.find("[INST]") != std::string::npos) {
  13513. // llama2 template and its variants
  13514. // [variant] support system message
  13515. bool support_system_message = tmpl.find("<<SYS>>") != std::string::npos;
  13516. // [variant] space before + after response
  13517. bool space_around_response = tmpl.find("' ' + eos_token") != std::string::npos;
  13518. // [variant] add BOS inside history
  13519. bool add_bos_inside_history = tmpl.find("bos_token + '[INST]") != std::string::npos;
  13520. // [variant] trim spaces from the input message
  13521. bool strip_message = tmpl.find("content.strip()") != std::string::npos;
  13522. // construct the prompt
  13523. bool is_inside_turn = true; // skip BOS at the beginning
  13524. ss << "[INST] ";
  13525. for (auto message : chat) {
  13526. std::string content = strip_message ? trim(message->content) : message->content;
  13527. std::string role(message->role);
  13528. if (!is_inside_turn) {
  13529. is_inside_turn = true;
  13530. ss << (add_bos_inside_history ? "<s>[INST] " : "[INST] ");
  13531. }
  13532. if (role == "system") {
  13533. if (support_system_message) {
  13534. ss << "<<SYS>>\n" << content << "\n<</SYS>>\n\n";
  13535. } else {
  13536. // if the model does not support system message, we still include it in the first message, but without <<SYS>>
  13537. ss << content << "\n";
  13538. }
  13539. } else if (role == "user") {
  13540. ss << content << " [/INST]";
  13541. } else {
  13542. ss << (space_around_response ? " " : "") << content << (space_around_response ? " " : "") << "</s>";
  13543. is_inside_turn = false;
  13544. }
  13545. }
  13546. // llama2 templates seem to not care about "add_generation_prompt"
  13547. } else if (tmpl == "zephyr" || tmpl.find("<|user|>") != std::string::npos) {
  13548. // zephyr template
  13549. for (auto message : chat) {
  13550. ss << "<|" << message->role << "|>" << "\n" << message->content << "<|endoftext|>\n";
  13551. }
  13552. if (add_ass) {
  13553. ss << "<|assistant|>\n";
  13554. }
  13555. } else if (tmpl == "monarch" || tmpl.find("bos_token + message['role']") != std::string::npos) {
  13556. // mlabonne/AlphaMonarch-7B template (the <s> is included inside history)
  13557. for (auto message : chat) {
  13558. std::string bos = (message == chat.front()) ? "" : "<s>"; // skip BOS for first message
  13559. ss << bos << message->role << "\n" << message->content << "</s>\n";
  13560. }
  13561. if (add_ass) {
  13562. ss << "<s>assistant\n";
  13563. }
  13564. } else if (tmpl == "gemma" || tmpl.find("<start_of_turn>") != std::string::npos) {
  13565. // google/gemma-7b-it
  13566. std::string system_prompt = "";
  13567. for (auto message : chat) {
  13568. std::string role(message->role);
  13569. if (role == "system") {
  13570. // there is no system message for gemma, but we will merge it with user prompt, so nothing is broken
  13571. system_prompt = trim(message->content);
  13572. continue;
  13573. }
  13574. // in gemma, "assistant" is "model"
  13575. role = role == "assistant" ? "model" : message->role;
  13576. ss << "<start_of_turn>" << role << "\n";
  13577. if (!system_prompt.empty() && role != "model") {
  13578. ss << system_prompt << "\n\n";
  13579. system_prompt = "";
  13580. }
  13581. ss << trim(message->content) << "<end_of_turn>\n";
  13582. }
  13583. if (add_ass) {
  13584. ss << "<start_of_turn>model\n";
  13585. }
  13586. } else if (tmpl == "orion" || tmpl.find("'\\n\\nAssistant: ' + eos_token") != std::string::npos) {
  13587. // OrionStarAI/Orion-14B-Chat
  13588. std::string system_prompt = "";
  13589. for (auto message : chat) {
  13590. std::string role(message->role);
  13591. if (role == "system") {
  13592. // there is no system message support, we will merge it with user prompt
  13593. system_prompt = message->content;
  13594. continue;
  13595. } else if (role == "user") {
  13596. ss << "Human: ";
  13597. if (!system_prompt.empty()) {
  13598. ss << system_prompt << "\n\n";
  13599. system_prompt = "";
  13600. }
  13601. ss << message->content << "\n\nAssistant: </s>";
  13602. } else {
  13603. ss << message->content << "</s>";
  13604. }
  13605. }
  13606. } else if (tmpl == "openchat" || tmpl.find("GPT4 Correct ") != std::string::npos) {
  13607. // openchat/openchat-3.5-0106,
  13608. for (auto message : chat) {
  13609. std::string role(message->role);
  13610. if (role == "system") {
  13611. ss << message->content << "<|end_of_turn|>";
  13612. } else {
  13613. role[0] = toupper(role[0]);
  13614. ss << "GPT4 Correct " << role << ": " << message->content << "<|end_of_turn|>";
  13615. }
  13616. }
  13617. if (add_ass) {
  13618. ss << "GPT4 Correct Assistant:";
  13619. }
  13620. } else if (tmpl == "vicuna" || tmpl == "vicuna-orca" || (tmpl.find("USER: ") != std::string::npos && tmpl.find("ASSISTANT: ") != std::string::npos)) {
  13621. // eachadea/vicuna-13b-1.1 (and Orca variant)
  13622. for (auto message : chat) {
  13623. std::string role(message->role);
  13624. if (role == "system") {
  13625. // Orca-Vicuna variant uses a system prefix
  13626. if (tmpl == "vicuna-orca" || tmpl.find("SYSTEM: ") != std::string::npos) {
  13627. ss << "SYSTEM: " << message->content << "\n";
  13628. } else {
  13629. ss << message->content << "\n\n";
  13630. }
  13631. } else if (role == "user") {
  13632. ss << "USER: " << message->content << "\n";
  13633. } else if (role == "assistant") {
  13634. ss << "ASSISTANT: " << message->content << "</s>\n";
  13635. }
  13636. }
  13637. if (add_ass) {
  13638. ss << "ASSISTANT:";
  13639. }
  13640. } else if (tmpl == "deepseek" || (tmpl.find("### Instruction:") != std::string::npos && tmpl.find("<|EOT|>") != std::string::npos)) {
  13641. // deepseek-ai/deepseek-coder-33b-instruct
  13642. for (auto message : chat) {
  13643. std::string role(message->role);
  13644. if (role == "system") {
  13645. ss << message->content;
  13646. } else if (role == "user") {
  13647. ss << "### Instruction:\n" << message->content << "\n";
  13648. } else if (role == "assistant") {
  13649. ss << "### Response:\n" << message->content << "\n<|EOT|>\n";
  13650. }
  13651. }
  13652. if (add_ass) {
  13653. ss << "### Response:\n";
  13654. }
  13655. } else {
  13656. // template not supported
  13657. return -1;
  13658. }
  13659. dest = ss.str();
  13660. return dest.size();
  13661. }
  13662. LLAMA_API int32_t llama_chat_apply_template(
  13663. const struct llama_model * model,
  13664. const char * tmpl,
  13665. const struct llama_chat_message * chat,
  13666. size_t n_msg,
  13667. bool add_ass,
  13668. char * buf,
  13669. int32_t length) {
  13670. std::string curr_tmpl(tmpl == nullptr ? "" : tmpl);
  13671. if (tmpl == nullptr) {
  13672. GGML_ASSERT(model != nullptr);
  13673. // load template from model
  13674. std::vector<char> model_template(2048, 0); // longest known template is about 1200 bytes
  13675. std::string template_key = "tokenizer.chat_template";
  13676. int32_t res = llama_model_meta_val_str(model, template_key.c_str(), model_template.data(), model_template.size());
  13677. if (res < 0) {
  13678. // worst case: there is no information about template, we will use chatml by default
  13679. curr_tmpl = "chatml"; // see llama_chat_apply_template_internal
  13680. } else {
  13681. curr_tmpl = std::string(model_template.data(), model_template.size());
  13682. }
  13683. }
  13684. // format the chat to string
  13685. std::vector<const llama_chat_message *> chat_vec;
  13686. chat_vec.resize(n_msg);
  13687. for (size_t i = 0; i < n_msg; i++) {
  13688. chat_vec[i] = &chat[i];
  13689. }
  13690. std::string formatted_chat;
  13691. int32_t res = llama_chat_apply_template_internal(curr_tmpl, chat_vec, formatted_chat, add_ass);
  13692. if (res < 0) {
  13693. return res;
  13694. }
  13695. if (buf && length > 0) {
  13696. strncpy(buf, formatted_chat.c_str(), length);
  13697. }
  13698. return res;
  13699. }
  13700. LLAMA_API int llama_split_path(char * split_path, size_t maxlen, const char * path_prefix, int split_no, int split_count) {
  13701. static const char * const SPLIT_PATH_FORMAT = "%s-%05d-of-%05d.gguf";
  13702. if (snprintf(split_path, maxlen, SPLIT_PATH_FORMAT, path_prefix, split_no + 1, split_count)) {
  13703. return strlen(split_path);
  13704. }
  13705. return 0;
  13706. }
  13707. int llama_split_prefix(char * dest, size_t maxlen, const char * split_path, int split_no, int split_count) {
  13708. std::string str_split_path(split_path);
  13709. char postfix[32];
  13710. snprintf(postfix, 32, "-%05d-of-%05d.gguf", split_no + 1, split_count);
  13711. std::string str_postfix(postfix);
  13712. // check if dest ends with postfix
  13713. int size_prefix = str_split_path.size() - str_postfix.size();
  13714. if (size_prefix > 0 && str_split_path.find(str_postfix, size_prefix) != std::string::npos) {
  13715. snprintf(dest, std::min((size_t) size_prefix + 1, maxlen), "%s", split_path);
  13716. return size_prefix;
  13717. }
  13718. return 0;
  13719. }
  13720. struct llama_timings llama_get_timings(struct llama_context * ctx) {
  13721. struct llama_timings result = {
  13722. /*.t_start_ms =*/ 1e-3 * ctx->t_start_us,
  13723. /*.t_end_ms =*/ 1.00 * ggml_time_ms(),
  13724. /*.t_load_ms =*/ 1e-3 * ctx->t_load_us,
  13725. /*.t_sample_ms =*/ 1e-3 * ctx->t_sample_us,
  13726. /*.t_p_eval_ms =*/ 1e-3 * ctx->t_p_eval_us,
  13727. /*.t_eval_ms =*/ 1e-3 * ctx->t_eval_us,
  13728. /*.n_sample =*/ std::max(1, ctx->n_sample),
  13729. /*.n_p_eval =*/ std::max(1, ctx->n_p_eval),
  13730. /*.n_eval =*/ std::max(1, ctx->n_eval),
  13731. };
  13732. return result;
  13733. }
  13734. void llama_print_timings(struct llama_context * ctx) {
  13735. const llama_timings timings = llama_get_timings(ctx);
  13736. LLAMA_LOG_INFO("\n");
  13737. LLAMA_LOG_INFO("%s: load time = %10.2f ms\n", __func__, timings.t_load_ms);
  13738. LLAMA_LOG_INFO("%s: sample time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  13739. __func__, timings.t_sample_ms, timings.n_sample, timings.t_sample_ms / timings.n_sample, 1e3 / timings.t_sample_ms * timings.n_sample);
  13740. LLAMA_LOG_INFO("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  13741. __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);
  13742. LLAMA_LOG_INFO("%s: eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  13743. __func__, timings.t_eval_ms, timings.n_eval, timings.t_eval_ms / timings.n_eval, 1e3 / timings.t_eval_ms * timings.n_eval);
  13744. 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));
  13745. }
  13746. void llama_reset_timings(struct llama_context * ctx) {
  13747. ctx->t_start_us = ggml_time_us();
  13748. ctx->t_sample_us = ctx->n_sample = 0;
  13749. ctx->t_eval_us = ctx->n_eval = 0;
  13750. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  13751. }
  13752. const char * llama_print_system_info(void) {
  13753. static std::string s;
  13754. s = "";
  13755. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  13756. s += "AVX_VNNI = " + std::to_string(ggml_cpu_has_avx_vnni()) + " | ";
  13757. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  13758. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  13759. s += "AVX512_VBMI = " + std::to_string(ggml_cpu_has_avx512_vbmi()) + " | ";
  13760. s += "AVX512_VNNI = " + std::to_string(ggml_cpu_has_avx512_vnni()) + " | ";
  13761. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  13762. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  13763. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  13764. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  13765. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  13766. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  13767. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  13768. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  13769. s += "SSSE3 = " + std::to_string(ggml_cpu_has_ssse3()) + " | ";
  13770. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  13771. s += "MATMUL_INT8 = " + std::to_string(ggml_cpu_has_matmul_int8()) + " | ";
  13772. return s.c_str();
  13773. }
  13774. void llama_dump_timing_info_yaml(FILE * stream, const llama_context * ctx) {
  13775. fprintf(stream, "\n");
  13776. fprintf(stream, "###########\n");
  13777. fprintf(stream, "# Timings #\n");
  13778. fprintf(stream, "###########\n");
  13779. fprintf(stream, "\n");
  13780. fprintf(stream, "mst_eval: %.2f # ms / token during generation\n",
  13781. 1.0e-3 * ctx->t_eval_us / ctx->n_eval);
  13782. fprintf(stream, "mst_p_eval: %.2f # ms / token during prompt processing\n",
  13783. 1.0e-3 * ctx->t_p_eval_us / ctx->n_p_eval);
  13784. fprintf(stream, "mst_sample: %.2f # ms / token during sampling\n",
  13785. 1.0e-3 * ctx->t_sample_us / ctx->n_sample);
  13786. fprintf(stream, "n_eval: %d # number of tokens generated (excluding the first one)\n", ctx->n_eval);
  13787. fprintf(stream, "n_p_eval: %d # number of tokens processed in batches at the beginning\n", ctx->n_p_eval);
  13788. fprintf(stream, "n_sample: %d # number of sampled tokens\n", ctx->n_sample);
  13789. fprintf(stream, "t_eval_us: %" PRId64 " # total microseconds spent generating tokens\n", ctx->t_eval_us);
  13790. fprintf(stream, "t_load_us: %" PRId64 " # total microseconds spent loading the model\n", ctx->t_load_us);
  13791. fprintf(stream, "t_p_eval_us: %" PRId64 " # total microseconds spent prompt processing\n", ctx->t_p_eval_us);
  13792. fprintf(stream, "t_sample_us: %" PRId64 " # total microseconds spent sampling\n", ctx->t_sample_us);
  13793. fprintf(stream, "ts_eval: %.2f # tokens / second during generation\n",
  13794. 1.0e6 * ctx->n_eval / ctx->t_eval_us);
  13795. fprintf(stream, "ts_p_eval: %.2f # tokens / second during prompt processing\n",
  13796. 1.0e6 * ctx->n_p_eval / ctx->t_p_eval_us);
  13797. fprintf(stream, "ts_sample: %.2f # tokens / second during sampling\n",
  13798. 1.0e6 * ctx->n_sample / ctx->t_sample_us);
  13799. }
  13800. // For internal test use
  13801. const std::vector<std::pair<std::string, struct ggml_tensor *>> & llama_internal_get_tensor_map(
  13802. struct llama_context * ctx
  13803. ) {
  13804. return ctx->model.tensors_by_name;
  13805. }
  13806. void llama_log_set(ggml_log_callback log_callback, void * user_data) {
  13807. g_state.log_callback = log_callback ? log_callback : llama_log_callback_default;
  13808. g_state.log_callback_user_data = user_data;
  13809. #ifdef GGML_USE_METAL
  13810. ggml_backend_metal_log_set_callback(g_state.log_callback, g_state.log_callback_user_data);
  13811. #endif
  13812. }
  13813. static void llama_log_internal_v(ggml_log_level level, const char * format, va_list args) {
  13814. va_list args_copy;
  13815. va_copy(args_copy, args);
  13816. char buffer[128];
  13817. int len = vsnprintf(buffer, 128, format, args);
  13818. if (len < 128) {
  13819. g_state.log_callback(level, buffer, g_state.log_callback_user_data);
  13820. } else {
  13821. char* buffer2 = new char[len+1];
  13822. vsnprintf(buffer2, len+1, format, args_copy);
  13823. buffer2[len] = 0;
  13824. g_state.log_callback(level, buffer2, g_state.log_callback_user_data);
  13825. delete[] buffer2;
  13826. }
  13827. va_end(args_copy);
  13828. }
  13829. static void llama_log_internal(ggml_log_level level, const char * format, ...) {
  13830. va_list args;
  13831. va_start(args, format);
  13832. llama_log_internal_v(level, format, args);
  13833. va_end(args);
  13834. }
  13835. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data) {
  13836. (void) level;
  13837. (void) user_data;
  13838. fputs(text, stderr);
  13839. fflush(stderr);
  13840. }