llama.cpp 663 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836
  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 16
  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_DBRX,
  199. LLM_ARCH_UNKNOWN,
  200. };
  201. static const std::map<llm_arch, const char *> LLM_ARCH_NAMES = {
  202. { LLM_ARCH_LLAMA, "llama" },
  203. { LLM_ARCH_FALCON, "falcon" },
  204. { LLM_ARCH_GROK, "grok" },
  205. { LLM_ARCH_GPT2, "gpt2" },
  206. { LLM_ARCH_GPTJ, "gptj" },
  207. { LLM_ARCH_GPTNEOX, "gptneox" },
  208. { LLM_ARCH_MPT, "mpt" },
  209. { LLM_ARCH_BAICHUAN, "baichuan" },
  210. { LLM_ARCH_STARCODER, "starcoder" },
  211. { LLM_ARCH_PERSIMMON, "persimmon" },
  212. { LLM_ARCH_REFACT, "refact" },
  213. { LLM_ARCH_BERT, "bert" },
  214. { LLM_ARCH_NOMIC_BERT, "nomic-bert" },
  215. { LLM_ARCH_BLOOM, "bloom" },
  216. { LLM_ARCH_STABLELM, "stablelm" },
  217. { LLM_ARCH_QWEN, "qwen" },
  218. { LLM_ARCH_QWEN2, "qwen2" },
  219. { LLM_ARCH_PHI2, "phi2" },
  220. { LLM_ARCH_PLAMO, "plamo" },
  221. { LLM_ARCH_CODESHELL, "codeshell" },
  222. { LLM_ARCH_ORION, "orion" },
  223. { LLM_ARCH_INTERNLM2, "internlm2" },
  224. { LLM_ARCH_MINICPM, "minicpm" },
  225. { LLM_ARCH_GEMMA, "gemma" },
  226. { LLM_ARCH_STARCODER2, "starcoder2" },
  227. { LLM_ARCH_MAMBA, "mamba" },
  228. { LLM_ARCH_XVERSE, "xverse" },
  229. { LLM_ARCH_COMMAND_R, "command-r" },
  230. { LLM_ARCH_DBRX, "dbrx" },
  231. { LLM_ARCH_UNKNOWN, "(unknown)" },
  232. };
  233. enum llm_kv {
  234. LLM_KV_GENERAL_ARCHITECTURE,
  235. LLM_KV_GENERAL_QUANTIZATION_VERSION,
  236. LLM_KV_GENERAL_ALIGNMENT,
  237. LLM_KV_GENERAL_NAME,
  238. LLM_KV_GENERAL_AUTHOR,
  239. LLM_KV_GENERAL_VERSION,
  240. LLM_KV_GENERAL_URL,
  241. LLM_KV_GENERAL_DESCRIPTION,
  242. LLM_KV_GENERAL_LICENSE,
  243. LLM_KV_GENERAL_SOURCE_URL,
  244. LLM_KV_GENERAL_SOURCE_HF_REPO,
  245. LLM_KV_VOCAB_SIZE,
  246. LLM_KV_CONTEXT_LENGTH,
  247. LLM_KV_EMBEDDING_LENGTH,
  248. LLM_KV_BLOCK_COUNT,
  249. LLM_KV_FEED_FORWARD_LENGTH,
  250. LLM_KV_USE_PARALLEL_RESIDUAL,
  251. LLM_KV_TENSOR_DATA_LAYOUT,
  252. LLM_KV_EXPERT_COUNT,
  253. LLM_KV_EXPERT_USED_COUNT,
  254. LLM_KV_POOLING_TYPE,
  255. LLM_KV_LOGIT_SCALE,
  256. LLM_KV_ATTENTION_HEAD_COUNT,
  257. LLM_KV_ATTENTION_HEAD_COUNT_KV,
  258. LLM_KV_ATTENTION_MAX_ALIBI_BIAS,
  259. LLM_KV_ATTENTION_CLAMP_KQV,
  260. LLM_KV_ATTENTION_KEY_LENGTH,
  261. LLM_KV_ATTENTION_VALUE_LENGTH,
  262. LLM_KV_ATTENTION_LAYERNORM_EPS,
  263. LLM_KV_ATTENTION_LAYERNORM_RMS_EPS,
  264. LLM_KV_ATTENTION_CAUSAL,
  265. LLM_KV_ROPE_DIMENSION_COUNT,
  266. LLM_KV_ROPE_FREQ_BASE,
  267. LLM_KV_ROPE_SCALE_LINEAR,
  268. LLM_KV_ROPE_SCALING_TYPE,
  269. LLM_KV_ROPE_SCALING_FACTOR,
  270. LLM_KV_ROPE_SCALING_ORIG_CTX_LEN,
  271. LLM_KV_ROPE_SCALING_FINETUNED,
  272. LLM_KV_SPLIT_NO,
  273. LLM_KV_SPLIT_COUNT,
  274. LLM_KV_SPLIT_TENSORS_COUNT,
  275. LLM_KV_SSM_INNER_SIZE,
  276. LLM_KV_SSM_CONV_KERNEL,
  277. LLM_KV_SSM_STATE_SIZE,
  278. LLM_KV_SSM_TIME_STEP_RANK,
  279. LLM_KV_TOKENIZER_MODEL,
  280. LLM_KV_TOKENIZER_LIST,
  281. LLM_KV_TOKENIZER_TOKEN_TYPE,
  282. LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT,
  283. LLM_KV_TOKENIZER_SCORES,
  284. LLM_KV_TOKENIZER_MERGES,
  285. LLM_KV_TOKENIZER_BOS_ID,
  286. LLM_KV_TOKENIZER_EOS_ID,
  287. LLM_KV_TOKENIZER_UNK_ID,
  288. LLM_KV_TOKENIZER_SEP_ID,
  289. LLM_KV_TOKENIZER_PAD_ID,
  290. LLM_KV_TOKENIZER_CLS_ID,
  291. LLM_KV_TOKENIZER_MASK_ID,
  292. LLM_KV_TOKENIZER_ADD_BOS,
  293. LLM_KV_TOKENIZER_ADD_EOS,
  294. LLM_KV_TOKENIZER_ADD_PREFIX,
  295. LLM_KV_TOKENIZER_HF_JSON,
  296. LLM_KV_TOKENIZER_RWKV,
  297. };
  298. static const std::map<llm_kv, const char *> LLM_KV_NAMES = {
  299. { LLM_KV_GENERAL_ARCHITECTURE, "general.architecture" },
  300. { LLM_KV_GENERAL_QUANTIZATION_VERSION, "general.quantization_version" },
  301. { LLM_KV_GENERAL_ALIGNMENT, "general.alignment" },
  302. { LLM_KV_GENERAL_NAME, "general.name" },
  303. { LLM_KV_GENERAL_AUTHOR, "general.author" },
  304. { LLM_KV_GENERAL_VERSION, "general.version" },
  305. { LLM_KV_GENERAL_URL, "general.url" },
  306. { LLM_KV_GENERAL_DESCRIPTION, "general.description" },
  307. { LLM_KV_GENERAL_LICENSE, "general.license" },
  308. { LLM_KV_GENERAL_SOURCE_URL, "general.source.url" },
  309. { LLM_KV_GENERAL_SOURCE_HF_REPO, "general.source.huggingface.repository" },
  310. { LLM_KV_VOCAB_SIZE, "%s.vocab_size" },
  311. { LLM_KV_CONTEXT_LENGTH, "%s.context_length" },
  312. { LLM_KV_EMBEDDING_LENGTH, "%s.embedding_length" },
  313. { LLM_KV_BLOCK_COUNT, "%s.block_count" },
  314. { LLM_KV_FEED_FORWARD_LENGTH, "%s.feed_forward_length" },
  315. { LLM_KV_USE_PARALLEL_RESIDUAL, "%s.use_parallel_residual" },
  316. { LLM_KV_TENSOR_DATA_LAYOUT, "%s.tensor_data_layout" },
  317. { LLM_KV_EXPERT_COUNT, "%s.expert_count" },
  318. { LLM_KV_EXPERT_USED_COUNT, "%s.expert_used_count" },
  319. { LLM_KV_POOLING_TYPE , "%s.pooling_type" },
  320. { LLM_KV_LOGIT_SCALE, "%s.logit_scale" },
  321. { LLM_KV_ATTENTION_HEAD_COUNT, "%s.attention.head_count" },
  322. { LLM_KV_ATTENTION_HEAD_COUNT_KV, "%s.attention.head_count_kv" },
  323. { LLM_KV_ATTENTION_MAX_ALIBI_BIAS, "%s.attention.max_alibi_bias" },
  324. { LLM_KV_ATTENTION_CLAMP_KQV, "%s.attention.clamp_kqv" },
  325. { LLM_KV_ATTENTION_KEY_LENGTH, "%s.attention.key_length" },
  326. { LLM_KV_ATTENTION_VALUE_LENGTH, "%s.attention.value_length" },
  327. { LLM_KV_ATTENTION_LAYERNORM_EPS, "%s.attention.layer_norm_epsilon" },
  328. { LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, "%s.attention.layer_norm_rms_epsilon" },
  329. { LLM_KV_ATTENTION_CAUSAL, "%s.attention.causal" },
  330. { LLM_KV_ROPE_DIMENSION_COUNT, "%s.rope.dimension_count" },
  331. { LLM_KV_ROPE_FREQ_BASE, "%s.rope.freq_base" },
  332. { LLM_KV_ROPE_SCALE_LINEAR, "%s.rope.scale_linear" },
  333. { LLM_KV_ROPE_SCALING_TYPE, "%s.rope.scaling.type" },
  334. { LLM_KV_ROPE_SCALING_FACTOR, "%s.rope.scaling.factor" },
  335. { LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, "%s.rope.scaling.original_context_length" },
  336. { LLM_KV_ROPE_SCALING_FINETUNED, "%s.rope.scaling.finetuned" },
  337. { LLM_KV_SPLIT_NO, "split.no" },
  338. { LLM_KV_SPLIT_COUNT, "split.count" },
  339. { LLM_KV_SPLIT_TENSORS_COUNT, "split.tensors.count" },
  340. { LLM_KV_SSM_CONV_KERNEL, "%s.ssm.conv_kernel" },
  341. { LLM_KV_SSM_INNER_SIZE, "%s.ssm.inner_size" },
  342. { LLM_KV_SSM_STATE_SIZE, "%s.ssm.state_size" },
  343. { LLM_KV_SSM_TIME_STEP_RANK, "%s.ssm.time_step_rank" },
  344. { LLM_KV_TOKENIZER_MODEL, "tokenizer.ggml.model" },
  345. { LLM_KV_TOKENIZER_LIST, "tokenizer.ggml.tokens" },
  346. { LLM_KV_TOKENIZER_TOKEN_TYPE, "tokenizer.ggml.token_type" },
  347. { LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, "tokenizer.ggml.token_type_count" },
  348. { LLM_KV_TOKENIZER_SCORES, "tokenizer.ggml.scores" },
  349. { LLM_KV_TOKENIZER_MERGES, "tokenizer.ggml.merges" },
  350. { LLM_KV_TOKENIZER_BOS_ID, "tokenizer.ggml.bos_token_id" },
  351. { LLM_KV_TOKENIZER_EOS_ID, "tokenizer.ggml.eos_token_id" },
  352. { LLM_KV_TOKENIZER_UNK_ID, "tokenizer.ggml.unknown_token_id" },
  353. { LLM_KV_TOKENIZER_SEP_ID, "tokenizer.ggml.seperator_token_id" },
  354. { LLM_KV_TOKENIZER_PAD_ID, "tokenizer.ggml.padding_token_id" },
  355. { LLM_KV_TOKENIZER_CLS_ID, "tokenizer.ggml.cls_token_id" },
  356. { LLM_KV_TOKENIZER_MASK_ID, "tokenizer.ggml.mask_token_id" },
  357. { LLM_KV_TOKENIZER_ADD_BOS, "tokenizer.ggml.add_bos_token" },
  358. { LLM_KV_TOKENIZER_ADD_EOS, "tokenizer.ggml.add_eos_token" },
  359. { LLM_KV_TOKENIZER_ADD_PREFIX, "tokenizer.ggml.add_space_prefix" },
  360. { LLM_KV_TOKENIZER_HF_JSON, "tokenizer.huggingface.json" },
  361. { LLM_KV_TOKENIZER_RWKV, "tokenizer.rwkv.world" },
  362. };
  363. struct LLM_KV {
  364. LLM_KV(llm_arch arch) : arch(arch) {}
  365. llm_arch arch;
  366. std::string operator()(llm_kv kv) const {
  367. return ::format(LLM_KV_NAMES.at(kv), LLM_ARCH_NAMES.at(arch));
  368. }
  369. };
  370. enum llm_tensor {
  371. LLM_TENSOR_TOKEN_EMBD,
  372. LLM_TENSOR_TOKEN_EMBD_NORM,
  373. LLM_TENSOR_TOKEN_TYPES,
  374. LLM_TENSOR_POS_EMBD,
  375. LLM_TENSOR_OUTPUT,
  376. LLM_TENSOR_OUTPUT_NORM,
  377. LLM_TENSOR_ROPE_FREQS,
  378. LLM_TENSOR_ATTN_Q,
  379. LLM_TENSOR_ATTN_K,
  380. LLM_TENSOR_ATTN_V,
  381. LLM_TENSOR_ATTN_QKV,
  382. LLM_TENSOR_ATTN_OUT,
  383. LLM_TENSOR_ATTN_NORM,
  384. LLM_TENSOR_ATTN_NORM_2,
  385. LLM_TENSOR_ATTN_OUT_NORM,
  386. LLM_TENSOR_ATTN_ROT_EMBD,
  387. LLM_TENSOR_FFN_GATE_INP,
  388. LLM_TENSOR_FFN_NORM,
  389. LLM_TENSOR_FFN_GATE,
  390. LLM_TENSOR_FFN_DOWN,
  391. LLM_TENSOR_FFN_UP,
  392. LLM_TENSOR_FFN_ACT,
  393. LLM_TENSOR_FFN_DOWN_EXP, // split experts for backward compatibility
  394. LLM_TENSOR_FFN_GATE_EXP,
  395. LLM_TENSOR_FFN_UP_EXP,
  396. LLM_TENSOR_FFN_DOWN_EXPS, // merged experts
  397. LLM_TENSOR_FFN_GATE_EXPS,
  398. LLM_TENSOR_FFN_UP_EXPS,
  399. LLM_TENSOR_ATTN_Q_NORM,
  400. LLM_TENSOR_ATTN_K_NORM,
  401. LLM_TENSOR_LAYER_OUT_NORM,
  402. LLM_TENSOR_SSM_IN,
  403. LLM_TENSOR_SSM_CONV1D,
  404. LLM_TENSOR_SSM_X,
  405. LLM_TENSOR_SSM_DT,
  406. LLM_TENSOR_SSM_A,
  407. LLM_TENSOR_SSM_D,
  408. LLM_TENSOR_SSM_OUT,
  409. };
  410. static const std::map<llm_arch, std::map<llm_tensor, std::string>> LLM_TENSOR_NAMES = {
  411. {
  412. LLM_ARCH_LLAMA,
  413. {
  414. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  415. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  416. { LLM_TENSOR_OUTPUT, "output" },
  417. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  418. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  419. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  420. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  421. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  422. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  423. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  424. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  425. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  426. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  427. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  428. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  429. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  430. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  431. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  432. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  433. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  434. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  435. },
  436. },
  437. {
  438. LLM_ARCH_BAICHUAN,
  439. {
  440. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  441. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  442. { LLM_TENSOR_OUTPUT, "output" },
  443. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  444. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  445. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  446. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  447. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  448. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  449. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  450. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  451. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  452. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  453. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  454. },
  455. },
  456. {
  457. LLM_ARCH_FALCON,
  458. {
  459. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  460. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  461. { LLM_TENSOR_OUTPUT, "output" },
  462. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  463. { LLM_TENSOR_ATTN_NORM_2, "blk.%d.attn_norm_2" },
  464. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  465. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  466. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  467. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  468. },
  469. },
  470. {
  471. LLM_ARCH_GROK,
  472. {
  473. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  474. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  475. { LLM_TENSOR_OUTPUT, "output" },
  476. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  477. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  478. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  479. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  480. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  481. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  482. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  483. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  484. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  485. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  486. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  487. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  488. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  489. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  490. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  491. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  492. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  493. },
  494. },
  495. {
  496. LLM_ARCH_GPT2,
  497. {
  498. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  499. { LLM_TENSOR_POS_EMBD, "position_embd" },
  500. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  501. { LLM_TENSOR_OUTPUT, "output" },
  502. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  503. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  504. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  505. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  506. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  507. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  508. },
  509. },
  510. {
  511. LLM_ARCH_GPTJ,
  512. {
  513. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  514. },
  515. },
  516. {
  517. LLM_ARCH_GPTNEOX,
  518. {
  519. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  520. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  521. { LLM_TENSOR_OUTPUT, "output" },
  522. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  523. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  524. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  525. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  526. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  527. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  528. },
  529. },
  530. {
  531. LLM_ARCH_PERSIMMON,
  532. {
  533. { LLM_TENSOR_TOKEN_EMBD, "token_embd"},
  534. { LLM_TENSOR_OUTPUT_NORM, "output_norm"},
  535. { LLM_TENSOR_OUTPUT, "output"},
  536. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm"},
  537. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv"},
  538. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output"},
  539. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm"},
  540. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm"},
  541. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm"},
  542. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down"},
  543. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up"},
  544. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd"},
  545. },
  546. },
  547. {
  548. LLM_ARCH_MPT,
  549. {
  550. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  551. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  552. { LLM_TENSOR_OUTPUT, "output"},
  553. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  554. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  555. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  556. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  557. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  558. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  559. { LLM_TENSOR_FFN_ACT, "blk.%d.ffn.act" },
  560. { LLM_TENSOR_POS_EMBD, "position_embd" },
  561. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm"},
  562. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm"},
  563. },
  564. },
  565. {
  566. LLM_ARCH_STARCODER,
  567. {
  568. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  569. { LLM_TENSOR_POS_EMBD, "position_embd" },
  570. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  571. { LLM_TENSOR_OUTPUT, "output" },
  572. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  573. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  574. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  575. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  576. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  577. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  578. },
  579. },
  580. {
  581. LLM_ARCH_REFACT,
  582. {
  583. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  584. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  585. { LLM_TENSOR_OUTPUT, "output" },
  586. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  587. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  588. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  589. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  590. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  591. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  592. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  593. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  594. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  595. },
  596. },
  597. {
  598. LLM_ARCH_BERT,
  599. {
  600. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  601. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  602. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  603. { LLM_TENSOR_POS_EMBD, "position_embd" },
  604. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  605. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  606. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  607. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  608. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  609. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  610. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  611. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  612. },
  613. },
  614. {
  615. LLM_ARCH_NOMIC_BERT,
  616. {
  617. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  618. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  619. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  620. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  621. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  622. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  623. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  624. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  625. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  626. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  627. },
  628. },
  629. {
  630. LLM_ARCH_BLOOM,
  631. {
  632. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  633. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  634. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  635. { LLM_TENSOR_OUTPUT, "output" },
  636. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  637. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  638. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  639. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  640. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  641. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  642. },
  643. },
  644. {
  645. LLM_ARCH_STABLELM,
  646. {
  647. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  648. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  649. { LLM_TENSOR_OUTPUT, "output" },
  650. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  651. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  652. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  653. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  654. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  655. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  656. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  657. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  658. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  659. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  660. },
  661. },
  662. {
  663. LLM_ARCH_QWEN,
  664. {
  665. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  666. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  667. { LLM_TENSOR_OUTPUT, "output" },
  668. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  669. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  670. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  671. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  672. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  673. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  674. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  675. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  676. },
  677. },
  678. {
  679. LLM_ARCH_QWEN2,
  680. {
  681. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  682. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  683. { LLM_TENSOR_OUTPUT, "output" },
  684. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  685. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  686. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  687. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  688. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  689. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  690. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  691. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  692. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  693. },
  694. },
  695. {
  696. LLM_ARCH_PHI2,
  697. {
  698. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  699. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  700. { LLM_TENSOR_OUTPUT, "output" },
  701. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  702. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  703. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  704. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  705. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  706. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  707. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  708. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  709. },
  710. },
  711. {
  712. LLM_ARCH_PLAMO,
  713. {
  714. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  715. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  716. { LLM_TENSOR_OUTPUT, "output" },
  717. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  718. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  719. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  720. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  721. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  722. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  723. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  724. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  725. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  726. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  727. },
  728. },
  729. {
  730. LLM_ARCH_CODESHELL,
  731. {
  732. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  733. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  734. { LLM_TENSOR_OUTPUT, "output" },
  735. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  736. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  737. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  738. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  739. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  740. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  741. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  742. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  743. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  744. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  745. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  746. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  747. },
  748. },
  749. {
  750. LLM_ARCH_ORION,
  751. {
  752. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  753. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  754. { LLM_TENSOR_OUTPUT, "output" },
  755. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  756. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  757. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  758. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  759. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  760. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  761. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  762. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  763. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  764. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  765. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  766. },
  767. },
  768. {
  769. LLM_ARCH_INTERNLM2,
  770. {
  771. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  772. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  773. { LLM_TENSOR_OUTPUT, "output" },
  774. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  775. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  776. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  777. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  778. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  779. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  780. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  781. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  782. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  783. },
  784. },
  785. {
  786. LLM_ARCH_MINICPM,
  787. {
  788. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  789. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  790. { LLM_TENSOR_OUTPUT, "output" },
  791. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  792. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  793. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  794. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  795. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  796. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  797. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  798. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  799. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  800. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  801. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  802. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  803. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  804. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  805. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  806. },
  807. },
  808. {
  809. LLM_ARCH_GEMMA,
  810. {
  811. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  812. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  813. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  814. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  815. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  816. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  817. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  818. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  819. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  820. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  821. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  822. },
  823. },
  824. {
  825. LLM_ARCH_STARCODER2,
  826. {
  827. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  828. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  829. { LLM_TENSOR_OUTPUT, "output" },
  830. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  831. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  832. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  833. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  834. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  835. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  836. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  837. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  838. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  839. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  840. },
  841. },
  842. {
  843. LLM_ARCH_MAMBA,
  844. {
  845. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  846. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  847. { LLM_TENSOR_OUTPUT, "output" },
  848. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  849. { LLM_TENSOR_SSM_IN, "blk.%d.ssm_in" },
  850. { LLM_TENSOR_SSM_CONV1D, "blk.%d.ssm_conv1d" },
  851. { LLM_TENSOR_SSM_X, "blk.%d.ssm_x" },
  852. { LLM_TENSOR_SSM_DT, "blk.%d.ssm_dt" },
  853. { LLM_TENSOR_SSM_A, "blk.%d.ssm_a" },
  854. { LLM_TENSOR_SSM_D, "blk.%d.ssm_d" },
  855. { LLM_TENSOR_SSM_OUT, "blk.%d.ssm_out" },
  856. },
  857. },
  858. {
  859. LLM_ARCH_XVERSE,
  860. {
  861. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  862. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  863. { LLM_TENSOR_OUTPUT, "output" },
  864. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  865. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  866. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  867. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  868. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  869. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  870. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  871. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  872. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  873. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  874. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  875. },
  876. },
  877. {
  878. LLM_ARCH_COMMAND_R,
  879. {
  880. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  881. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  882. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  883. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  884. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  885. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  886. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  887. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  888. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  889. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  890. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm" },
  891. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
  892. },
  893. },
  894. {
  895. LLM_ARCH_DBRX,
  896. {
  897. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  898. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  899. { LLM_TENSOR_OUTPUT, "output" },
  900. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  901. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  902. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  903. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  904. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  905. { LLM_TENSOR_FFN_GATE_EXPS, "blk.%d.ffn_gate_exps" },
  906. { LLM_TENSOR_FFN_DOWN_EXPS, "blk.%d.ffn_down_exps" },
  907. { LLM_TENSOR_FFN_UP_EXPS, "blk.%d.ffn_up_exps" },
  908. },
  909. },
  910. {
  911. LLM_ARCH_UNKNOWN,
  912. {
  913. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  914. },
  915. },
  916. };
  917. static llm_arch llm_arch_from_string(const std::string & name) {
  918. for (const auto & kv : LLM_ARCH_NAMES) { // NOLINT
  919. if (kv.second == name) {
  920. return kv.first;
  921. }
  922. }
  923. return LLM_ARCH_UNKNOWN;
  924. }
  925. // helper to handle gguf constants
  926. // usage:
  927. //
  928. // const auto tn = LLM_TN(LLM_ARCH_LLAMA);
  929. //
  930. // std::string name = tn(LLM_TENSOR_OUTPUT); -> "output"
  931. // std::string name = tn(LLM_TENSOR_TOKEN_EMBD, "bias"); -> "token_embd.bias"
  932. // std::string name = tn(LLM_TENSOR_ATTN_NORM, "weight", 3); -> "blk.3.attn_norm.weight"
  933. //
  934. struct LLM_TN {
  935. LLM_TN(llm_arch arch) : arch(arch) {}
  936. llm_arch arch;
  937. std::string operator()(llm_tensor tensor) const {
  938. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  939. return "__missing__";
  940. }
  941. return LLM_TENSOR_NAMES.at(arch).at(tensor);
  942. }
  943. std::string operator()(llm_tensor tensor, const std::string & suffix) const {
  944. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  945. return "__missing__";
  946. }
  947. return LLM_TENSOR_NAMES.at(arch).at(tensor) + "." + suffix;
  948. }
  949. std::string operator()(llm_tensor tensor, int bid) const {
  950. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  951. return "__missing__";
  952. }
  953. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid);
  954. }
  955. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid) const {
  956. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  957. return "__missing__";
  958. }
  959. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid) + "." + suffix;
  960. }
  961. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid, int xid) const {
  962. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  963. return "__missing__";
  964. }
  965. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid, xid) + "." + suffix;
  966. }
  967. };
  968. //
  969. // gguf helpers
  970. //
  971. static const std::map<llama_rope_scaling_type, const char *> LLAMA_ROPE_SCALING_TYPES = {
  972. { LLAMA_ROPE_SCALING_TYPE_NONE, "none" },
  973. { LLAMA_ROPE_SCALING_TYPE_LINEAR, "linear" },
  974. { LLAMA_ROPE_SCALING_TYPE_YARN, "yarn" },
  975. };
  976. static llama_rope_scaling_type llama_rope_scaling_type_from_string(const std::string & name) {
  977. for (const auto & kv : LLAMA_ROPE_SCALING_TYPES) {
  978. if (kv.second == name) {
  979. return (llama_rope_scaling_type) kv.first;
  980. }
  981. }
  982. return LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED;
  983. }
  984. static std::string gguf_data_to_str(enum gguf_type type, const void * data, int i) {
  985. switch (type) {
  986. case GGUF_TYPE_UINT8: return std::to_string(((const uint8_t *)data)[i]);
  987. case GGUF_TYPE_INT8: return std::to_string(((const int8_t *)data)[i]);
  988. case GGUF_TYPE_UINT16: return std::to_string(((const uint16_t *)data)[i]);
  989. case GGUF_TYPE_INT16: return std::to_string(((const int16_t *)data)[i]);
  990. case GGUF_TYPE_UINT32: return std::to_string(((const uint32_t *)data)[i]);
  991. case GGUF_TYPE_INT32: return std::to_string(((const int32_t *)data)[i]);
  992. case GGUF_TYPE_UINT64: return std::to_string(((const uint64_t *)data)[i]);
  993. case GGUF_TYPE_INT64: return std::to_string(((const int64_t *)data)[i]);
  994. case GGUF_TYPE_FLOAT32: return std::to_string(((const float *)data)[i]);
  995. case GGUF_TYPE_FLOAT64: return std::to_string(((const double *)data)[i]);
  996. case GGUF_TYPE_BOOL: return ((const bool *)data)[i] ? "true" : "false";
  997. default: return format("unknown type %d", type);
  998. }
  999. }
  1000. static std::string gguf_kv_to_str(const struct gguf_context * ctx_gguf, int i) {
  1001. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  1002. switch (type) {
  1003. case GGUF_TYPE_STRING:
  1004. return gguf_get_val_str(ctx_gguf, i);
  1005. case GGUF_TYPE_ARRAY:
  1006. {
  1007. const enum gguf_type arr_type = gguf_get_arr_type(ctx_gguf, i);
  1008. int arr_n = gguf_get_arr_n(ctx_gguf, i);
  1009. const void * data = gguf_get_arr_data(ctx_gguf, i);
  1010. std::stringstream ss;
  1011. ss << "[";
  1012. for (int j = 0; j < arr_n; j++) {
  1013. if (arr_type == GGUF_TYPE_STRING) {
  1014. std::string val = gguf_get_arr_str(ctx_gguf, i, j);
  1015. // escape quotes
  1016. replace_all(val, "\\", "\\\\");
  1017. replace_all(val, "\"", "\\\"");
  1018. ss << '"' << val << '"';
  1019. } else if (arr_type == GGUF_TYPE_ARRAY) {
  1020. ss << "???";
  1021. } else {
  1022. ss << gguf_data_to_str(arr_type, data, j);
  1023. }
  1024. if (j < arr_n - 1) {
  1025. ss << ", ";
  1026. }
  1027. }
  1028. ss << "]";
  1029. return ss.str();
  1030. }
  1031. default:
  1032. return gguf_data_to_str(type, gguf_get_val_data(ctx_gguf, i), 0);
  1033. }
  1034. }
  1035. //
  1036. // llama helpers
  1037. //
  1038. #if defined(_WIN32)
  1039. static std::string llama_format_win_err(DWORD err) {
  1040. LPSTR buf;
  1041. size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  1042. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, NULL);
  1043. if (!size) {
  1044. return "FormatMessageA failed";
  1045. }
  1046. std::string ret(buf, size);
  1047. LocalFree(buf);
  1048. return ret;
  1049. }
  1050. #endif
  1051. template <typename T>
  1052. struct no_init {
  1053. T value;
  1054. no_init() { /* do nothing */ }
  1055. };
  1056. struct llama_file {
  1057. // use FILE * so we don't have to re-open the file to mmap
  1058. FILE * fp;
  1059. size_t size;
  1060. llama_file(const char * fname, const char * mode) {
  1061. fp = ggml_fopen(fname, mode);
  1062. if (fp == NULL) {
  1063. throw std::runtime_error(format("failed to open %s: %s", fname, strerror(errno)));
  1064. }
  1065. seek(0, SEEK_END);
  1066. size = tell();
  1067. seek(0, SEEK_SET);
  1068. }
  1069. size_t tell() const {
  1070. #ifdef _WIN32
  1071. __int64 ret = _ftelli64(fp);
  1072. #else
  1073. long ret = std::ftell(fp);
  1074. #endif
  1075. GGML_ASSERT(ret != -1); // this really shouldn't fail
  1076. return (size_t) ret;
  1077. }
  1078. void seek(size_t offset, int whence) const {
  1079. #ifdef _WIN32
  1080. int ret = _fseeki64(fp, (__int64) offset, whence);
  1081. #else
  1082. int ret = std::fseek(fp, (long) offset, whence);
  1083. #endif
  1084. GGML_ASSERT(ret == 0); // same
  1085. }
  1086. void read_raw(void * ptr, size_t len) const {
  1087. if (len == 0) {
  1088. return;
  1089. }
  1090. errno = 0;
  1091. std::size_t ret = std::fread(ptr, len, 1, fp);
  1092. if (ferror(fp)) {
  1093. throw std::runtime_error(format("read error: %s", strerror(errno)));
  1094. }
  1095. if (ret != 1) {
  1096. throw std::runtime_error("unexpectedly reached end of file");
  1097. }
  1098. }
  1099. uint32_t read_u32() const {
  1100. uint32_t ret;
  1101. read_raw(&ret, sizeof(ret));
  1102. return ret;
  1103. }
  1104. void write_raw(const void * ptr, size_t len) const {
  1105. if (len == 0) {
  1106. return;
  1107. }
  1108. errno = 0;
  1109. size_t ret = std::fwrite(ptr, len, 1, fp);
  1110. if (ret != 1) {
  1111. throw std::runtime_error(format("write error: %s", strerror(errno)));
  1112. }
  1113. }
  1114. void write_u32(std::uint32_t val) const {
  1115. write_raw(&val, sizeof(val));
  1116. }
  1117. ~llama_file() {
  1118. if (fp) {
  1119. std::fclose(fp);
  1120. }
  1121. }
  1122. };
  1123. using llama_files = std::vector<std::unique_ptr<llama_file>>;
  1124. struct llama_mmap {
  1125. void * addr;
  1126. size_t size;
  1127. llama_mmap(const llama_mmap &) = delete;
  1128. #ifdef _POSIX_MAPPED_FILES
  1129. static constexpr bool SUPPORTED = true;
  1130. // list of mapped fragments (first_offset, last_offset)
  1131. std::vector<std::pair<size_t, size_t>> mapped_fragments;
  1132. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1 /* -1 = max value */, bool numa = false) {
  1133. size = file->size;
  1134. int fd = fileno(file->fp);
  1135. int flags = MAP_SHARED;
  1136. // prefetch/readahead impairs performance on NUMA systems
  1137. if (numa) { prefetch = 0; }
  1138. #ifdef __linux__
  1139. // advise the kernel to read the file sequentially (increases readahead)
  1140. if (posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL)) {
  1141. LLAMA_LOG_WARN("warning: posix_fadvise(.., POSIX_FADV_SEQUENTIAL) failed: %s\n",
  1142. strerror(errno));
  1143. }
  1144. if (prefetch) { flags |= MAP_POPULATE; }
  1145. #endif
  1146. addr = mmap(NULL, file->size, PROT_READ, flags, fd, 0);
  1147. if (addr == MAP_FAILED) { // NOLINT
  1148. throw std::runtime_error(format("mmap failed: %s", strerror(errno)));
  1149. }
  1150. if (prefetch > 0) {
  1151. // advise the kernel to preload the mapped memory
  1152. if (posix_madvise(addr, std::min(file->size, prefetch), POSIX_MADV_WILLNEED)) {
  1153. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_WILLNEED) failed: %s\n",
  1154. strerror(errno));
  1155. }
  1156. }
  1157. if (numa) {
  1158. // advise the kernel not to use readahead
  1159. // (because the next page might not belong on the same node)
  1160. if (posix_madvise(addr, file->size, POSIX_MADV_RANDOM)) {
  1161. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_RANDOM) failed: %s\n",
  1162. strerror(errno));
  1163. }
  1164. }
  1165. // initialize list of mapped_fragments
  1166. mapped_fragments.emplace_back(0, file->size);
  1167. }
  1168. static void align_range(size_t * first, size_t * last, size_t page_size) {
  1169. // align first to the next page
  1170. size_t offset_in_page = *first & (page_size - 1);
  1171. size_t offset_to_page = offset_in_page == 0 ? 0 : page_size - offset_in_page;
  1172. *first += offset_to_page;
  1173. // align last to the previous page
  1174. *last = *last & ~(page_size - 1);
  1175. if (*last <= *first) {
  1176. *last = *first;
  1177. }
  1178. }
  1179. // partially unmap the file in the range [first, last)
  1180. void unmap_fragment(size_t first, size_t last) {
  1181. // note: this function must not be called multiple times with overlapping ranges
  1182. // otherwise, there is a risk of invalidating addresses that have been repurposed for other mappings
  1183. int page_size = sysconf(_SC_PAGESIZE);
  1184. align_range(&first, &last, page_size);
  1185. size_t len = last - first;
  1186. if (len == 0) {
  1187. return;
  1188. }
  1189. GGML_ASSERT(first % page_size == 0);
  1190. GGML_ASSERT(last % page_size == 0);
  1191. GGML_ASSERT(last > first);
  1192. void * next_page_start = (uint8_t *) addr + first;
  1193. // unmap the range
  1194. if (munmap(next_page_start, len)) {
  1195. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  1196. }
  1197. // update the list of mapped fragments to avoid unmapping the same range again in the destructor
  1198. std::vector<std::pair<size_t, size_t>> new_mapped_fragments;
  1199. for (const auto & frag : mapped_fragments) {
  1200. if (frag.first < first && frag.second > last) {
  1201. // the range is in the middle of the fragment, split it
  1202. new_mapped_fragments.emplace_back(frag.first, first);
  1203. new_mapped_fragments.emplace_back(last, frag.second);
  1204. } else if (frag.first < first && frag.second > first) {
  1205. // the range starts in the middle of the fragment
  1206. new_mapped_fragments.emplace_back(frag.first, first);
  1207. } else if (frag.first < last && frag.second > last) {
  1208. // the range ends in the middle of the fragment
  1209. new_mapped_fragments.emplace_back(last, frag.second);
  1210. } else if (frag.first >= first && frag.second <= last) {
  1211. // the range covers the entire fragment
  1212. } else {
  1213. // the range is outside the fragment
  1214. new_mapped_fragments.push_back(frag);
  1215. }
  1216. }
  1217. mapped_fragments = std::move(new_mapped_fragments);
  1218. }
  1219. ~llama_mmap() {
  1220. for (const auto & frag : mapped_fragments) {
  1221. if (munmap((char *) addr + frag.first, frag.second - frag.first)) {
  1222. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  1223. }
  1224. }
  1225. }
  1226. #elif defined(_WIN32)
  1227. static constexpr bool SUPPORTED = true;
  1228. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1, bool numa = false) {
  1229. GGML_UNUSED(numa);
  1230. size = file->size;
  1231. HANDLE hFile = (HANDLE) _get_osfhandle(_fileno(file->fp));
  1232. HANDLE hMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
  1233. if (hMapping == NULL) {
  1234. DWORD error = GetLastError();
  1235. throw std::runtime_error(format("CreateFileMappingA failed: %s", llama_format_win_err(error).c_str()));
  1236. }
  1237. addr = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
  1238. DWORD error = GetLastError();
  1239. CloseHandle(hMapping);
  1240. if (addr == NULL) {
  1241. throw std::runtime_error(format("MapViewOfFile failed: %s", llama_format_win_err(error).c_str()));
  1242. }
  1243. if (prefetch > 0) {
  1244. #if _WIN32_WINNT >= 0x602
  1245. // PrefetchVirtualMemory is only present on Windows 8 and above, so we dynamically load it
  1246. BOOL (WINAPI *pPrefetchVirtualMemory) (HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG);
  1247. HMODULE hKernel32 = GetModuleHandleW(L"kernel32.dll");
  1248. // may fail on pre-Windows 8 systems
  1249. pPrefetchVirtualMemory = reinterpret_cast<decltype(pPrefetchVirtualMemory)> (GetProcAddress(hKernel32, "PrefetchVirtualMemory"));
  1250. if (pPrefetchVirtualMemory) {
  1251. // advise the kernel to preload the mapped memory
  1252. WIN32_MEMORY_RANGE_ENTRY range;
  1253. range.VirtualAddress = addr;
  1254. range.NumberOfBytes = (SIZE_T) std::min(size, prefetch);
  1255. if (!pPrefetchVirtualMemory(GetCurrentProcess(), 1, &range, 0)) {
  1256. LLAMA_LOG_WARN("warning: PrefetchVirtualMemory failed: %s\n",
  1257. llama_format_win_err(GetLastError()).c_str());
  1258. }
  1259. }
  1260. #else
  1261. throw std::runtime_error("PrefetchVirtualMemory unavailable");
  1262. #endif
  1263. }
  1264. }
  1265. void unmap_fragment(size_t first, size_t last) {
  1266. // not supported
  1267. GGML_UNUSED(first);
  1268. GGML_UNUSED(last);
  1269. }
  1270. ~llama_mmap() {
  1271. if (!UnmapViewOfFile(addr)) {
  1272. LLAMA_LOG_WARN("warning: UnmapViewOfFile failed: %s\n",
  1273. llama_format_win_err(GetLastError()).c_str());
  1274. }
  1275. }
  1276. #else
  1277. static constexpr bool SUPPORTED = false;
  1278. llama_mmap(struct llama_file * file, size_t prefetch = -1, bool numa = false) {
  1279. GGML_UNUSED(file);
  1280. GGML_UNUSED(prefetch);
  1281. GGML_UNUSED(numa);
  1282. throw std::runtime_error("mmap not supported");
  1283. }
  1284. void unmap_fragment(size_t first, size_t last) {
  1285. GGML_UNUSED(first);
  1286. GGML_UNUSED(last);
  1287. throw std::runtime_error("mmap not supported");
  1288. }
  1289. #endif
  1290. };
  1291. using llama_mmaps = std::vector<std::unique_ptr<llama_mmap>>;
  1292. // Represents some region of memory being locked using mlock or VirtualLock;
  1293. // will automatically unlock on destruction.
  1294. struct llama_mlock {
  1295. void * addr = NULL;
  1296. size_t size = 0;
  1297. bool failed_already = false;
  1298. llama_mlock() {}
  1299. llama_mlock(const llama_mlock &) = delete;
  1300. ~llama_mlock() {
  1301. if (size) {
  1302. raw_unlock(addr, size);
  1303. }
  1304. }
  1305. void init(void * ptr) {
  1306. GGML_ASSERT(addr == NULL && size == 0); // NOLINT
  1307. addr = ptr;
  1308. }
  1309. void grow_to(size_t target_size) {
  1310. GGML_ASSERT(addr);
  1311. if (failed_already) {
  1312. return;
  1313. }
  1314. size_t granularity = lock_granularity();
  1315. target_size = (target_size + granularity - 1) & ~(granularity - 1);
  1316. if (target_size > size) {
  1317. if (raw_lock((uint8_t *) addr + size, target_size - size)) {
  1318. size = target_size;
  1319. } else {
  1320. failed_already = true;
  1321. }
  1322. }
  1323. }
  1324. #ifdef _POSIX_MEMLOCK_RANGE
  1325. static constexpr bool SUPPORTED = true;
  1326. static size_t lock_granularity() {
  1327. return (size_t) sysconf(_SC_PAGESIZE);
  1328. }
  1329. #ifdef __APPLE__
  1330. #define MLOCK_SUGGESTION \
  1331. "Try increasing the sysctl values 'vm.user_wire_limit' and 'vm.global_user_wire_limit' and/or " \
  1332. "decreasing 'vm.global_no_user_wire_amount'. Also try increasing RLIMIT_MEMLOCK (ulimit -l).\n"
  1333. #else
  1334. #define MLOCK_SUGGESTION \
  1335. "Try increasing RLIMIT_MEMLOCK ('ulimit -l' as root).\n"
  1336. #endif
  1337. bool raw_lock(const void * addr, size_t size) const {
  1338. if (!mlock(addr, size)) {
  1339. return true;
  1340. }
  1341. char* errmsg = std::strerror(errno);
  1342. bool suggest = (errno == ENOMEM);
  1343. // Check if the resource limit is fine after all
  1344. struct rlimit lock_limit;
  1345. if (suggest && getrlimit(RLIMIT_MEMLOCK, &lock_limit)) {
  1346. suggest = false;
  1347. }
  1348. if (suggest && (lock_limit.rlim_max > lock_limit.rlim_cur + size)) {
  1349. suggest = false;
  1350. }
  1351. LLAMA_LOG_WARN("warning: failed to mlock %zu-byte buffer (after previously locking %zu bytes): %s\n%s",
  1352. size, this->size, errmsg, suggest ? MLOCK_SUGGESTION : "");
  1353. return false;
  1354. }
  1355. #undef MLOCK_SUGGESTION
  1356. static void raw_unlock(void * addr, size_t size) {
  1357. if (munlock(addr, size)) {
  1358. LLAMA_LOG_WARN("warning: failed to munlock buffer: %s\n", std::strerror(errno));
  1359. }
  1360. }
  1361. #elif defined(_WIN32)
  1362. static constexpr bool SUPPORTED = true;
  1363. static size_t lock_granularity() {
  1364. SYSTEM_INFO si;
  1365. GetSystemInfo(&si);
  1366. return (size_t) si.dwPageSize;
  1367. }
  1368. bool raw_lock(void * ptr, size_t len) const {
  1369. for (int tries = 1; ; tries++) {
  1370. if (VirtualLock(ptr, len)) {
  1371. return true;
  1372. }
  1373. if (tries == 2) {
  1374. LLAMA_LOG_WARN("warning: failed to VirtualLock %zu-byte buffer (after previously locking %zu bytes): %s\n",
  1375. len, size, llama_format_win_err(GetLastError()).c_str());
  1376. return false;
  1377. }
  1378. // It failed but this was only the first try; increase the working
  1379. // set size and try again.
  1380. SIZE_T min_ws_size, max_ws_size;
  1381. if (!GetProcessWorkingSetSize(GetCurrentProcess(), &min_ws_size, &max_ws_size)) {
  1382. LLAMA_LOG_WARN("warning: GetProcessWorkingSetSize failed: %s\n",
  1383. llama_format_win_err(GetLastError()).c_str());
  1384. return false;
  1385. }
  1386. // Per MSDN: "The maximum number of pages that a process can lock
  1387. // is equal to the number of pages in its minimum working set minus
  1388. // a small overhead."
  1389. // Hopefully a megabyte is enough overhead:
  1390. size_t increment = len + 1048576;
  1391. // The minimum must be <= the maximum, so we need to increase both:
  1392. min_ws_size += increment;
  1393. max_ws_size += increment;
  1394. if (!SetProcessWorkingSetSize(GetCurrentProcess(), min_ws_size, max_ws_size)) {
  1395. LLAMA_LOG_WARN("warning: SetProcessWorkingSetSize failed: %s\n",
  1396. llama_format_win_err(GetLastError()).c_str());
  1397. return false;
  1398. }
  1399. }
  1400. }
  1401. static void raw_unlock(void * ptr, size_t len) {
  1402. if (!VirtualUnlock(ptr, len)) {
  1403. LLAMA_LOG_WARN("warning: failed to VirtualUnlock buffer: %s\n",
  1404. llama_format_win_err(GetLastError()).c_str());
  1405. }
  1406. }
  1407. #else
  1408. static constexpr bool SUPPORTED = false;
  1409. static size_t lock_granularity() {
  1410. return (size_t) 65536;
  1411. }
  1412. bool raw_lock(const void * addr, size_t len) const {
  1413. LLAMA_LOG_WARN("warning: mlock not supported on this system\n");
  1414. return false;
  1415. }
  1416. static void raw_unlock(const void * addr, size_t len) {}
  1417. #endif
  1418. };
  1419. using llama_mlocks = std::vector<std::unique_ptr<llama_mlock>>;
  1420. static std::string llama_token_to_piece(const struct llama_context * ctx, llama_token token) {
  1421. std::vector<char> result(8, 0);
  1422. const int n_tokens = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1423. if (n_tokens < 0) {
  1424. result.resize(-n_tokens);
  1425. int check = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1426. GGML_ASSERT(check == -n_tokens);
  1427. }
  1428. else {
  1429. result.resize(n_tokens);
  1430. }
  1431. return std::string(result.data(), result.size());
  1432. }
  1433. static ggml_backend_buffer_type_t llama_default_buffer_type_cpu(bool host_buffer) {
  1434. ggml_backend_buffer_type_t buft = nullptr;
  1435. #if defined(GGML_USE_CUDA)
  1436. // host buffers should only be used when data is expected to be copied to/from the GPU
  1437. if (host_buffer) {
  1438. buft = ggml_backend_cuda_host_buffer_type();
  1439. }
  1440. #elif defined(GGML_USE_SYCL)
  1441. if (host_buffer) {
  1442. buft = ggml_backend_sycl_host_buffer_type();
  1443. }
  1444. #elif defined(GGML_USE_CPU_HBM)
  1445. buft = ggml_backend_cpu_hbm_buffer_type();
  1446. #elif defined(GGML_USE_VULKAN)
  1447. if (host_buffer) {
  1448. buft = ggml_backend_vk_host_buffer_type();
  1449. }
  1450. #endif
  1451. if (buft == nullptr) {
  1452. buft = ggml_backend_cpu_buffer_type();
  1453. }
  1454. return buft;
  1455. GGML_UNUSED(host_buffer);
  1456. }
  1457. static ggml_backend_buffer_type_t llama_default_buffer_type_offload(int gpu) {
  1458. ggml_backend_buffer_type_t buft = nullptr;
  1459. #ifdef GGML_USE_METAL
  1460. buft = ggml_backend_metal_buffer_type();
  1461. #elif defined(GGML_USE_CUDA)
  1462. buft = ggml_backend_cuda_buffer_type(gpu);
  1463. #elif defined(GGML_USE_VULKAN)
  1464. buft = ggml_backend_vk_buffer_type(gpu);
  1465. #elif defined(GGML_USE_SYCL)
  1466. buft = ggml_backend_sycl_buffer_type(gpu);
  1467. #elif defined(GGML_USE_CLBLAST)
  1468. buft = ggml_backend_opencl_buffer_type();
  1469. #elif defined(GGML_USE_KOMPUTE)
  1470. buft = ggml_backend_kompute_buffer_type(gpu);
  1471. if (buft == nullptr) {
  1472. LLAMA_LOG_WARN("%s: cannot use GPU %d, check `vulkaninfo --summary`\n", __func__, gpu);
  1473. }
  1474. #endif
  1475. if (buft == nullptr) {
  1476. buft = llama_default_buffer_type_cpu(true);
  1477. }
  1478. return buft;
  1479. GGML_UNUSED(gpu);
  1480. }
  1481. static ggml_backend_buffer_type_t llama_default_buffer_type_split(int fallback_gpu, const float * tensor_split) {
  1482. ggml_backend_buffer_type_t buft = nullptr;
  1483. #ifdef GGML_USE_CUDA
  1484. if (ggml_backend_cuda_get_device_count() > 1) {
  1485. buft = ggml_backend_cuda_split_buffer_type(tensor_split);
  1486. }
  1487. #endif
  1488. #ifdef GGML_USE_SYCL
  1489. if (ggml_backend_sycl_get_device_count() > 1) {
  1490. buft = ggml_backend_sycl_split_buffer_type(tensor_split);
  1491. }
  1492. #endif
  1493. if (buft == nullptr) {
  1494. buft = llama_default_buffer_type_offload(fallback_gpu);
  1495. }
  1496. return buft;
  1497. GGML_UNUSED(tensor_split);
  1498. }
  1499. static size_t llama_get_device_count() {
  1500. #if defined(GGML_USE_CUDA)
  1501. return ggml_backend_cuda_get_device_count();
  1502. #elif defined(GGML_USE_SYCL)
  1503. return ggml_backend_sycl_get_device_count();
  1504. #elif defined(GGML_USE_VULKAN)
  1505. return ggml_backend_vk_get_device_count();
  1506. #else
  1507. return 1;
  1508. #endif
  1509. }
  1510. static size_t llama_get_device_memory(int device) {
  1511. #if defined(GGML_USE_CUDA)
  1512. size_t total;
  1513. size_t free;
  1514. ggml_backend_cuda_get_device_memory(device, &free, &total);
  1515. return free;
  1516. #elif defined(GGML_USE_SYCL)
  1517. size_t total;
  1518. size_t free;
  1519. ggml_backend_sycl_get_device_memory(device, &free, &total);
  1520. return free;
  1521. #elif defined(GGML_USE_VULKAN)
  1522. size_t total;
  1523. size_t free;
  1524. ggml_backend_vk_get_device_memory(device, &free, &total);
  1525. return free;
  1526. #else
  1527. return 1;
  1528. GGML_UNUSED(device);
  1529. #endif
  1530. }
  1531. //
  1532. // globals
  1533. //
  1534. struct llama_state {
  1535. llama_state() {
  1536. #ifdef GGML_USE_METAL
  1537. ggml_backend_metal_log_set_callback(log_callback, log_callback_user_data);
  1538. #endif
  1539. }
  1540. // We save the log callback globally
  1541. ggml_log_callback log_callback = llama_log_callback_default;
  1542. void * log_callback_user_data = nullptr;
  1543. };
  1544. static llama_state g_state;
  1545. // available llama models
  1546. enum e_model {
  1547. MODEL_UNKNOWN,
  1548. MODEL_17M,
  1549. MODEL_22M,
  1550. MODEL_33M,
  1551. MODEL_109M,
  1552. MODEL_137M,
  1553. MODEL_335M,
  1554. MODEL_0_5B,
  1555. MODEL_1B,
  1556. MODEL_2B,
  1557. MODEL_3B,
  1558. MODEL_4B,
  1559. MODEL_7B,
  1560. MODEL_8B,
  1561. MODEL_13B,
  1562. MODEL_14B,
  1563. MODEL_15B,
  1564. MODEL_20B,
  1565. MODEL_30B,
  1566. MODEL_34B,
  1567. MODEL_35B,
  1568. MODEL_40B,
  1569. MODEL_65B,
  1570. MODEL_70B,
  1571. MODEL_314B,
  1572. MODEL_SMALL,
  1573. MODEL_MEDIUM,
  1574. MODEL_LARGE,
  1575. MODEL_XL,
  1576. MODEL_8x7B,
  1577. MODEL_8x22B,
  1578. MODEL_16x12B,
  1579. };
  1580. static const size_t kiB = 1024;
  1581. static const size_t MiB = 1024*kiB;
  1582. static const size_t GiB = 1024*MiB;
  1583. struct llama_hparams {
  1584. bool vocab_only;
  1585. bool rope_finetuned;
  1586. uint32_t n_vocab;
  1587. uint32_t n_ctx_train; // context size the model was trained on
  1588. uint32_t n_embd;
  1589. uint32_t n_head;
  1590. uint32_t n_head_kv;
  1591. uint32_t n_layer;
  1592. uint32_t n_rot;
  1593. 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
  1594. uint32_t n_embd_head_v; // dimension of values (d_v) aka n_embd_head
  1595. uint32_t n_ff;
  1596. uint32_t n_expert = 0;
  1597. uint32_t n_expert_used = 0;
  1598. uint32_t n_vocab_type = 0; // for BERT-style token types
  1599. float f_norm_eps;
  1600. float f_norm_rms_eps;
  1601. float rope_freq_base_train;
  1602. float rope_freq_scale_train;
  1603. uint32_t n_yarn_orig_ctx;
  1604. // for State Space Models
  1605. uint32_t ssm_d_conv = 0;
  1606. uint32_t ssm_d_inner = 0;
  1607. uint32_t ssm_d_state = 0;
  1608. uint32_t ssm_dt_rank = 0;
  1609. float f_clamp_kqv = 0.0f;
  1610. float f_max_alibi_bias = 0.0f;
  1611. float f_logit_scale = 0.0f;
  1612. bool causal_attn = true;
  1613. bool need_kq_pos = false;
  1614. enum llama_pooling_type pooling_type = LLAMA_POOLING_TYPE_NONE;
  1615. enum llama_rope_type rope_type = LLAMA_ROPE_TYPE_NONE;
  1616. enum llama_rope_scaling_type rope_scaling_type_train = LLAMA_ROPE_SCALING_TYPE_NONE;
  1617. bool operator!=(const llama_hparams & other) const {
  1618. if (this->vocab_only != other.vocab_only) return true;
  1619. if (this->n_vocab != other.n_vocab) return true;
  1620. if (this->n_ctx_train != other.n_ctx_train) return true;
  1621. if (this->n_embd != other.n_embd) return true;
  1622. if (this->n_head != other.n_head) return true;
  1623. if (this->n_head_kv != other.n_head_kv) return true;
  1624. if (this->n_layer != other.n_layer) return true;
  1625. if (this->n_rot != other.n_rot) return true;
  1626. if (this->n_embd_head_k != other.n_embd_head_k) return true;
  1627. if (this->n_embd_head_v != other.n_embd_head_v) return true;
  1628. if (this->n_ff != other.n_ff) return true;
  1629. if (this->n_expert != other.n_expert) return true;
  1630. if (this->n_expert_used != other.n_expert_used) return true;
  1631. if (this->rope_finetuned != other.rope_finetuned) return true;
  1632. if (this->n_yarn_orig_ctx != other.n_yarn_orig_ctx) return true;
  1633. if (this->ssm_d_conv != other.ssm_d_conv) return true;
  1634. if (this->ssm_d_inner != other.ssm_d_inner) return true;
  1635. if (this->ssm_d_state != other.ssm_d_state) return true;
  1636. if (this->ssm_dt_rank != other.ssm_dt_rank) return true;
  1637. const float EPSILON = 1e-9f;
  1638. if (!is_float_close(this->f_norm_eps, other.f_norm_eps, EPSILON)) return true;
  1639. if (!is_float_close(this->f_norm_rms_eps, other.f_norm_rms_eps, EPSILON)) return true;
  1640. if (!is_float_close(this->rope_freq_base_train, other.rope_freq_base_train, EPSILON)) return true;
  1641. if (!is_float_close(this->rope_freq_scale_train, other.rope_freq_scale_train, EPSILON)) return true;
  1642. return false;
  1643. }
  1644. uint32_t n_gqa() const {
  1645. if (n_head_kv == 0) {
  1646. return 0;
  1647. }
  1648. return n_head/n_head_kv;
  1649. }
  1650. uint32_t n_embd_k_gqa() const { // dimension of key embeddings across all k-v heads
  1651. return n_embd_head_k * n_head_kv;
  1652. }
  1653. uint32_t n_embd_v_gqa() const { // dimension of value embeddings across all k-v heads
  1654. return n_embd_head_v * n_head_kv;
  1655. }
  1656. uint32_t n_embd_k_s() const { // dimension of the rolling state embeddings
  1657. // corresponds to Mamba's conv_states size
  1658. // TODO: maybe support other convolution strides than 1
  1659. // NOTE: since the first column of the conv_state is shifted out each time, it's not actually needed
  1660. return (ssm_d_conv > 0 ? ssm_d_conv - 1 : 0) * ssm_d_inner;
  1661. }
  1662. uint32_t n_embd_v_s() const { // dimension of the recurrent state embeddings
  1663. // corresponds to Mamba's ssm_states size
  1664. return ssm_d_state * ssm_d_inner;
  1665. }
  1666. };
  1667. struct llama_cparams {
  1668. uint32_t n_ctx; // context size used during inference
  1669. uint32_t n_batch;
  1670. uint32_t n_ubatch;
  1671. uint32_t n_seq_max;
  1672. uint32_t n_threads; // number of threads to use for generation
  1673. uint32_t n_threads_batch; // number of threads to use for batch processing
  1674. float rope_freq_base;
  1675. float rope_freq_scale;
  1676. uint32_t n_yarn_orig_ctx;
  1677. // These hyperparameters are not exposed in GGUF, because all
  1678. // existing YaRN models use the same values for them.
  1679. float yarn_ext_factor;
  1680. float yarn_attn_factor;
  1681. float yarn_beta_fast;
  1682. float yarn_beta_slow;
  1683. float defrag_thold;
  1684. bool embeddings;
  1685. bool causal_attn;
  1686. bool offload_kqv;
  1687. enum llama_pooling_type pooling_type;
  1688. ggml_backend_sched_eval_callback cb_eval;
  1689. void * cb_eval_user_data;
  1690. };
  1691. struct llama_layer {
  1692. // normalization
  1693. struct ggml_tensor * attn_norm;
  1694. struct ggml_tensor * attn_norm_b;
  1695. struct ggml_tensor * attn_norm_2;
  1696. struct ggml_tensor * attn_norm_2_b;
  1697. struct ggml_tensor * attn_q_norm;
  1698. struct ggml_tensor * attn_q_norm_b;
  1699. struct ggml_tensor * attn_k_norm;
  1700. struct ggml_tensor * attn_k_norm_b;
  1701. struct ggml_tensor * attn_out_norm;
  1702. struct ggml_tensor * attn_out_norm_b;
  1703. // attention
  1704. struct ggml_tensor * wq;
  1705. struct ggml_tensor * wk;
  1706. struct ggml_tensor * wv;
  1707. struct ggml_tensor * wo;
  1708. struct ggml_tensor * wqkv;
  1709. // attention bias
  1710. struct ggml_tensor * bq;
  1711. struct ggml_tensor * bk;
  1712. struct ggml_tensor * bv;
  1713. struct ggml_tensor * bo;
  1714. struct ggml_tensor * bqkv;
  1715. // normalization
  1716. struct ggml_tensor * ffn_norm;
  1717. struct ggml_tensor * ffn_norm_b;
  1718. struct ggml_tensor * layer_out_norm;
  1719. struct ggml_tensor * layer_out_norm_b;
  1720. // ff
  1721. struct ggml_tensor * ffn_gate; // w1
  1722. struct ggml_tensor * ffn_down; // w2
  1723. struct ggml_tensor * ffn_up; // w3
  1724. // ff MoE
  1725. struct ggml_tensor * ffn_gate_inp;
  1726. struct ggml_tensor * ffn_gate_exps;
  1727. struct ggml_tensor * ffn_down_exps;
  1728. struct ggml_tensor * ffn_up_exps ;
  1729. // ff bias
  1730. struct ggml_tensor * ffn_down_b; // b2
  1731. struct ggml_tensor * ffn_up_b; // b3
  1732. struct ggml_tensor * ffn_act;
  1733. // mamba proj
  1734. struct ggml_tensor * ssm_in;
  1735. struct ggml_tensor * ssm_x;
  1736. struct ggml_tensor * ssm_dt;
  1737. struct ggml_tensor * ssm_out;
  1738. // mamba
  1739. struct ggml_tensor * ssm_conv1d;
  1740. struct ggml_tensor * ssm_a;
  1741. struct ggml_tensor * ssm_d;
  1742. // mamba bias
  1743. struct ggml_tensor * ssm_conv1d_b;
  1744. struct ggml_tensor * ssm_dt_b;
  1745. };
  1746. struct llama_kv_cell {
  1747. llama_pos pos = -1;
  1748. llama_pos delta = 0;
  1749. int32_t src = 0; // used by recurrent state models to copy states
  1750. std::set<llama_seq_id> seq_id;
  1751. bool has_seq_id(const llama_seq_id & id) const {
  1752. return seq_id.find(id) != seq_id.end();
  1753. }
  1754. bool is_empty() const {
  1755. return seq_id.empty();
  1756. }
  1757. bool is_same_seq(const llama_kv_cell & other) const {
  1758. return seq_id == other.seq_id;
  1759. }
  1760. };
  1761. // ring-buffer of cached KV data
  1762. struct llama_kv_cache {
  1763. bool has_shift = false;
  1764. bool do_defrag = false;
  1765. bool do_copy = false;
  1766. // with recurrent state models, a cell can hold the state for more than one past token
  1767. bool recurrent = false;
  1768. // Note: The value of head isn't only used to optimize searching
  1769. // for a free KV slot. llama_decode_internal also uses it, so it
  1770. // cannot be freely changed after a slot has been allocated.
  1771. uint32_t head = 0;
  1772. uint32_t size = 0;
  1773. uint32_t used = 0; // used cells (i.e. at least one seq_id)
  1774. // computed before each graph build
  1775. uint32_t n = 0;
  1776. ggml_type type_k = GGML_TYPE_F16;
  1777. ggml_type type_v = GGML_TYPE_F16;
  1778. std::vector<llama_kv_cell> cells;
  1779. std::vector<struct ggml_tensor *> k_l; // per layer
  1780. std::vector<struct ggml_tensor *> v_l;
  1781. std::vector<struct ggml_context *> ctxs;
  1782. std::vector<ggml_backend_buffer_t> bufs;
  1783. size_t total_size() const {
  1784. size_t size = 0;
  1785. for (ggml_backend_buffer_t buf : bufs) {
  1786. size += ggml_backend_buffer_get_size(buf);
  1787. }
  1788. return size;
  1789. }
  1790. ~llama_kv_cache() {
  1791. for (struct ggml_context * ctx : ctxs) {
  1792. ggml_free(ctx);
  1793. }
  1794. for (ggml_backend_buffer_t buf : bufs) {
  1795. ggml_backend_buffer_free(buf);
  1796. }
  1797. }
  1798. };
  1799. struct llama_control_vector {
  1800. std::vector<struct ggml_tensor *> tensors; // per layer
  1801. std::vector<struct ggml_context *> ctxs;
  1802. std::vector<ggml_backend_buffer_t> bufs;
  1803. int32_t layer_start = -1;
  1804. int32_t layer_end = -1;
  1805. ggml_tensor * tensor_for(int il) const {
  1806. if (il < 0 || il < layer_start || il > layer_end || (size_t) il >= tensors.size()) {
  1807. return nullptr;
  1808. }
  1809. return tensors[il];
  1810. }
  1811. ~llama_control_vector() {
  1812. for (struct ggml_context * ctx : ctxs) {
  1813. ggml_free(ctx);
  1814. }
  1815. for (ggml_backend_buffer_t buf : bufs) {
  1816. ggml_backend_buffer_free(buf);
  1817. }
  1818. }
  1819. };
  1820. struct llama_vocab {
  1821. using id = int32_t;
  1822. using token = std::string;
  1823. using ttype = llama_token_type;
  1824. struct token_data {
  1825. token text;
  1826. float score;
  1827. ttype type;
  1828. };
  1829. enum llama_vocab_type type = LLAMA_VOCAB_TYPE_SPM;
  1830. std::unordered_map<token, id> token_to_id;
  1831. std::vector<token_data> id_to_token;
  1832. std::unordered_map<token, id> special_tokens_cache;
  1833. std::map<std::pair<std::string, std::string>, int> bpe_ranks;
  1834. // default LLaMA special tokens
  1835. id special_bos_id = 1;
  1836. id special_eos_id = 2;
  1837. id special_unk_id = 0;
  1838. id special_sep_id = -1;
  1839. id special_pad_id = -1;
  1840. id special_cls_id = -1;
  1841. id special_mask_id = -1;
  1842. int special_add_bos = -1; // -1 unknown, 1 add, 0 don't add.
  1843. int special_add_eos = -1; // -1 unknown, 1 add, 0 don't add.
  1844. id linefeed_id = 13;
  1845. id special_prefix_id = 32007;
  1846. id special_middle_id = 32009;
  1847. id special_suffix_id = 32008;
  1848. id special_eot_id = 32010;
  1849. bool add_space_prefix = true;
  1850. int find_bpe_rank(const std::string & token_left, const std::string & token_right) const {
  1851. GGML_ASSERT(token_left.find(' ') == std::string::npos);
  1852. GGML_ASSERT(token_left.find('\n') == std::string::npos);
  1853. GGML_ASSERT(token_right.find(' ') == std::string::npos);
  1854. GGML_ASSERT(token_right.find('\n') == std::string::npos);
  1855. auto it = bpe_ranks.find(std::make_pair(token_left, token_right));
  1856. if (it == bpe_ranks.end()) {
  1857. return -1;
  1858. }
  1859. return it->second;
  1860. }
  1861. };
  1862. struct llama_model {
  1863. e_model type = MODEL_UNKNOWN;
  1864. llm_arch arch = LLM_ARCH_UNKNOWN;
  1865. llama_ftype ftype = LLAMA_FTYPE_ALL_F32;
  1866. std::string name = "n/a";
  1867. llama_hparams hparams = {};
  1868. llama_vocab vocab;
  1869. struct ggml_tensor * tok_embd;
  1870. struct ggml_tensor * type_embd;
  1871. struct ggml_tensor * pos_embd;
  1872. struct ggml_tensor * tok_norm;
  1873. struct ggml_tensor * tok_norm_b;
  1874. struct ggml_tensor * output_norm;
  1875. struct ggml_tensor * output_norm_b;
  1876. struct ggml_tensor * output;
  1877. struct ggml_tensor * output_b;
  1878. std::vector<llama_layer> layers;
  1879. llama_split_mode split_mode;
  1880. int main_gpu;
  1881. int n_gpu_layers;
  1882. // gguf metadata
  1883. std::unordered_map<std::string, std::string> gguf_kv;
  1884. // layer -> buffer type mapping
  1885. struct layer_buft {
  1886. layer_buft() : buft_matrix(nullptr), buft(nullptr) {}
  1887. layer_buft(ggml_backend_buffer_type_t matrix) : buft_matrix(matrix), buft(matrix) {}
  1888. layer_buft(ggml_backend_buffer_type_t matrix, ggml_backend_buffer_type_t other) : buft_matrix(matrix), buft(other) {}
  1889. ggml_backend_buffer_type_t buft_matrix; // matrices only - used by split buffers and backends that support only matrix multiplication
  1890. ggml_backend_buffer_type_t buft; // everything else
  1891. };
  1892. layer_buft buft_input;
  1893. layer_buft buft_output;
  1894. std::vector<layer_buft> buft_layer;
  1895. // contexts where the model tensors metadata is stored
  1896. std::vector<struct ggml_context *> ctxs;
  1897. // the model memory buffers for the tensor data
  1898. std::vector<ggml_backend_buffer_t> bufs;
  1899. // model memory mapped files
  1900. llama_mmaps mappings;
  1901. // objects representing data potentially being locked in memory
  1902. llama_mlocks mlock_bufs;
  1903. llama_mlocks mlock_mmaps;
  1904. // for quantize-stats only
  1905. std::vector<std::pair<std::string, struct ggml_tensor *>> tensors_by_name;
  1906. int64_t t_load_us = 0;
  1907. int64_t t_start_us = 0;
  1908. ~llama_model() {
  1909. for (struct ggml_context * ctx : ctxs) {
  1910. ggml_free(ctx);
  1911. }
  1912. for (ggml_backend_buffer_t buf : bufs) {
  1913. #ifdef GGML_USE_CUDA
  1914. if (ggml_backend_buffer_get_type(buf) == ggml_backend_cpu_buffer_type()) {
  1915. ggml_backend_cuda_unregister_host_buffer(ggml_backend_buffer_get_base(buf));
  1916. }
  1917. #endif
  1918. ggml_backend_buffer_free(buf);
  1919. }
  1920. }
  1921. };
  1922. struct llama_context {
  1923. llama_context(const llama_model & model) : model(model), t_start_us(model.t_start_us), t_load_us(model.t_load_us) {}
  1924. ~llama_context() {
  1925. ggml_backend_sched_free(sched);
  1926. for (ggml_backend_t backend : backends) {
  1927. ggml_backend_free(backend);
  1928. }
  1929. ggml_backend_buffer_free(buf_output);
  1930. }
  1931. llama_cparams cparams;
  1932. std::vector<ggml_backend_t> backends;
  1933. #ifdef GGML_USE_METAL
  1934. ggml_backend_t backend_metal = nullptr;
  1935. #endif
  1936. ggml_backend_t backend_cpu = nullptr;
  1937. const llama_model & model;
  1938. // key + value cache for the self attention
  1939. struct llama_kv_cache kv_self;
  1940. std::mt19937 rng;
  1941. bool has_evaluated_once = false;
  1942. int64_t t_start_us;
  1943. int64_t t_load_us;
  1944. int64_t t_sample_us = 0;
  1945. int64_t t_p_eval_us = 0;
  1946. int64_t t_eval_us = 0;
  1947. int64_t t_compute_start_us = 0;
  1948. int64_t n_queued_tokens = 0;
  1949. int32_t n_sample = 0; // number of tokens sampled
  1950. int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1)
  1951. int32_t n_eval = 0; // number of eval calls
  1952. // host buffer for the model output (logits and embeddings)
  1953. ggml_backend_buffer_t buf_output = nullptr;
  1954. // decode output (2-dimensional array: [n_outputs][n_vocab])
  1955. size_t logits_size = 0; // capacity (of floats) for logits
  1956. float * logits = nullptr;
  1957. std::vector<int32_t> output_ids; // map batch token positions to ids of the logits and embd buffers
  1958. size_t output_size = 0; // capacity (of tokens positions) for the output buffers
  1959. int32_t n_outputs = 0; // number of actually-used outputs in the current ubatch or last logical batch
  1960. bool logits_all = false;
  1961. // embeddings output (2-dimensional array: [n_outputs][n_embd])
  1962. // populated only when pooling_type == LLAMA_POOLING_TYPE_NONE
  1963. size_t embd_size = 0; // capacity (of floats) for embeddings
  1964. float * embd = nullptr;
  1965. // sequence embeddings output (map of [n_embd] vectors)
  1966. // populated only when pooling_type != LLAMA_POOLING_TYPE_NONE
  1967. std::map<llama_seq_id, std::vector<float>> embd_seq;
  1968. // memory buffers used to evaluate the model
  1969. std::vector<uint8_t> buf_compute_meta;
  1970. ggml_backend_sched_t sched = nullptr;
  1971. ggml_abort_callback abort_callback = nullptr;
  1972. void * abort_callback_data = nullptr;
  1973. // input tensors
  1974. struct ggml_tensor * inp_tokens; // I32 [n_batch]
  1975. struct ggml_tensor * inp_embd; // F32 [n_embd, n_batch]
  1976. struct ggml_tensor * inp_pos; // I32 [n_batch]
  1977. struct ggml_tensor * inp_out_ids; // I32 [n_outputs]
  1978. struct ggml_tensor * inp_KQ_mask; // F32 [kv_size, n_batch]
  1979. struct ggml_tensor * inp_KQ_pos; // F32 [n_kv]
  1980. struct ggml_tensor * inp_K_shift; // I32 [kv_size]
  1981. struct ggml_tensor * inp_mean; // F32 [n_batch, n_batch]
  1982. struct ggml_tensor * inp_cls; // I32 [n_batch]
  1983. struct ggml_tensor * inp_s_copy; // I32 [kv_size]
  1984. struct ggml_tensor * inp_s_mask; // F32 [1, n_kv]
  1985. struct ggml_tensor * inp_s_seq; // I32 [n_kv, n_batch]
  1986. // control vectors
  1987. struct llama_control_vector cvec;
  1988. #ifdef GGML_USE_MPI
  1989. ggml_mpi_context * ctx_mpi = NULL;
  1990. #endif
  1991. };
  1992. //
  1993. // kv cache helpers
  1994. //
  1995. static bool llama_kv_cache_init(
  1996. struct llama_kv_cache & cache,
  1997. const llama_model & model,
  1998. ggml_type type_k,
  1999. ggml_type type_v,
  2000. uint32_t kv_size,
  2001. bool offload) {
  2002. const struct llama_hparams & hparams = model.hparams;
  2003. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  2004. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  2005. const int64_t n_layer = hparams.n_layer;
  2006. cache.has_shift = false;
  2007. // TODO: find a nicer way to add other recurrent model architectures
  2008. cache.recurrent = model.arch == LLM_ARCH_MAMBA;
  2009. // TODO: support mixed reccurent Transformer architectues
  2010. // NOTE: (!a || b) is a logical implication (a -> b)
  2011. GGML_ASSERT(!cache.recurrent || n_embd_k_gqa == hparams.n_embd_k_s());
  2012. GGML_ASSERT(!cache.recurrent || n_embd_v_gqa == hparams.n_embd_v_s());
  2013. GGML_ASSERT( cache.recurrent || n_embd_k_gqa == hparams.n_embd_k_gqa());
  2014. GGML_ASSERT( cache.recurrent || n_embd_v_gqa == hparams.n_embd_v_gqa());
  2015. cache.head = 0;
  2016. cache.size = kv_size;
  2017. cache.used = 0;
  2018. cache.type_k = type_k;
  2019. cache.type_v = type_v;
  2020. cache.cells.clear();
  2021. cache.cells.resize(kv_size);
  2022. if (cache.recurrent) {
  2023. // init state copy sources
  2024. for (uint32_t i = 0; i < cache.size; ++i) {
  2025. cache.cells[i].src = i;
  2026. }
  2027. }
  2028. #ifdef GGML_USE_CLBLAST
  2029. offload = false;
  2030. #endif
  2031. // count used buffer types
  2032. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  2033. if (offload) {
  2034. for (int64_t i = 0; i < n_layer; ++i) {
  2035. buft_layer_count[model.buft_layer[i].buft]++;
  2036. }
  2037. } else {
  2038. buft_layer_count[llama_default_buffer_type_cpu(true)] = n_layer;
  2039. }
  2040. // create a context for each buffer type
  2041. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  2042. for (auto & it : buft_layer_count) {
  2043. int n_layers = it.second;
  2044. struct ggml_init_params params = {
  2045. /*.mem_size =*/ 2u*n_layers*ggml_tensor_overhead(),
  2046. /*.mem_buffer =*/ NULL,
  2047. /*.no_alloc =*/ true,
  2048. };
  2049. ggml_context * ctx = ggml_init(params);
  2050. if (!ctx) {
  2051. LLAMA_LOG_ERROR("%s: failed to allocate context for kv cache\n", __func__);
  2052. return false;
  2053. }
  2054. ctx_map[it.first] = ctx;
  2055. cache.ctxs.push_back(ctx);
  2056. }
  2057. cache.k_l.reserve(n_layer);
  2058. cache.v_l.reserve(n_layer);
  2059. for (int i = 0; i < (int) n_layer; i++) {
  2060. struct ggml_context * ctx = offload ? ctx_map.at(model.buft_layer[i].buft) : cache.ctxs.front();
  2061. ggml_tensor * k = ggml_new_tensor_1d(ctx, type_k, n_embd_k_gqa*kv_size);
  2062. ggml_tensor * v = ggml_new_tensor_1d(ctx, type_v, n_embd_v_gqa*kv_size);
  2063. ggml_format_name(k, "cache_k_l%d", i);
  2064. ggml_format_name(v, "cache_v_l%d", i);
  2065. cache.k_l.push_back(k);
  2066. cache.v_l.push_back(v);
  2067. }
  2068. // allocate tensors and initialize the buffers to avoid NaNs in the padding
  2069. for (auto it : ctx_map) {
  2070. ggml_backend_buffer_type_t buft = it.first;
  2071. ggml_context * ctx = it.second;
  2072. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  2073. if (!buf) {
  2074. LLAMA_LOG_ERROR("%s: failed to allocate buffer for kv cache\n", __func__);
  2075. return false;
  2076. }
  2077. ggml_backend_buffer_clear(buf, 0);
  2078. 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);
  2079. cache.bufs.push_back(buf);
  2080. }
  2081. return true;
  2082. }
  2083. // find an empty slot of size "n_tokens" in the cache
  2084. // updates the cache head
  2085. // Note: On success, it's important that cache.head points
  2086. // to the first cell of the slot.
  2087. static bool llama_kv_cache_find_slot(
  2088. struct llama_kv_cache & cache,
  2089. const struct llama_batch & batch) {
  2090. const uint32_t n_ctx = cache.size;
  2091. const uint32_t n_tokens = batch.n_tokens;
  2092. if (cache.recurrent) {
  2093. // For recurrent state architectures (like Mamba),
  2094. // each KV cache cell can store the state for a whole sequence.
  2095. llama_seq_id min = cache.size - 1;
  2096. llama_seq_id max = 0;
  2097. for (uint32_t i = 0; i < n_tokens; ++i) {
  2098. for (int32_t j = 0; j < batch.n_seq_id[i]; ++j) {
  2099. llama_seq_id seq_id = batch.seq_id[i][j];
  2100. // make sure it's a valid seq_id
  2101. if ((uint32_t) seq_id < cache.size) {
  2102. if (seq_id > max) {
  2103. max = seq_id;
  2104. }
  2105. if (seq_id < min) {
  2106. min = seq_id;
  2107. }
  2108. // Assuming the tokens are in-order
  2109. if (batch.pos[i] != cache.cells[seq_id].pos + 1) {
  2110. // What should happen when the pos backtracks or skips a value?
  2111. // Clearing the state mid-batch would require special-casing which isn't done.
  2112. LLAMA_LOG_WARN("%s: non-consecutive token position %d after %d for sequence %d\n",
  2113. __func__, batch.pos[i], cache.cells[seq_id].pos, seq_id);
  2114. }
  2115. if (cache.cells[seq_id].pos < 0 && 0 <= batch.pos[i]) {
  2116. cache.used += 1;
  2117. }
  2118. cache.cells[seq_id].pos = batch.pos[i];
  2119. // NOTE: seq_ids are not inserted here; they are handled when the input tensors are set
  2120. } else {
  2121. // too big seq_id
  2122. // TODO: would it be possible to resize the KV cache size instead?
  2123. LLAMA_LOG_ERROR("%s: seq_id=%d >= kv_size=%d Try using a bigger --parallel value\n", __func__, seq_id, cache.size);
  2124. return false;
  2125. }
  2126. }
  2127. }
  2128. // allow getting the range of used cells, from head to head + n
  2129. cache.head = min;
  2130. cache.n = max - min + 1;
  2131. // sanity check
  2132. return max >= min;
  2133. }
  2134. // otherwise, one cell per token.
  2135. if (n_tokens > n_ctx) {
  2136. LLAMA_LOG_ERROR("%s: n_tokens=%d > n_ctx=%d\n", __func__, n_tokens, n_ctx);
  2137. return false;
  2138. }
  2139. uint32_t n_tested = 0;
  2140. while (true) {
  2141. if (cache.head + n_tokens > n_ctx) {
  2142. n_tested += n_ctx - cache.head;
  2143. cache.head = 0;
  2144. continue;
  2145. }
  2146. bool found = true;
  2147. for (uint32_t i = 0; i < n_tokens; i++) {
  2148. if (cache.cells[cache.head + i].pos >= 0) {
  2149. found = false;
  2150. cache.head += i + 1;
  2151. n_tested += i + 1;
  2152. break;
  2153. }
  2154. }
  2155. if (found) {
  2156. break;
  2157. }
  2158. if (n_tested >= n_ctx) {
  2159. //LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens);
  2160. return false;
  2161. }
  2162. }
  2163. for (uint32_t i = 0; i < n_tokens; i++) {
  2164. cache.cells[cache.head + i].pos = batch.pos[i];
  2165. for (int32_t j = 0; j < batch.n_seq_id[i]; j++) {
  2166. cache.cells[cache.head + i].seq_id.insert(batch.seq_id[i][j]);
  2167. }
  2168. }
  2169. cache.used += n_tokens;
  2170. return true;
  2171. }
  2172. // find how many cells are currently in use
  2173. static uint32_t llama_kv_cache_cell_max(const struct llama_kv_cache & cache) {
  2174. for (uint32_t i = cache.size; i > 0; --i) {
  2175. const llama_kv_cell & cell = cache.cells[i - 1];
  2176. if (cell.pos >= 0 && !cell.is_empty()) {
  2177. return i;
  2178. }
  2179. }
  2180. return 0;
  2181. }
  2182. static void llama_kv_cache_clear(struct llama_kv_cache & cache) {
  2183. for (int32_t i = 0; i < (int32_t) cache.size; ++i) {
  2184. cache.cells[i].pos = -1;
  2185. cache.cells[i].seq_id.clear();
  2186. }
  2187. cache.head = 0;
  2188. cache.used = 0;
  2189. }
  2190. static bool llama_kv_cache_seq_rm(
  2191. struct llama_kv_cache & cache,
  2192. llama_seq_id seq_id,
  2193. llama_pos p0,
  2194. llama_pos p1) {
  2195. uint32_t new_head = cache.size;
  2196. if (p0 < 0) p0 = 0;
  2197. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2198. // models like Mamba can't have a state partially erased
  2199. if (cache.recurrent) {
  2200. if (seq_id >= (int64_t) cache.size) {
  2201. // could be fatal
  2202. return false;
  2203. }
  2204. if (0 <= seq_id) {
  2205. // partial intersection is invalid
  2206. if ((0 < p0 && p0 <= cache.cells[seq_id].pos) || (0 < p1 && p1 <= cache.cells[seq_id].pos)) {
  2207. return false;
  2208. }
  2209. } else {
  2210. // seq_id is negative, then the range should include everything or nothing
  2211. if (p0 != p1 && (p0 != 0 || p1 != std::numeric_limits<llama_pos>::max())) {
  2212. return false;
  2213. }
  2214. }
  2215. }
  2216. for (uint32_t i = 0; i < cache.size; ++i) {
  2217. if (cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2218. if (seq_id < 0) {
  2219. cache.cells[i].seq_id.clear();
  2220. } else if (cache.cells[i].has_seq_id(seq_id)) {
  2221. cache.cells[i].seq_id.erase(seq_id);
  2222. } else {
  2223. continue;
  2224. }
  2225. if (cache.cells[i].is_empty()) {
  2226. // keep count of the number of used cells
  2227. if (cache.cells[i].pos >= 0) cache.used--;
  2228. cache.cells[i].pos = -1;
  2229. if (new_head == cache.size) new_head = i;
  2230. }
  2231. }
  2232. }
  2233. // If we freed up a slot, set head to it so searching can start there.
  2234. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  2235. return true;
  2236. }
  2237. static void llama_kv_cache_seq_cp(
  2238. struct llama_kv_cache & cache,
  2239. llama_seq_id seq_id_src,
  2240. llama_seq_id seq_id_dst,
  2241. llama_pos p0,
  2242. llama_pos p1) {
  2243. if (p0 < 0) p0 = 0;
  2244. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2245. if (cache.recurrent) {
  2246. if ((uint32_t) seq_id_dst < cache.size && (uint32_t) seq_id_src < cache.size) {
  2247. seq_id_src = cache.cells[seq_id_src].src;
  2248. GGML_ASSERT((uint32_t) seq_id_src < cache.size);
  2249. // intent to "copy from"
  2250. // supports copy chains thanks to taking the source of the source
  2251. cache.cells[seq_id_dst].src = seq_id_src;
  2252. // preserve the "keep or clear" status of the copied sequence
  2253. if (cache.cells[seq_id_src].has_seq_id(seq_id_src)) {
  2254. cache.cells[seq_id_dst].seq_id.insert(seq_id_dst);
  2255. } else {
  2256. cache.cells[seq_id_dst].seq_id.erase(seq_id_dst);
  2257. }
  2258. cache.do_copy = true;
  2259. cache.cells[seq_id_dst].pos = cache.cells[seq_id_src].pos;
  2260. }
  2261. return;
  2262. }
  2263. // otherwise, this is the KV cache of a Transformer-like model
  2264. cache.head = 0;
  2265. for (uint32_t i = 0; i < cache.size; ++i) {
  2266. if (cache.cells[i].has_seq_id(seq_id_src) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2267. cache.cells[i].seq_id.insert(seq_id_dst);
  2268. }
  2269. }
  2270. }
  2271. static void llama_kv_cache_seq_keep(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  2272. uint32_t new_head = cache.size;
  2273. for (uint32_t i = 0; i < cache.size; ++i) {
  2274. if (!cache.cells[i].has_seq_id(seq_id)) {
  2275. if (cache.cells[i].pos >= 0) cache.used--;
  2276. cache.cells[i].pos = -1;
  2277. cache.cells[i].seq_id.clear();
  2278. if (new_head == cache.size) new_head = i;
  2279. } else {
  2280. cache.cells[i].seq_id.clear();
  2281. cache.cells[i].seq_id.insert(seq_id);
  2282. }
  2283. }
  2284. // If we freed up a slot, set head to it so searching can start there.
  2285. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  2286. }
  2287. static void llama_kv_cache_seq_add(
  2288. struct llama_kv_cache & cache,
  2289. llama_seq_id seq_id,
  2290. llama_pos p0,
  2291. llama_pos p1,
  2292. llama_pos delta) {
  2293. uint32_t new_head = cache.size;
  2294. if (p0 < 0) p0 = 0;
  2295. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2296. if (cache.recurrent) {
  2297. // for Mamba-like models, only the pos needs to be shifted
  2298. if (0 <= seq_id && seq_id < (int64_t) cache.size) {
  2299. llama_kv_cell & cell = cache.cells[seq_id];
  2300. if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
  2301. cell.pos += delta;
  2302. }
  2303. }
  2304. return;
  2305. }
  2306. for (uint32_t i = 0; i < cache.size; ++i) {
  2307. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2308. cache.has_shift = true;
  2309. cache.cells[i].pos += delta;
  2310. cache.cells[i].delta += delta;
  2311. if (cache.cells[i].pos < 0) {
  2312. if (!cache.cells[i].is_empty()) {
  2313. cache.used--;
  2314. }
  2315. cache.cells[i].pos = -1;
  2316. cache.cells[i].seq_id.clear();
  2317. if (new_head == cache.size) {
  2318. new_head = i;
  2319. }
  2320. }
  2321. }
  2322. }
  2323. // If we freed up a slot, set head to it so searching can start there.
  2324. // Otherwise we just start the next search from the beginning.
  2325. cache.head = new_head != cache.size ? new_head : 0;
  2326. }
  2327. static void llama_kv_cache_seq_div(
  2328. struct llama_kv_cache & cache,
  2329. llama_seq_id seq_id,
  2330. llama_pos p0,
  2331. llama_pos p1,
  2332. int d) {
  2333. if (p0 < 0) p0 = 0;
  2334. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2335. if (cache.recurrent) {
  2336. // for Mamba-like models, only the pos needs to be changed
  2337. if (0 <= seq_id && seq_id < (int64_t) cache.size) {
  2338. llama_kv_cell & cell = cache.cells[seq_id];
  2339. if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
  2340. cell.pos /= d;
  2341. }
  2342. }
  2343. return;
  2344. }
  2345. for (uint32_t i = 0; i < cache.size; ++i) {
  2346. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2347. cache.has_shift = true;
  2348. {
  2349. llama_pos p_old = cache.cells[i].pos;
  2350. cache.cells[i].pos /= d;
  2351. cache.cells[i].delta += cache.cells[i].pos - p_old;
  2352. }
  2353. }
  2354. }
  2355. }
  2356. static llama_pos llama_kv_cache_seq_pos_max(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  2357. llama_pos result = 0;
  2358. for (uint32_t i = 0; i < cache.size; ++i) {
  2359. if (cache.cells[i].has_seq_id(seq_id)) {
  2360. result = std::max(result, cache.cells[i].pos);
  2361. }
  2362. }
  2363. return result;
  2364. }
  2365. static void llama_kv_cache_defrag(struct llama_kv_cache & cache) {
  2366. cache.do_defrag = true;
  2367. }
  2368. //
  2369. // model loading and saving
  2370. //
  2371. enum llama_fver {
  2372. GGUF_FILE_VERSION_V1 = 1,
  2373. GGUF_FILE_VERSION_V2 = 2,
  2374. GGUF_FILE_VERSION_V3 = 3,
  2375. };
  2376. static const char * llama_file_version_name(llama_fver version) {
  2377. switch (version) {
  2378. case GGUF_FILE_VERSION_V1: return "GGUF V1 (support until nov 2023)";
  2379. case GGUF_FILE_VERSION_V2: return "GGUF V2";
  2380. case GGUF_FILE_VERSION_V3: return "GGUF V3 (latest)";
  2381. }
  2382. return "unknown";
  2383. }
  2384. static std::string llama_format_tensor_shape(const std::vector<int64_t> & ne) {
  2385. char buf[256];
  2386. snprintf(buf, sizeof(buf), "%5" PRId64, ne.at(0));
  2387. for (size_t i = 1; i < ne.size(); i++) {
  2388. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, ne.at(i));
  2389. }
  2390. return buf;
  2391. }
  2392. static std::string llama_format_tensor_shape(const struct ggml_tensor * t) {
  2393. char buf[256];
  2394. snprintf(buf, sizeof(buf), "%5" PRId64, t->ne[0]);
  2395. for (int i = 1; i < GGML_MAX_DIMS; i++) {
  2396. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, t->ne[i]);
  2397. }
  2398. return buf;
  2399. }
  2400. namespace GGUFMeta {
  2401. template <typename T, gguf_type gt_, T (*gfun)(const gguf_context *, const int)>
  2402. struct GKV_Base_Type {
  2403. static constexpr gguf_type gt = gt_;
  2404. static T getter(const gguf_context * ctx, const int kid) {
  2405. return gfun(ctx, kid);
  2406. }
  2407. };
  2408. template<typename T> struct GKV_Base;
  2409. template<> struct GKV_Base<bool >: GKV_Base_Type<bool, GGUF_TYPE_BOOL, gguf_get_val_bool> {};
  2410. template<> struct GKV_Base<uint8_t >: GKV_Base_Type<uint8_t, GGUF_TYPE_UINT8, gguf_get_val_u8 > {};
  2411. template<> struct GKV_Base<uint16_t >: GKV_Base_Type<uint16_t, GGUF_TYPE_UINT16, gguf_get_val_u16 > {};
  2412. template<> struct GKV_Base<uint32_t >: GKV_Base_Type<uint32_t, GGUF_TYPE_UINT32, gguf_get_val_u32 > {};
  2413. template<> struct GKV_Base<uint64_t >: GKV_Base_Type<uint64_t, GGUF_TYPE_UINT64, gguf_get_val_u64 > {};
  2414. template<> struct GKV_Base<int8_t >: GKV_Base_Type<int8_t, GGUF_TYPE_INT8, gguf_get_val_i8 > {};
  2415. template<> struct GKV_Base<int16_t >: GKV_Base_Type<int16_t, GGUF_TYPE_INT16, gguf_get_val_i16 > {};
  2416. template<> struct GKV_Base<int32_t >: GKV_Base_Type<int32_t, GGUF_TYPE_INT32, gguf_get_val_i32 > {};
  2417. template<> struct GKV_Base<int64_t >: GKV_Base_Type<int64_t, GGUF_TYPE_INT64, gguf_get_val_i64 > {};
  2418. template<> struct GKV_Base<float >: GKV_Base_Type<float, GGUF_TYPE_FLOAT32, gguf_get_val_f32 > {};
  2419. template<> struct GKV_Base<double >: GKV_Base_Type<double, GGUF_TYPE_FLOAT64, gguf_get_val_f64 > {};
  2420. template<> struct GKV_Base<const char *>: GKV_Base_Type<const char *, GGUF_TYPE_STRING, gguf_get_val_str > {};
  2421. template<> struct GKV_Base<std::string> {
  2422. static constexpr gguf_type gt = GGUF_TYPE_STRING;
  2423. static std::string getter(const gguf_context * ctx, const int kid) {
  2424. return gguf_get_val_str(ctx, kid);
  2425. }
  2426. };
  2427. struct ArrayInfo {
  2428. const gguf_type gt;
  2429. const size_t length;
  2430. const void * data;
  2431. };
  2432. template<> struct GKV_Base<ArrayInfo> {
  2433. public:
  2434. static constexpr gguf_type gt = GGUF_TYPE_ARRAY;
  2435. static ArrayInfo getter(const gguf_context *ctx, const int k) {
  2436. return ArrayInfo {
  2437. gguf_get_arr_type(ctx, k),
  2438. size_t(gguf_get_arr_n(ctx, k)),
  2439. gguf_get_arr_data(ctx, k),
  2440. };
  2441. }
  2442. };
  2443. template<typename T>
  2444. class GKV : public GKV_Base<T> {
  2445. GKV() = delete;
  2446. public:
  2447. static T get_kv(const gguf_context * ctx, const int k) {
  2448. const enum gguf_type kt = gguf_get_kv_type(ctx, k);
  2449. if (kt != GKV::gt) {
  2450. throw std::runtime_error(format("key %s has wrong type %s but expected type %s",
  2451. gguf_get_key(ctx, k), gguf_type_name(kt), gguf_type_name(GKV::gt)));
  2452. }
  2453. return GKV::getter(ctx, k);
  2454. }
  2455. static const char * override_type_to_str(const llama_model_kv_override_type ty) {
  2456. switch (ty) {
  2457. case LLAMA_KV_OVERRIDE_TYPE_BOOL: return "bool";
  2458. case LLAMA_KV_OVERRIDE_TYPE_INT: return "int";
  2459. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: return "float";
  2460. }
  2461. return "unknown";
  2462. }
  2463. static bool validate_override(const llama_model_kv_override_type expected_type, const struct llama_model_kv_override * ovrd) {
  2464. if (!ovrd) { return false; }
  2465. if (ovrd->tag == expected_type) {
  2466. LLAMA_LOG_INFO("%s: Using metadata override (%5s) '%s' = ",
  2467. __func__, override_type_to_str(ovrd->tag), ovrd->key);
  2468. switch (ovrd->tag) {
  2469. case LLAMA_KV_OVERRIDE_TYPE_BOOL: {
  2470. LLAMA_LOG_INFO("%s\n", ovrd->bool_value ? "true" : "false");
  2471. } break;
  2472. case LLAMA_KV_OVERRIDE_TYPE_INT: {
  2473. LLAMA_LOG_INFO("%" PRId64 "\n", ovrd->int_value);
  2474. } break;
  2475. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: {
  2476. LLAMA_LOG_INFO("%.6f\n", ovrd->float_value);
  2477. } break;
  2478. default:
  2479. // Shouldn't be possible to end up here, but just in case...
  2480. throw std::runtime_error(
  2481. format("Unsupported attempt to override %s type for metadata key %s\n",
  2482. override_type_to_str(ovrd->tag), ovrd->key));
  2483. }
  2484. return true;
  2485. }
  2486. LLAMA_LOG_WARN("%s: Warning: Bad metadata override type for key '%s', expected %s but got %s\n",
  2487. __func__, ovrd->key, override_type_to_str(expected_type), override_type_to_str(ovrd->tag));
  2488. return false;
  2489. }
  2490. template<typename OT>
  2491. static typename std::enable_if<std::is_same<OT, bool>::value, bool>::type
  2492. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  2493. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_BOOL, ovrd)) {
  2494. target = ovrd->bool_value;
  2495. return true;
  2496. }
  2497. return false;
  2498. }
  2499. template<typename OT>
  2500. static typename std::enable_if<!std::is_same<OT, bool>::value && std::is_integral<OT>::value, bool>::type
  2501. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  2502. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_INT, ovrd)) {
  2503. target = ovrd->int_value;
  2504. return true;
  2505. }
  2506. return false;
  2507. }
  2508. template<typename OT>
  2509. static typename std::enable_if<std::is_floating_point<OT>::value, bool>::type
  2510. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  2511. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_FLOAT, ovrd)) {
  2512. target = ovrd->float_value;
  2513. return true;
  2514. }
  2515. return false;
  2516. }
  2517. template<typename OT>
  2518. static typename std::enable_if<std::is_same<OT, std::string>::value, bool>::type
  2519. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  2520. (void)target;
  2521. (void)ovrd;
  2522. if (!ovrd) { return false; }
  2523. // Currently, we should never end up here so it would be a bug if we do.
  2524. throw std::runtime_error(format("Unsupported attempt to override string type for metadata key %s\n",
  2525. ovrd ? ovrd->key : "NULL"));
  2526. }
  2527. static bool set(const gguf_context * ctx, const int k, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  2528. if (try_override<T>(target, ovrd)) {
  2529. return true;
  2530. }
  2531. if (k < 0) { return false; }
  2532. target = get_kv(ctx, k);
  2533. return true;
  2534. }
  2535. static bool set(const gguf_context * ctx, const char * key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  2536. return set(ctx, gguf_find_key(ctx, key), target, ovrd);
  2537. }
  2538. static bool set(const gguf_context * ctx, const std::string & key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  2539. return set(ctx, key.c_str(), target, ovrd);
  2540. }
  2541. };
  2542. }
  2543. using llama_buf_map = std::unordered_map<uint32_t, ggml_backend_buffer_t>;
  2544. struct llama_model_loader {
  2545. int n_kv = 0;
  2546. int n_tensors = 0;
  2547. int n_created = 0;
  2548. int64_t n_elements = 0;
  2549. size_t n_bytes = 0;
  2550. bool use_mmap = false;
  2551. llama_files files;
  2552. llama_ftype ftype;
  2553. llama_fver fver;
  2554. llama_mmaps mappings;
  2555. // Holds information on a model weight
  2556. struct llama_tensor_weight {
  2557. uint16_t idx; // source file index
  2558. size_t offs; // tensor data offset in the original file
  2559. ggml_tensor * tensor;
  2560. llama_tensor_weight(uint16_t idx, const char * name, const struct gguf_context * gguf_ctx, ggml_tensor * tensor) : idx(idx), tensor(tensor) {
  2561. const int tensor_idx = gguf_find_tensor(gguf_ctx, name);
  2562. offs = gguf_get_data_offset(gguf_ctx) + gguf_get_tensor_offset(gguf_ctx, tensor_idx);
  2563. }
  2564. };
  2565. std::vector<llama_tensor_weight> weights;
  2566. std::unordered_map<std::string, struct llama_model_kv_override> kv_overrides;
  2567. struct gguf_context * meta = NULL;
  2568. std::vector<ggml_context *> contexts;
  2569. std::string arch_name;
  2570. LLM_KV llm_kv = LLM_KV(LLM_ARCH_UNKNOWN);
  2571. llama_model_loader(const std::string & fname, bool use_mmap, const struct llama_model_kv_override * param_overrides_p) {
  2572. int trace = 0;
  2573. if (getenv("LLAMA_TRACE")) {
  2574. trace = atoi(getenv("LLAMA_TRACE"));
  2575. }
  2576. if (param_overrides_p != nullptr) {
  2577. for (const struct llama_model_kv_override *p = param_overrides_p; p->key[0] != 0; p++) {
  2578. kv_overrides.insert({std::string(p->key), *p});
  2579. }
  2580. }
  2581. struct ggml_context * ctx = NULL;
  2582. struct gguf_init_params params = {
  2583. /*.no_alloc = */ true,
  2584. /*.ctx = */ &ctx,
  2585. };
  2586. meta = gguf_init_from_file(fname.c_str(), params);
  2587. if (!meta) {
  2588. throw std::runtime_error(format("%s: failed to load model from %s\n", __func__, fname.c_str()));
  2589. }
  2590. get_key(llm_kv(LLM_KV_GENERAL_ARCHITECTURE), arch_name, false);
  2591. llm_kv = LLM_KV(llm_arch_from_string(arch_name));
  2592. // Save tensors data offset of the main file.
  2593. // For subsidiary files, `meta` tensor data offset must not be used,
  2594. // so we build a unified tensors index for weights.
  2595. for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  2596. weights.emplace_back(0, cur->name, meta, cur);
  2597. }
  2598. files.emplace_back(new llama_file(fname.c_str(), "rb"));
  2599. contexts.emplace_back(ctx);
  2600. uint16_t n_split = 0;
  2601. get_key(llm_kv(LLM_KV_SPLIT_COUNT), n_split, false);
  2602. // Load additional GGML contexts
  2603. if (n_split > 1) {
  2604. uint16_t idx = 0;
  2605. get_key(llm_kv(LLM_KV_SPLIT_NO), idx);
  2606. if (idx != 0) {
  2607. throw std::runtime_error(format("illegal split file: %d, model must be loaded with the first split", idx));
  2608. }
  2609. char split_prefix[PATH_MAX] = {0};
  2610. if (!llama_split_prefix(split_prefix, sizeof(split_prefix), fname.c_str(), idx, n_split)) {
  2611. throw std::runtime_error(format("invalid split file: %s", fname.c_str()));
  2612. }
  2613. if (trace > 0) {
  2614. LLAMA_LOG_INFO("%s: loading additional %d GGUFs\n", __func__, n_split);
  2615. }
  2616. char split_path[PATH_MAX] = {0};
  2617. for (idx = 1; idx < n_split; idx++) {
  2618. llama_split_path(split_path, sizeof(split_path), split_prefix, idx, n_split);
  2619. struct gguf_init_params split_params = {
  2620. /*.no_alloc = */ true,
  2621. /*.ctx = */ &ctx,
  2622. };
  2623. struct gguf_context * ctx_gguf = gguf_init_from_file(split_path, split_params);
  2624. if (!ctx_gguf) {
  2625. throw std::runtime_error(format("%s: failed to load GGUF split from %s\n", __func__, split_path));
  2626. }
  2627. // Save tensors data offset info of the shard.
  2628. for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  2629. weights.emplace_back(idx, cur->name, ctx_gguf, cur);
  2630. }
  2631. files.emplace_back(new llama_file(split_path, "rb"));
  2632. contexts.emplace_back(ctx);
  2633. gguf_free(ctx_gguf);
  2634. }
  2635. get_key(llm_kv(LLM_KV_SPLIT_TENSORS_COUNT), n_tensors);
  2636. // sanity check
  2637. {
  2638. const int n_tensors_loaded = (int) weights.size();
  2639. if (n_tensors != n_tensors_loaded) {
  2640. throw std::runtime_error(format("corrupted model: %d tensors expected but %d found", n_tensors, n_tensors_loaded));
  2641. }
  2642. }
  2643. LLAMA_LOG_INFO("%s: additional %d GGUFs metadata loaded.\n", __func__, n_split - 1);
  2644. }
  2645. n_kv = gguf_get_n_kv(meta);
  2646. n_tensors = weights.size();
  2647. fver = (enum llama_fver) gguf_get_version(meta);
  2648. for (auto & w : weights) {
  2649. n_elements += ggml_nelements(w.tensor);
  2650. n_bytes += ggml_nbytes(w.tensor);
  2651. }
  2652. LLAMA_LOG_INFO("%s: loaded meta data with %d key-value pairs and %d tensors from %s (version %s)\n",
  2653. __func__, n_kv, n_tensors, fname.c_str(), llama_file_version_name(fver));
  2654. // determine file type based on the number of tensors for each quantization and print meta data
  2655. // TODO: make optional
  2656. {
  2657. std::map<enum ggml_type, uint32_t> n_type;
  2658. uint32_t n_type_max = 0;
  2659. enum ggml_type type_max = GGML_TYPE_F32;
  2660. for (int i = 0; i < n_tensors; i++) {
  2661. const ggml_tensor * tensor = weights.at(i).tensor;
  2662. enum ggml_type type = tensor->type;
  2663. n_type[type]++;
  2664. if (n_type_max < n_type[type]) {
  2665. n_type_max = n_type[type];
  2666. type_max = type;
  2667. }
  2668. if (trace > 0) {
  2669. const uint16_t sid = weights.at(i).idx;
  2670. 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());
  2671. }
  2672. }
  2673. switch (type_max) {
  2674. case GGML_TYPE_F32: ftype = LLAMA_FTYPE_ALL_F32; break;
  2675. case GGML_TYPE_F16: ftype = LLAMA_FTYPE_MOSTLY_F16; break;
  2676. case GGML_TYPE_Q4_0: ftype = LLAMA_FTYPE_MOSTLY_Q4_0; break;
  2677. case GGML_TYPE_Q4_1: ftype = LLAMA_FTYPE_MOSTLY_Q4_1; break;
  2678. case GGML_TYPE_Q5_0: ftype = LLAMA_FTYPE_MOSTLY_Q5_0; break;
  2679. case GGML_TYPE_Q5_1: ftype = LLAMA_FTYPE_MOSTLY_Q5_1; break;
  2680. case GGML_TYPE_Q8_0: ftype = LLAMA_FTYPE_MOSTLY_Q8_0; break;
  2681. case GGML_TYPE_Q2_K: ftype = LLAMA_FTYPE_MOSTLY_Q2_K; break;
  2682. case GGML_TYPE_Q3_K: ftype = LLAMA_FTYPE_MOSTLY_Q3_K_M; break;
  2683. case GGML_TYPE_Q4_K: ftype = LLAMA_FTYPE_MOSTLY_Q4_K_M; break;
  2684. case GGML_TYPE_Q5_K: ftype = LLAMA_FTYPE_MOSTLY_Q5_K_M; break;
  2685. case GGML_TYPE_Q6_K: ftype = LLAMA_FTYPE_MOSTLY_Q6_K; break;
  2686. case GGML_TYPE_IQ2_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XXS; break;
  2687. case GGML_TYPE_IQ2_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XS; break;
  2688. case GGML_TYPE_IQ2_S: ftype = LLAMA_FTYPE_MOSTLY_IQ2_S; break;
  2689. case GGML_TYPE_IQ3_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ3_XXS; break;
  2690. case GGML_TYPE_IQ1_S: ftype = LLAMA_FTYPE_MOSTLY_IQ1_S; break;
  2691. case GGML_TYPE_IQ1_M: ftype = LLAMA_FTYPE_MOSTLY_IQ1_M; break;
  2692. case GGML_TYPE_IQ4_NL: ftype = LLAMA_FTYPE_MOSTLY_IQ4_NL; break;
  2693. case GGML_TYPE_IQ4_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ4_XS; break;
  2694. case GGML_TYPE_IQ3_S: ftype = LLAMA_FTYPE_MOSTLY_IQ3_S; break;
  2695. default:
  2696. {
  2697. LLAMA_LOG_WARN("%s: unknown type %s\n", __func__, ggml_type_name(type_max));
  2698. ftype = LLAMA_FTYPE_ALL_F32;
  2699. } break;
  2700. }
  2701. // this is a way to mark that we have "guessed" the file type
  2702. ftype = (llama_ftype) (ftype | LLAMA_FTYPE_GUESSED);
  2703. {
  2704. const int kid = gguf_find_key(meta, "general.file_type");
  2705. if (kid >= 0) {
  2706. ftype = (llama_ftype) gguf_get_val_u32(meta, kid);
  2707. }
  2708. }
  2709. LLAMA_LOG_INFO("%s: Dumping metadata keys/values. Note: KV overrides do not apply in this output.\n", __func__);
  2710. for (int i = 0; i < n_kv; i++) {
  2711. const char * name = gguf_get_key(meta, i);
  2712. const enum gguf_type type = gguf_get_kv_type(meta, i);
  2713. const std::string type_name =
  2714. type == GGUF_TYPE_ARRAY
  2715. ? format("%s[%s,%d]", gguf_type_name(type), gguf_type_name(gguf_get_arr_type(meta, i)), gguf_get_arr_n(meta, i))
  2716. : gguf_type_name(type);
  2717. std::string value = gguf_kv_to_str(meta, i);
  2718. const size_t MAX_VALUE_LEN = 40;
  2719. if (value.size() > MAX_VALUE_LEN) {
  2720. value = format("%s...", value.substr(0, MAX_VALUE_LEN - 3).c_str());
  2721. }
  2722. replace_all(value, "\n", "\\n");
  2723. LLAMA_LOG_INFO("%s: - kv %3d: %42s %-16s = %s\n", __func__, i, name, type_name.c_str(), value.c_str());
  2724. }
  2725. // print type counts
  2726. for (auto & kv : n_type) {
  2727. if (kv.second == 0) {
  2728. continue;
  2729. }
  2730. LLAMA_LOG_INFO("%s: - type %4s: %4d tensors\n", __func__, ggml_type_name(kv.first), kv.second);
  2731. }
  2732. }
  2733. if (!llama_mmap::SUPPORTED) {
  2734. LLAMA_LOG_WARN("%s: mmap is not supported on this platform\n", __func__);
  2735. use_mmap = false;
  2736. }
  2737. this->use_mmap = use_mmap;
  2738. }
  2739. ~llama_model_loader() {
  2740. if (meta) {
  2741. gguf_free(meta);
  2742. }
  2743. for (auto * ctx : contexts) {
  2744. ggml_free(ctx);
  2745. }
  2746. }
  2747. template<typename T>
  2748. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2749. get_arr_n(const std::string & key, T & result, const bool required = true) {
  2750. const int kid = gguf_find_key(meta, key.c_str());
  2751. if (kid < 0) {
  2752. if (required) {
  2753. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2754. }
  2755. return false;
  2756. }
  2757. struct GGUFMeta::ArrayInfo arr_info =
  2758. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(meta, kid);
  2759. result = arr_info.length;
  2760. return true;
  2761. }
  2762. template<typename T>
  2763. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2764. get_arr_n(const enum llm_kv kid, T & result, const bool required = true) {
  2765. return get_arr_n(llm_kv(kid), result, required);
  2766. }
  2767. template<typename T>
  2768. bool get_key(const std::string & key, T & result, const bool required = true) {
  2769. auto it = kv_overrides.find(key);
  2770. const struct llama_model_kv_override * override =
  2771. it != kv_overrides.end() ? &it->second : nullptr;
  2772. const bool found = GGUFMeta::GKV<T>::set(meta, key, result, override);
  2773. if (required && !found) {
  2774. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2775. }
  2776. return found;
  2777. }
  2778. template<typename T>
  2779. bool get_key(const enum llm_kv kid, T & result, const bool required = true) {
  2780. return get_key(llm_kv(kid), result, required);
  2781. }
  2782. std::string get_arch_name() const {
  2783. return arch_name;
  2784. }
  2785. enum llm_arch get_arch() const {
  2786. return llm_kv.arch;
  2787. }
  2788. const char * get_tensor_name(int i) const {
  2789. return weights.at(i).tensor->name;
  2790. }
  2791. const llama_tensor_weight * get_weight(const char * name) const {
  2792. for (const auto & weight : weights) {
  2793. if (strcmp(name, weight.tensor->name) == 0) {
  2794. return &weight;
  2795. }
  2796. }
  2797. return nullptr;
  2798. }
  2799. const llama_tensor_weight & require_weight(const char * name) const {
  2800. const llama_tensor_weight * weight = get_weight(name);
  2801. if (!weight) {
  2802. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name));
  2803. }
  2804. return *weight;
  2805. }
  2806. struct ggml_tensor * get_tensor_meta(const char * name) const {
  2807. const auto * weight = get_weight(name);
  2808. if (!weight) {
  2809. return nullptr;
  2810. }
  2811. return weight->tensor;
  2812. }
  2813. struct ggml_tensor * require_tensor_meta(const char * name) const {
  2814. struct ggml_tensor * tensor = get_tensor_meta(name);
  2815. if (!tensor) {
  2816. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name));
  2817. }
  2818. return tensor;
  2819. }
  2820. struct ggml_tensor * get_tensor_meta(int i) const {
  2821. return get_tensor_meta(get_tensor_name(i));
  2822. }
  2823. struct ggml_tensor * create_tensor_for(struct ggml_context * ctx, const struct ggml_tensor * cur) {
  2824. struct ggml_tensor * tensor = ggml_dup_tensor(ctx, cur);
  2825. ggml_set_name(tensor, ggml_get_name(cur));
  2826. n_created++;
  2827. return tensor;
  2828. }
  2829. const struct ggml_tensor * check_tensor_dims(const std::string & name, const std::vector<int64_t> & ne, bool required) const {
  2830. const struct ggml_tensor * cur = get_tensor_meta(name.c_str());
  2831. if (cur == NULL) {
  2832. if (!required) {
  2833. return NULL;
  2834. }
  2835. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
  2836. }
  2837. {
  2838. bool is_ok = true;
  2839. for (size_t i = 0; i < GGML_MAX_DIMS; ++i) {
  2840. if ((i < ne.size() && ne[i] != cur->ne[i]) || (i >= ne.size() && cur->ne[i] != 1)) {
  2841. is_ok = false;
  2842. break;
  2843. }
  2844. }
  2845. if (!is_ok) {
  2846. throw std::runtime_error(
  2847. format("%s: tensor '%s' has wrong shape; expected %s, got %s",
  2848. __func__, name.c_str(),
  2849. llama_format_tensor_shape(ne).c_str(),
  2850. llama_format_tensor_shape(cur).c_str()));
  2851. }
  2852. }
  2853. return cur;
  2854. }
  2855. struct ggml_tensor * create_tensor(struct ggml_context * ctx, const std::string & name, const std::vector<int64_t> & ne, bool required = true) {
  2856. const struct ggml_tensor * cur = check_tensor_dims(name, ne, required);
  2857. if (cur == NULL) {
  2858. return NULL;
  2859. }
  2860. return create_tensor_for(ctx, cur);
  2861. }
  2862. 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) {
  2863. const struct ggml_tensor * cur = check_tensor_dims(name, ne, required);
  2864. if (cur == NULL) {
  2865. return NULL;
  2866. }
  2867. if (cur->type != base->type) {
  2868. 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)));
  2869. }
  2870. std::array<int64_t, GGML_MAX_DIMS> dims;
  2871. for (size_t i = 0; i < GGML_MAX_DIMS; ++i) {
  2872. dims[i] = i < ne.size() ? ne[i] : 1;
  2873. }
  2874. struct ggml_tensor * tensor = ggml_view_4d(ctx, base,
  2875. dims[0], dims[1], dims[2], dims[3],
  2876. cur->nb[1], cur->nb[2], cur->nb[3],
  2877. offset);
  2878. ggml_set_name(tensor, name.c_str());
  2879. n_created++;
  2880. return tensor;
  2881. }
  2882. void done_getting_tensors() const {
  2883. if (n_created != n_tensors) {
  2884. throw std::runtime_error(format("%s: wrong number of tensors; expected %d, got %d", __func__, n_tensors, n_created));
  2885. }
  2886. }
  2887. void init_mappings(bool prefetch = true, llama_mlocks * mlock_mmaps = nullptr) {
  2888. if (use_mmap) {
  2889. mappings.reserve(files.size());
  2890. mmaps_used.reserve(files.size());
  2891. for (const auto & file : files) {
  2892. std::unique_ptr<llama_mmap> mapping(new llama_mmap(file.get(), prefetch ? -1 : 0, ggml_is_numa()));
  2893. mmaps_used.emplace_back(mapping->size, 0);
  2894. if (mlock_mmaps) {
  2895. std::unique_ptr<llama_mlock> mlock_mmap(new llama_mlock());
  2896. mlock_mmap->init(mapping->addr);
  2897. mlock_mmaps->emplace_back(std::move(mlock_mmap));
  2898. }
  2899. mappings.emplace_back(std::move(mapping));
  2900. }
  2901. }
  2902. // compute the total size of all tensors for progress reporting
  2903. for (auto & w : weights) {
  2904. size_data += ggml_nbytes(w.tensor);
  2905. }
  2906. }
  2907. void get_mapping_range(size_t * first, size_t * last, void ** addr, int idx, ggml_context * ctx) const {
  2908. GGML_ASSERT(!mappings.empty());
  2909. const auto & mapping = mappings.at(idx);
  2910. *first = mapping->size;
  2911. *last = 0;
  2912. *addr = mapping->addr;
  2913. for (ggml_tensor * tensor = ggml_get_first_tensor(ctx); tensor; tensor = ggml_get_next_tensor(ctx, tensor)) {
  2914. try {
  2915. const auto * weight = get_weight(ggml_get_name(tensor));
  2916. if (!weight) {
  2917. continue;
  2918. }
  2919. if (weight->idx != idx) {
  2920. continue;
  2921. }
  2922. *first = std::min(*first, weight->offs);
  2923. *last = std::max(*last, weight->offs + ggml_nbytes(tensor));
  2924. } catch(...) {
  2925. // the tensor is not in the model
  2926. }
  2927. }
  2928. }
  2929. // for backwards compatibility, does not support ggml-backend
  2930. void load_data_for(struct ggml_tensor * cur) const {
  2931. const auto & w = require_weight(ggml_get_name(cur));
  2932. if (use_mmap) {
  2933. const auto & mapping = mappings.at(w.idx);
  2934. if (cur->data == nullptr) {
  2935. cur->data = (uint8_t *)mapping->addr + w.offs;
  2936. } else {
  2937. memcpy(cur->data, (uint8_t *)mapping->addr + w.offs, ggml_nbytes(cur));
  2938. }
  2939. } else {
  2940. GGML_ASSERT(cur->data != nullptr);
  2941. GGML_ASSERT(w.idx < files.size());
  2942. const auto & file = files.at(w.idx);
  2943. file->seek(w.offs, SEEK_SET);
  2944. file->read_raw(cur->data, ggml_nbytes(cur));
  2945. }
  2946. }
  2947. size_t size_done = 0;
  2948. size_t size_data = 0;
  2949. std::vector<std::pair<size_t, size_t>> mmaps_used;
  2950. // Returns false if cancelled by progress_callback
  2951. bool load_all_data(
  2952. struct ggml_context * ctx,
  2953. llama_buf_map & bufs_mmap,
  2954. llama_mlocks * lmlocks,
  2955. llama_progress_callback progress_callback,
  2956. void * progress_callback_user_data) {
  2957. GGML_ASSERT(size_data != 0 && "call init_mappings() first");
  2958. std::vector<no_init<uint8_t>> read_buf;
  2959. for (struct ggml_tensor * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  2960. const auto * weight = get_weight(ggml_get_name(cur));
  2961. if (weight == nullptr) {
  2962. // this can happen with split experts models
  2963. continue;
  2964. }
  2965. if (progress_callback) {
  2966. if (!progress_callback((float) size_done / size_data, progress_callback_user_data)) {
  2967. return false;
  2968. }
  2969. }
  2970. size_t n_size = ggml_nbytes(cur);
  2971. if (use_mmap) {
  2972. const auto & mapping = mappings.at(weight->idx);
  2973. ggml_backend_buffer_t buf_mmap = nullptr;
  2974. if (bufs_mmap.count(weight->idx)) {
  2975. buf_mmap = bufs_mmap.at(weight->idx);
  2976. }
  2977. GGML_ASSERT(buf_mmap || cur->data); // either we have a buffer to allocate the tensor in, or it is already allocated
  2978. if (buf_mmap && cur->data == nullptr) {
  2979. ggml_backend_tensor_alloc(buf_mmap, cur, (uint8_t *) mapping->addr + weight->offs);
  2980. if (lmlocks) {
  2981. const auto & lmlock = lmlocks->at(weight->idx);
  2982. lmlock->grow_to(weight->offs + ggml_nbytes(cur));
  2983. }
  2984. auto & mmap_used = mmaps_used[weight->idx];
  2985. mmap_used.first = std::min(mmap_used.first, weight->offs);
  2986. mmap_used.second = std::max(mmap_used.second, weight->offs + n_size);
  2987. } else {
  2988. ggml_backend_tensor_set(cur, (uint8_t *) mapping->addr + weight->offs, 0, n_size);
  2989. }
  2990. } else {
  2991. GGML_ASSERT(weight->idx < files.size());
  2992. const auto & file = files.at(weight->idx);
  2993. if (ggml_backend_buffer_is_host(cur->buffer)) {
  2994. file->seek(weight->offs, SEEK_SET);
  2995. file->read_raw(cur->data, ggml_nbytes(cur));
  2996. } else {
  2997. read_buf.resize(ggml_nbytes(cur));
  2998. file->seek(weight->offs, SEEK_SET);
  2999. file->read_raw(read_buf.data(), ggml_nbytes(cur));
  3000. ggml_backend_tensor_set(cur, read_buf.data(), 0, n_size);
  3001. }
  3002. }
  3003. size_done += n_size;
  3004. }
  3005. // check if this is the last call and do final cleanup
  3006. if (size_done >= size_data) {
  3007. // unmap offloaded tensors and metadata
  3008. if (use_mmap) {
  3009. for (uint32_t idx = 0; idx < mappings.size(); idx++) {
  3010. const auto & mmap_used = mmaps_used.at(idx);
  3011. auto & mapping = mappings.at(idx);
  3012. mapping->unmap_fragment(0, mmap_used.first);
  3013. if (mmap_used.second != 0) {
  3014. mapping->unmap_fragment(mmap_used.second, mapping->size);
  3015. }
  3016. }
  3017. }
  3018. if (progress_callback) {
  3019. // Even though the model is done loading, we still honor
  3020. // cancellation since we need to free allocations.
  3021. return progress_callback(1.0f, progress_callback_user_data);
  3022. }
  3023. }
  3024. return true;
  3025. }
  3026. };
  3027. template<>
  3028. bool llama_model_loader::get_key(const enum llm_kv kid, enum llama_pooling_type & result, const bool required) {
  3029. uint32_t tmp;
  3030. const bool found = get_key(kid, tmp, required);
  3031. if (found) {
  3032. result = (enum llama_pooling_type) tmp;
  3033. } else {
  3034. result = LLAMA_POOLING_TYPE_UNSPECIFIED;
  3035. }
  3036. return found;
  3037. }
  3038. //
  3039. // load LLaMA models
  3040. //
  3041. static const char * llama_model_arch_name(llm_arch arch) {
  3042. auto it = LLM_ARCH_NAMES.find(arch);
  3043. if (it == LLM_ARCH_NAMES.end()) {
  3044. return "unknown";
  3045. }
  3046. return it->second;
  3047. }
  3048. static std::string llama_model_ftype_name(llama_ftype ftype) {
  3049. if (ftype & LLAMA_FTYPE_GUESSED) {
  3050. return llama_model_ftype_name((enum llama_ftype) (ftype & ~LLAMA_FTYPE_GUESSED)) + " (guessed)";
  3051. }
  3052. switch (ftype) {
  3053. case LLAMA_FTYPE_ALL_F32: return "all F32";
  3054. case LLAMA_FTYPE_MOSTLY_F16: return "F16";
  3055. case LLAMA_FTYPE_MOSTLY_Q4_0: return "Q4_0";
  3056. case LLAMA_FTYPE_MOSTLY_Q4_1: return "Q4_1";
  3057. case LLAMA_FTYPE_MOSTLY_Q4_1_SOME_F16:
  3058. return "Q4_1, some F16";
  3059. case LLAMA_FTYPE_MOSTLY_Q5_0: return "Q5_0";
  3060. case LLAMA_FTYPE_MOSTLY_Q5_1: return "Q5_1";
  3061. case LLAMA_FTYPE_MOSTLY_Q8_0: return "Q8_0";
  3062. // K-quants
  3063. case LLAMA_FTYPE_MOSTLY_Q2_K: return "Q2_K - Medium";
  3064. case LLAMA_FTYPE_MOSTLY_Q2_K_S: return "Q2_K - Small";
  3065. case LLAMA_FTYPE_MOSTLY_Q3_K_S: return "Q3_K - Small";
  3066. case LLAMA_FTYPE_MOSTLY_Q3_K_M: return "Q3_K - Medium";
  3067. case LLAMA_FTYPE_MOSTLY_Q3_K_L: return "Q3_K - Large";
  3068. case LLAMA_FTYPE_MOSTLY_Q4_K_S: return "Q4_K - Small";
  3069. case LLAMA_FTYPE_MOSTLY_Q4_K_M: return "Q4_K - Medium";
  3070. case LLAMA_FTYPE_MOSTLY_Q5_K_S: return "Q5_K - Small";
  3071. case LLAMA_FTYPE_MOSTLY_Q5_K_M: return "Q5_K - Medium";
  3072. case LLAMA_FTYPE_MOSTLY_Q6_K: return "Q6_K";
  3073. case LLAMA_FTYPE_MOSTLY_IQ2_XXS:return "IQ2_XXS - 2.0625 bpw";
  3074. case LLAMA_FTYPE_MOSTLY_IQ2_XS: return "IQ2_XS - 2.3125 bpw";
  3075. case LLAMA_FTYPE_MOSTLY_IQ2_S: return "IQ2_S - 2.5 bpw";
  3076. case LLAMA_FTYPE_MOSTLY_IQ2_M: return "IQ2_M - 2.7 bpw";
  3077. case LLAMA_FTYPE_MOSTLY_IQ3_XS: return "IQ3_XS - 3.3 bpw";
  3078. case LLAMA_FTYPE_MOSTLY_IQ3_XXS:return "IQ3_XXS - 3.0625 bpw";
  3079. case LLAMA_FTYPE_MOSTLY_IQ1_S :return "IQ1_S - 1.5625 bpw";
  3080. case LLAMA_FTYPE_MOSTLY_IQ1_M :return "IQ1_M - 1.75 bpw";
  3081. case LLAMA_FTYPE_MOSTLY_IQ4_NL: return "IQ4_NL - 4.5 bpw";
  3082. case LLAMA_FTYPE_MOSTLY_IQ4_XS: return "IQ4_XS - 4.25 bpw";
  3083. case LLAMA_FTYPE_MOSTLY_IQ3_S: return "IQ3_S - 3.4375 bpw";
  3084. case LLAMA_FTYPE_MOSTLY_IQ3_M: return "IQ3_S mix - 3.66 bpw";
  3085. default: return "unknown, may not work";
  3086. }
  3087. }
  3088. static const char * llama_model_type_name(e_model type) {
  3089. switch (type) {
  3090. case MODEL_22M: return "22M";
  3091. case MODEL_33M: return "33M";
  3092. case MODEL_109M: return "109M";
  3093. case MODEL_137M: return "137M";
  3094. case MODEL_0_5B: return "0.5B";
  3095. case MODEL_1B: return "1B";
  3096. case MODEL_2B: return "2B";
  3097. case MODEL_3B: return "3B";
  3098. case MODEL_7B: return "7B";
  3099. case MODEL_8B: return "8B";
  3100. case MODEL_13B: return "13B";
  3101. case MODEL_14B: return "14B";
  3102. case MODEL_15B: return "15B";
  3103. case MODEL_20B: return "20B";
  3104. case MODEL_30B: return "30B";
  3105. case MODEL_34B: return "34B";
  3106. case MODEL_35B: return "35B";
  3107. case MODEL_40B: return "40B";
  3108. case MODEL_65B: return "65B";
  3109. case MODEL_70B: return "70B";
  3110. case MODEL_314B: return "314B";
  3111. case MODEL_SMALL: return "0.1B";
  3112. case MODEL_MEDIUM: return "0.4B";
  3113. case MODEL_LARGE: return "0.8B";
  3114. case MODEL_XL: return "1.5B";
  3115. case MODEL_8x7B: return "8x7B";
  3116. case MODEL_8x22B: return "8x22B";
  3117. case MODEL_16x12B: return "16x12B";
  3118. default: return "?B";
  3119. }
  3120. }
  3121. static const char * llama_model_vocab_type_name(enum llama_vocab_type type){
  3122. switch (type) {
  3123. case LLAMA_VOCAB_TYPE_NONE: return "no vocab";
  3124. case LLAMA_VOCAB_TYPE_SPM: return "SPM";
  3125. case LLAMA_VOCAB_TYPE_BPE: return "BPE";
  3126. case LLAMA_VOCAB_TYPE_WPM: return "WPM";
  3127. default: return "unknown";
  3128. }
  3129. }
  3130. static void llm_load_arch(llama_model_loader & ml, llama_model & model) {
  3131. model.arch = ml.get_arch();
  3132. if (model.arch == LLM_ARCH_UNKNOWN) {
  3133. throw std::runtime_error("unknown model architecture: '" + ml.get_arch_name() + "'");
  3134. }
  3135. }
  3136. static void llm_load_hparams(
  3137. llama_model_loader & ml,
  3138. llama_model & model) {
  3139. auto & hparams = model.hparams;
  3140. const gguf_context * ctx = ml.meta;
  3141. // get metadata as string
  3142. for (int i = 0; i < gguf_get_n_kv(ctx); i++) {
  3143. enum gguf_type type = gguf_get_kv_type(ctx, i);
  3144. if (type == GGUF_TYPE_ARRAY) {
  3145. continue;
  3146. }
  3147. const char * name = gguf_get_key(ctx, i);
  3148. const std::string value = gguf_kv_to_str(ctx, i);
  3149. model.gguf_kv.emplace(name, value);
  3150. }
  3151. // get general kv
  3152. ml.get_key(LLM_KV_GENERAL_NAME, model.name, false);
  3153. // get hparams kv
  3154. ml.get_key(LLM_KV_VOCAB_SIZE, hparams.n_vocab, false) || ml.get_arr_n(LLM_KV_TOKENIZER_LIST, hparams.n_vocab);
  3155. ml.get_key(LLM_KV_CONTEXT_LENGTH, hparams.n_ctx_train);
  3156. ml.get_key(LLM_KV_EMBEDDING_LENGTH, hparams.n_embd);
  3157. ml.get_key(LLM_KV_FEED_FORWARD_LENGTH, hparams.n_ff);
  3158. ml.get_key(LLM_KV_ATTENTION_HEAD_COUNT, hparams.n_head);
  3159. ml.get_key(LLM_KV_BLOCK_COUNT, hparams.n_layer);
  3160. ml.get_key(LLM_KV_EXPERT_COUNT, hparams.n_expert, false);
  3161. ml.get_key(LLM_KV_EXPERT_USED_COUNT, hparams.n_expert_used, false);
  3162. GGML_ASSERT(hparams.n_expert <= LLAMA_MAX_EXPERTS);
  3163. GGML_ASSERT(hparams.n_expert_used <= hparams.n_expert);
  3164. if (hparams.n_expert > 0) {
  3165. GGML_ASSERT(hparams.n_expert_used > 0);
  3166. } else {
  3167. GGML_ASSERT(hparams.n_expert_used == 0);
  3168. }
  3169. // n_head_kv is optional, default to n_head
  3170. hparams.n_head_kv = hparams.n_head;
  3171. ml.get_key(LLM_KV_ATTENTION_HEAD_COUNT_KV, hparams.n_head_kv, false);
  3172. bool rope_finetuned = false;
  3173. ml.get_key(LLM_KV_ROPE_SCALING_FINETUNED, rope_finetuned, false);
  3174. hparams.rope_finetuned = rope_finetuned;
  3175. hparams.n_yarn_orig_ctx = hparams.n_ctx_train;
  3176. ml.get_key(LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, hparams.n_yarn_orig_ctx, false);
  3177. // rope_freq_base (optional)
  3178. hparams.rope_freq_base_train = 10000.0f;
  3179. ml.get_key(LLM_KV_ROPE_FREQ_BASE, hparams.rope_freq_base_train, false);
  3180. std::string rope_scaling("linear");
  3181. ml.get_key(LLM_KV_ROPE_SCALING_TYPE, rope_scaling, false);
  3182. hparams.rope_scaling_type_train = llama_rope_scaling_type_from_string(rope_scaling);
  3183. GGML_ASSERT(hparams.rope_scaling_type_train != LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED);
  3184. // rope_freq_scale (inverse of the kv) is optional
  3185. float ropescale = 0.0f;
  3186. if (!ml.get_key(LLM_KV_ROPE_SCALING_FACTOR, ropescale, false)) {
  3187. // try the old key name
  3188. ml.get_key(LLM_KV_ROPE_SCALE_LINEAR, ropescale, false);
  3189. }
  3190. hparams.rope_freq_scale_train = ropescale == 0.0f ? 1.0f : 1.0f/ropescale;
  3191. // sanity check for n_rot (optional)
  3192. {
  3193. hparams.n_rot = (hparams.n_head == 0) ? 0 : hparams.n_embd / hparams.n_head;
  3194. ml.get_key(LLM_KV_ROPE_DIMENSION_COUNT, hparams.n_rot, false);
  3195. if (model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON) {
  3196. if (hparams.n_rot != hparams.n_embd / hparams.n_head) {
  3197. throw std::runtime_error(format("invalid n_rot: %u, expected %u", hparams.n_rot, hparams.n_embd / hparams.n_head));
  3198. }
  3199. }
  3200. // gpt-neox n_rot = rotary_pct * (n_embd / n_head)
  3201. // gpt-j n_rot = rotary_dim
  3202. }
  3203. hparams.n_embd_head_k = (hparams.n_head == 0) ? 0 : hparams.n_embd / hparams.n_head;
  3204. ml.get_key(LLM_KV_ATTENTION_KEY_LENGTH, hparams.n_embd_head_k, false);
  3205. hparams.n_embd_head_v = (hparams.n_head == 0) ? 0 : hparams.n_embd / hparams.n_head;
  3206. ml.get_key(LLM_KV_ATTENTION_VALUE_LENGTH, hparams.n_embd_head_v, false);
  3207. // arch-specific KVs
  3208. switch (model.arch) {
  3209. case LLM_ARCH_LLAMA:
  3210. {
  3211. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3212. if (hparams.n_expert == 8) {
  3213. switch (hparams.n_layer) {
  3214. case 32: model.type = e_model::MODEL_8x7B; break;
  3215. case 56: model.type = e_model::MODEL_8x22B; break;
  3216. default: model.type = e_model::MODEL_UNKNOWN;
  3217. }
  3218. } else {
  3219. switch (hparams.n_layer) {
  3220. case 22: model.type = e_model::MODEL_1B; break;
  3221. case 26: model.type = e_model::MODEL_3B; break;
  3222. case 32: model.type = e_model::MODEL_7B; break;
  3223. case 40: model.type = e_model::MODEL_13B; break;
  3224. case 48: model.type = e_model::MODEL_34B; break;
  3225. case 60: model.type = e_model::MODEL_30B; break;
  3226. case 80: model.type = hparams.n_head == hparams.n_head_kv ? e_model::MODEL_65B : e_model::MODEL_70B; break;
  3227. default: model.type = e_model::MODEL_UNKNOWN;
  3228. }
  3229. }
  3230. } break;
  3231. case LLM_ARCH_MINICPM:
  3232. {
  3233. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3234. switch (hparams.n_layer) {
  3235. case 40: model.type = e_model::MODEL_2B; break;
  3236. default: model.type = e_model::MODEL_UNKNOWN;
  3237. }
  3238. } break;
  3239. case LLM_ARCH_GROK:
  3240. {
  3241. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3242. switch (hparams.n_layer) {
  3243. case 64: model.type = e_model::MODEL_314B; break;
  3244. default: model.type = e_model::MODEL_UNKNOWN;
  3245. }
  3246. } break;
  3247. case LLM_ARCH_FALCON:
  3248. {
  3249. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3250. switch (hparams.n_layer) {
  3251. case 32: model.type = e_model::MODEL_7B; break;
  3252. case 60: model.type = e_model::MODEL_40B; break;
  3253. default: model.type = e_model::MODEL_UNKNOWN;
  3254. }
  3255. } break;
  3256. case LLM_ARCH_BAICHUAN:
  3257. {
  3258. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3259. switch (hparams.n_layer) {
  3260. case 32: model.type = e_model::MODEL_7B; break;
  3261. case 40: model.type = e_model::MODEL_13B; break;
  3262. default: model.type = e_model::MODEL_UNKNOWN;
  3263. }
  3264. if (model.type == e_model::MODEL_13B) {
  3265. // TODO: become GGUF KV parameter
  3266. hparams.f_max_alibi_bias = 8.0f;
  3267. }
  3268. } break;
  3269. case LLM_ARCH_STARCODER:
  3270. {
  3271. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3272. switch (hparams.n_layer) {
  3273. case 24: model.type = e_model::MODEL_1B; break;
  3274. case 36: model.type = e_model::MODEL_3B; break;
  3275. case 42: model.type = e_model::MODEL_7B; break;
  3276. case 40: model.type = e_model::MODEL_15B; break;
  3277. default: model.type = e_model::MODEL_UNKNOWN;
  3278. }
  3279. } break;
  3280. case LLM_ARCH_PERSIMMON:
  3281. {
  3282. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3283. switch (hparams.n_layer) {
  3284. case 36: model.type = e_model::MODEL_8B; break;
  3285. default: model.type = e_model::MODEL_UNKNOWN;
  3286. }
  3287. } break;
  3288. case LLM_ARCH_REFACT:
  3289. {
  3290. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3291. switch (hparams.n_layer) {
  3292. case 32: model.type = e_model::MODEL_1B; break;
  3293. default: model.type = e_model::MODEL_UNKNOWN;
  3294. }
  3295. // TODO: become GGUF KV parameter
  3296. hparams.f_max_alibi_bias = 8.0f;
  3297. } break;
  3298. case LLM_ARCH_BERT:
  3299. {
  3300. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3301. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  3302. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  3303. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type, false);
  3304. switch (hparams.n_layer) {
  3305. case 3:
  3306. model.type = e_model::MODEL_17M; break; // bge-micro
  3307. case 6:
  3308. model.type = e_model::MODEL_22M; break; // MiniLM-L6
  3309. case 12:
  3310. switch (hparams.n_embd) {
  3311. case 384: model.type = e_model::MODEL_33M; break; // MiniLM-L12, bge-small
  3312. case 768: model.type = e_model::MODEL_109M; break; // bge-base
  3313. } break;
  3314. case 24:
  3315. model.type = e_model::MODEL_335M; break; // bge-large
  3316. }
  3317. } break;
  3318. case LLM_ARCH_NOMIC_BERT:
  3319. {
  3320. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3321. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  3322. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  3323. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type);
  3324. if (hparams.n_layer == 12 && hparams.n_embd == 768) {
  3325. model.type = e_model::MODEL_137M;
  3326. }
  3327. } break;
  3328. case LLM_ARCH_BLOOM:
  3329. {
  3330. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3331. switch (hparams.n_layer) {
  3332. case 24: model.type = e_model::MODEL_1B; break;
  3333. case 30:
  3334. switch (hparams.n_embd) {
  3335. case 2560: model.type = e_model::MODEL_3B; break;
  3336. case 4096: model.type = e_model::MODEL_7B; break;
  3337. } break;
  3338. }
  3339. // TODO: become GGUF KV parameter
  3340. hparams.f_max_alibi_bias = 8.0f;
  3341. } break;
  3342. case LLM_ARCH_MPT:
  3343. {
  3344. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3345. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv, false);
  3346. ml.get_key(LLM_KV_ATTENTION_MAX_ALIBI_BIAS, hparams.f_max_alibi_bias);
  3347. switch (hparams.n_layer) {
  3348. case 32: model.type = e_model::MODEL_7B; break;
  3349. case 48: model.type = e_model::MODEL_30B; break;
  3350. default: model.type = e_model::MODEL_UNKNOWN;
  3351. }
  3352. } break;
  3353. case LLM_ARCH_STABLELM:
  3354. {
  3355. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3356. switch (hparams.n_layer) {
  3357. case 24: model.type = e_model::MODEL_1B; break;
  3358. case 32: model.type = e_model::MODEL_3B; break;
  3359. default: model.type = e_model::MODEL_UNKNOWN;
  3360. }
  3361. } break;
  3362. case LLM_ARCH_QWEN:
  3363. {
  3364. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3365. switch (hparams.n_layer) {
  3366. case 32: model.type = e_model::MODEL_7B; break;
  3367. case 40: model.type = e_model::MODEL_13B; break;
  3368. default: model.type = e_model::MODEL_UNKNOWN;
  3369. }
  3370. } break;
  3371. case LLM_ARCH_QWEN2:
  3372. {
  3373. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3374. switch (hparams.n_layer) {
  3375. case 24: model.type = hparams.n_embd == 1024 ? e_model::MODEL_0_5B : e_model::MODEL_1B; break;
  3376. case 32: model.type = e_model::MODEL_7B; break;
  3377. case 40: model.type = hparams.n_head == 20 ? e_model::MODEL_4B : e_model::MODEL_13B; break;
  3378. case 80: model.type = e_model::MODEL_70B; break;
  3379. default: model.type = e_model::MODEL_UNKNOWN;
  3380. }
  3381. } break;
  3382. case LLM_ARCH_PHI2:
  3383. {
  3384. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3385. switch (hparams.n_layer) {
  3386. case 24: model.type = e_model::MODEL_1B; break;
  3387. case 32: model.type = e_model::MODEL_3B; break;
  3388. default: model.type = e_model::MODEL_UNKNOWN;
  3389. }
  3390. } break;
  3391. case LLM_ARCH_PLAMO:
  3392. {
  3393. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3394. switch (hparams.n_layer) {
  3395. case 40: model.type = e_model::MODEL_13B; break;
  3396. default: model.type = e_model::MODEL_UNKNOWN;
  3397. }
  3398. } break;
  3399. case LLM_ARCH_GPT2:
  3400. {
  3401. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3402. switch (hparams.n_layer) {
  3403. case 12: model.type = e_model::MODEL_SMALL; break;
  3404. case 24: model.type = e_model::MODEL_MEDIUM; break;
  3405. case 36: model.type = e_model::MODEL_LARGE; break;
  3406. case 48: model.type = e_model::MODEL_XL; break;
  3407. default: model.type = e_model::MODEL_UNKNOWN;
  3408. }
  3409. } break;
  3410. case LLM_ARCH_CODESHELL:
  3411. {
  3412. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3413. switch (hparams.n_layer) {
  3414. case 42: model.type = e_model::MODEL_SMALL; break;
  3415. default: model.type = e_model::MODEL_UNKNOWN;
  3416. }
  3417. } break;
  3418. case LLM_ARCH_ORION:
  3419. {
  3420. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3421. switch (hparams.n_layer) {
  3422. case 40: model.type = e_model::MODEL_14B; break;
  3423. default: model.type = e_model::MODEL_UNKNOWN;
  3424. }
  3425. } break;
  3426. case LLM_ARCH_INTERNLM2:
  3427. {
  3428. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3429. switch (hparams.n_layer) {
  3430. case 32: model.type = e_model::MODEL_7B; break;
  3431. case 48: model.type = e_model::MODEL_20B; break;
  3432. default: model.type = e_model::MODEL_UNKNOWN;
  3433. }
  3434. } break;
  3435. case LLM_ARCH_GEMMA:
  3436. {
  3437. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3438. switch (hparams.n_layer) {
  3439. case 18: model.type = e_model::MODEL_2B; break;
  3440. case 28: model.type = e_model::MODEL_7B; break;
  3441. default: model.type = e_model::MODEL_UNKNOWN;
  3442. }
  3443. } break;
  3444. case LLM_ARCH_STARCODER2:
  3445. {
  3446. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3447. switch (hparams.n_layer) {
  3448. case 30: model.type = e_model::MODEL_3B; break;
  3449. case 32: model.type = e_model::MODEL_7B; break;
  3450. case 40: model.type = e_model::MODEL_15B; break;
  3451. default: model.type = e_model::MODEL_UNKNOWN;
  3452. }
  3453. } break;
  3454. case LLM_ARCH_MAMBA:
  3455. {
  3456. ml.get_key(LLM_KV_SSM_CONV_KERNEL, hparams.ssm_d_conv);
  3457. ml.get_key(LLM_KV_SSM_INNER_SIZE, hparams.ssm_d_inner);
  3458. ml.get_key(LLM_KV_SSM_STATE_SIZE, hparams.ssm_d_state);
  3459. ml.get_key(LLM_KV_SSM_TIME_STEP_RANK, hparams.ssm_dt_rank);
  3460. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3461. switch (hparams.n_layer) {
  3462. case 24:
  3463. switch (hparams.n_embd) {
  3464. case 768: model.type = e_model::MODEL_SMALL; break;
  3465. default: model.type = e_model::MODEL_UNKNOWN;
  3466. } break;
  3467. case 48:
  3468. switch (hparams.n_embd) {
  3469. case 1024: model.type = e_model::MODEL_MEDIUM; break;
  3470. case 1536: model.type = e_model::MODEL_LARGE; break;
  3471. case 2048: model.type = e_model::MODEL_XL; break;
  3472. default: model.type = e_model::MODEL_UNKNOWN;
  3473. } break;
  3474. case 64:
  3475. switch (hparams.n_embd) {
  3476. case 2560: model.type = e_model::MODEL_3B; break;
  3477. default: model.type = e_model::MODEL_UNKNOWN;
  3478. } break;
  3479. default: model.type = e_model::MODEL_UNKNOWN;
  3480. }
  3481. } break;
  3482. case LLM_ARCH_XVERSE:
  3483. {
  3484. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3485. switch (hparams.n_layer) {
  3486. case 32: model.type = e_model::MODEL_7B; break;
  3487. case 40: model.type = e_model::MODEL_13B; break;
  3488. case 80: model.type = e_model::MODEL_65B; break;
  3489. default: model.type = e_model::MODEL_UNKNOWN;
  3490. }
  3491. } break;
  3492. case LLM_ARCH_COMMAND_R:
  3493. {
  3494. ml.get_key(LLM_KV_LOGIT_SCALE, hparams.f_logit_scale);
  3495. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3496. switch (hparams.n_layer) {
  3497. case 40: model.type = e_model::MODEL_35B; break;
  3498. default: model.type = e_model::MODEL_UNKNOWN;
  3499. }
  3500. } break;
  3501. case LLM_ARCH_DBRX:
  3502. {
  3503. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3504. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv);
  3505. switch (hparams.n_layer) {
  3506. case 40: model.type = e_model::MODEL_16x12B; break;
  3507. default: model.type = e_model::MODEL_UNKNOWN;
  3508. }
  3509. } break;
  3510. default: (void)0;
  3511. }
  3512. model.ftype = ml.ftype;
  3513. if (hparams.f_max_alibi_bias > 0.0f) {
  3514. hparams.need_kq_pos = true;
  3515. }
  3516. hparams.rope_type = llama_rope_type(&model);
  3517. }
  3518. // TODO: This should probably be in llama.h
  3519. static std::vector<llama_vocab::id> llama_tokenize_internal(
  3520. const llama_vocab & vocab, std::string raw_text, bool add_special, bool parse_special = false
  3521. );
  3522. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch);
  3523. static void llm_load_vocab(
  3524. llama_model_loader & ml,
  3525. llama_model & model) {
  3526. auto & vocab = model.vocab;
  3527. struct gguf_context * ctx = ml.meta;
  3528. const auto kv = LLM_KV(model.arch);
  3529. // determine vocab type
  3530. {
  3531. std::string tokenizer_name;
  3532. ml.get_key(LLM_KV_TOKENIZER_MODEL, tokenizer_name);
  3533. if (tokenizer_name == "no_vocab") {
  3534. vocab.type = LLAMA_VOCAB_TYPE_NONE;
  3535. // default special tokens
  3536. vocab.special_bos_id = -1;
  3537. vocab.special_eos_id = -1;
  3538. vocab.special_unk_id = -1;
  3539. vocab.special_sep_id = -1;
  3540. vocab.special_pad_id = -1;
  3541. vocab.special_cls_id = -1;
  3542. vocab.special_mask_id = -1;
  3543. vocab.linefeed_id = -1;
  3544. return;
  3545. } else if (tokenizer_name == "llama") {
  3546. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  3547. // default special tokens
  3548. vocab.special_bos_id = 1;
  3549. vocab.special_eos_id = 2;
  3550. vocab.special_unk_id = 0;
  3551. vocab.special_sep_id = -1;
  3552. vocab.special_pad_id = -1;
  3553. vocab.special_cls_id = -1;
  3554. vocab.special_mask_id = -1;
  3555. const int add_space_prefix_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_ADD_PREFIX).c_str());
  3556. if (add_space_prefix_keyidx != -1) {
  3557. vocab.add_space_prefix = gguf_get_val_bool(ctx, add_space_prefix_keyidx);
  3558. } // The default value of add_space_prefix is true.
  3559. } else if (tokenizer_name == "gpt2") {
  3560. vocab.type = LLAMA_VOCAB_TYPE_BPE;
  3561. // read bpe merges and populate bpe ranks
  3562. const int merges_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_MERGES).c_str());
  3563. if (merges_keyidx == -1) {
  3564. throw std::runtime_error("cannot find tokenizer merges in model file\n");
  3565. }
  3566. const int n_merges = gguf_get_arr_n(ctx, merges_keyidx);
  3567. for (int i = 0; i < n_merges; i++) {
  3568. const std::string word = gguf_get_arr_str(ctx, merges_keyidx, i);
  3569. GGML_ASSERT(unicode_cpts_from_utf8(word).size() > 0);
  3570. std::string first;
  3571. std::string second;
  3572. const size_t pos = word.find(' ', 1);
  3573. if (pos != std::string::npos) {
  3574. first = word.substr(0, pos);
  3575. second = word.substr(pos + 1);
  3576. }
  3577. vocab.bpe_ranks.emplace(std::make_pair(first, second), i);
  3578. }
  3579. // default special tokens
  3580. vocab.special_bos_id = 11;
  3581. vocab.special_eos_id = 11;
  3582. vocab.special_unk_id = -1;
  3583. vocab.special_sep_id = -1;
  3584. vocab.special_pad_id = -1;
  3585. vocab.special_cls_id = -1;
  3586. vocab.special_mask_id = -1;
  3587. } else if (tokenizer_name == "bert") {
  3588. vocab.type = LLAMA_VOCAB_TYPE_WPM;
  3589. // default special tokens
  3590. vocab.special_bos_id = -1;
  3591. vocab.special_eos_id = -1;
  3592. vocab.special_unk_id = 100;
  3593. vocab.special_sep_id = 102;
  3594. vocab.special_pad_id = 0;
  3595. vocab.special_cls_id = 101;
  3596. vocab.special_mask_id = 103;
  3597. vocab.add_space_prefix = false;
  3598. } else {
  3599. LLAMA_LOG_WARN("%s: unknown tokenizer: '%s'", __func__, tokenizer_name.c_str());
  3600. LLAMA_LOG_WARN("%s: using default tokenizer: 'llama'", __func__);
  3601. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  3602. }
  3603. }
  3604. const int token_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_LIST).c_str());
  3605. if (token_idx == -1) {
  3606. throw std::runtime_error("cannot find tokenizer vocab in model file\n");
  3607. }
  3608. const float * scores = nullptr;
  3609. const int score_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_SCORES).c_str());
  3610. if (score_idx != -1) {
  3611. scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
  3612. }
  3613. const int * toktypes = nullptr;
  3614. const int toktype_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE).c_str());
  3615. if (toktype_idx != -1) {
  3616. toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
  3617. }
  3618. const uint32_t n_vocab = gguf_get_arr_n(ctx, token_idx);
  3619. vocab.id_to_token.resize(n_vocab);
  3620. for (uint32_t i = 0; i < n_vocab; i++) {
  3621. std::string word = gguf_get_arr_str(ctx, token_idx, i);
  3622. GGML_ASSERT(unicode_cpts_from_utf8(word).size() > 0);
  3623. vocab.token_to_id[word] = i;
  3624. auto & token_data = vocab.id_to_token[i];
  3625. token_data.text = std::move(word);
  3626. token_data.score = scores ? scores[i] : 0.0f;
  3627. token_data.type = toktypes ? (llama_token_type) toktypes[i] : LLAMA_TOKEN_TYPE_NORMAL;
  3628. }
  3629. GGML_ASSERT(vocab.id_to_token.size() == vocab.token_to_id.size());
  3630. // determine the newline token: LLaMA "<0x0A>" == 10 == '\n', Falcon 193 == '\n'
  3631. if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  3632. try {
  3633. vocab.linefeed_id = llama_byte_to_token(vocab, '\n');
  3634. } catch (const std::exception & e) {
  3635. LLAMA_LOG_WARN("%s: SPM vocabulary, but newline token not found: %s! Using special_pad_id instead.", __func__, e.what());
  3636. vocab.linefeed_id = vocab.special_pad_id;
  3637. }
  3638. } else if (vocab.type == LLAMA_VOCAB_TYPE_WPM) {
  3639. vocab.linefeed_id = vocab.special_pad_id;
  3640. } else {
  3641. const std::vector<int> ids = llama_tokenize_internal(vocab, "\xC4\x8A", false); // U+010A
  3642. GGML_ASSERT(!ids.empty() && "model vocab missing newline token");
  3643. vocab.linefeed_id = ids[0];
  3644. }
  3645. // special tokens
  3646. {
  3647. const std::vector<std::pair<enum llm_kv, int32_t &>> special_token_types = {
  3648. { LLM_KV_TOKENIZER_BOS_ID, vocab.special_bos_id },
  3649. { LLM_KV_TOKENIZER_EOS_ID, vocab.special_eos_id },
  3650. { LLM_KV_TOKENIZER_UNK_ID, vocab.special_unk_id },
  3651. { LLM_KV_TOKENIZER_SEP_ID, vocab.special_sep_id },
  3652. { LLM_KV_TOKENIZER_PAD_ID, vocab.special_pad_id },
  3653. { LLM_KV_TOKENIZER_CLS_ID, vocab.special_cls_id },
  3654. { LLM_KV_TOKENIZER_MASK_ID, vocab.special_mask_id },
  3655. };
  3656. for (const auto & it : special_token_types) {
  3657. const std::string & key = kv(std::get<0>(it));
  3658. int32_t & id = std::get<1>(it);
  3659. uint32_t new_id;
  3660. if (!ml.get_key(std::get<0>(it), new_id, false)) {
  3661. continue;
  3662. }
  3663. if (new_id >= vocab.id_to_token.size()) {
  3664. LLAMA_LOG_WARN("%s: bad special token: '%s' = %ud, using default id %d\n",
  3665. __func__, key.c_str(), new_id, id);
  3666. } else {
  3667. id = new_id;
  3668. }
  3669. }
  3670. // Handle add_bos_token and add_eos_token
  3671. {
  3672. bool temp = true;
  3673. if (ml.get_key(LLM_KV_TOKENIZER_ADD_BOS, temp, false)) {
  3674. vocab.special_add_bos = int(temp);
  3675. }
  3676. if (ml.get_key(LLM_KV_TOKENIZER_ADD_EOS, temp, false)) {
  3677. vocab.special_add_eos = int(temp);
  3678. }
  3679. }
  3680. }
  3681. // build special tokens cache
  3682. {
  3683. // TODO: It is unclear (to me) at this point, whether special tokes are guaranteed to be of a deterministic type,
  3684. // and will always be correctly labeled in 'added_tokens.json' etc.
  3685. // The assumption is, since special tokens aren't meant to be exposed to end user, they are designed
  3686. // to be unmatchable by the tokenizer, therefore tokens from the vocab, which are unmatchable by the tokenizer
  3687. // are special tokens.
  3688. // From testing, this appears to correlate 1:1 with special tokens.
  3689. //
  3690. // Counting special tokens and verifying in only one direction
  3691. // is sufficient to detect difference in those two sets.
  3692. //
  3693. uint32_t special_tokens_count_by_type = 0;
  3694. uint32_t special_tokens_count_from_verification = 0;
  3695. bool special_tokens_definition_mismatch = false;
  3696. for (const auto & t : vocab.token_to_id) {
  3697. const auto & token = t.first;
  3698. const auto & id = t.second;
  3699. // Count all non-normal tokens in the vocab while iterating
  3700. if (vocab.id_to_token[id].type != LLAMA_TOKEN_TYPE_NORMAL) {
  3701. special_tokens_count_by_type++;
  3702. }
  3703. // Skip single character tokens
  3704. if (token.length() > 1) {
  3705. bool is_tokenizable = false;
  3706. // Split token string representation in two, in all possible ways
  3707. // and check if both halves can be matched to a valid token
  3708. for (unsigned i = 1; i < token.length();) {
  3709. const auto left = token.substr(0, i);
  3710. const auto right = token.substr(i);
  3711. // check if we didnt partition in the middle of a utf sequence
  3712. auto utf = utf8_len(left.at(left.length() - 1));
  3713. if (utf == 1) {
  3714. if (vocab.token_to_id.find(left) != vocab.token_to_id.end() &&
  3715. vocab.token_to_id.find(right) != vocab.token_to_id.end() ) {
  3716. is_tokenizable = true;
  3717. break;
  3718. }
  3719. i++;
  3720. } else {
  3721. // skip over the rest of multibyte utf sequence
  3722. i += utf - 1;
  3723. }
  3724. }
  3725. if (!is_tokenizable) {
  3726. // Some tokens are multibyte, but they are utf sequences with equivalent text length of 1
  3727. // it's faster to re-filter them here, since there are way less candidates now
  3728. // Calculate a total "utf" length of a token string representation
  3729. size_t utf8_str_len = 0;
  3730. for (unsigned i = 0; i < token.length();) {
  3731. utf8_str_len++;
  3732. i += utf8_len(token.at(i));
  3733. }
  3734. // And skip the ones which are one character
  3735. if (utf8_str_len > 1) {
  3736. // At this point what we have left are special tokens only
  3737. vocab.special_tokens_cache[token] = id;
  3738. // Count manually found special tokens
  3739. special_tokens_count_from_verification++;
  3740. // If this manually found special token is not marked as such, flag a mismatch
  3741. if (vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL) {
  3742. special_tokens_definition_mismatch = true;
  3743. }
  3744. }
  3745. }
  3746. }
  3747. }
  3748. if (special_tokens_definition_mismatch || special_tokens_count_from_verification != special_tokens_count_by_type) {
  3749. LLAMA_LOG_WARN("%s: mismatch in special tokens definition ( %u/%zu vs %u/%zu ).\n",
  3750. __func__,
  3751. special_tokens_count_from_verification, vocab.id_to_token.size(),
  3752. special_tokens_count_by_type, vocab.id_to_token.size()
  3753. );
  3754. } else {
  3755. LLAMA_LOG_INFO("%s: special tokens definition check successful ( %u/%zu ).\n",
  3756. __func__,
  3757. special_tokens_count_from_verification, vocab.id_to_token.size()
  3758. );
  3759. }
  3760. }
  3761. }
  3762. static void llm_load_print_meta(llama_model_loader & ml, llama_model & model) {
  3763. const auto & hparams = model.hparams;
  3764. const auto & vocab = model.vocab;
  3765. const char * rope_scaling_type = LLAMA_ROPE_SCALING_TYPES.at(hparams.rope_scaling_type_train);
  3766. // hparams
  3767. LLAMA_LOG_INFO("%s: format = %s\n", __func__, llama_file_version_name(ml.fver));
  3768. LLAMA_LOG_INFO("%s: arch = %s\n", __func__, LLM_ARCH_NAMES.at(model.arch));
  3769. LLAMA_LOG_INFO("%s: vocab type = %s\n", __func__, llama_model_vocab_type_name(vocab.type));
  3770. LLAMA_LOG_INFO("%s: n_vocab = %u\n", __func__, hparams.n_vocab);
  3771. LLAMA_LOG_INFO("%s: n_merges = %u\n", __func__, (int) vocab.bpe_ranks.size());
  3772. LLAMA_LOG_INFO("%s: n_ctx_train = %u\n", __func__, hparams.n_ctx_train);
  3773. LLAMA_LOG_INFO("%s: n_embd = %u\n", __func__, hparams.n_embd);
  3774. LLAMA_LOG_INFO("%s: n_head = %u\n", __func__, hparams.n_head);
  3775. LLAMA_LOG_INFO("%s: n_head_kv = %u\n", __func__, hparams.n_head_kv);
  3776. LLAMA_LOG_INFO("%s: n_layer = %u\n", __func__, hparams.n_layer);
  3777. LLAMA_LOG_INFO("%s: n_rot = %u\n", __func__, hparams.n_rot);
  3778. LLAMA_LOG_INFO("%s: n_embd_head_k = %u\n", __func__, hparams.n_embd_head_k);
  3779. LLAMA_LOG_INFO("%s: n_embd_head_v = %u\n", __func__, hparams.n_embd_head_v);
  3780. LLAMA_LOG_INFO("%s: n_gqa = %u\n", __func__, hparams.n_gqa());
  3781. LLAMA_LOG_INFO("%s: n_embd_k_gqa = %u\n", __func__, hparams.n_embd_k_gqa());
  3782. LLAMA_LOG_INFO("%s: n_embd_v_gqa = %u\n", __func__, hparams.n_embd_v_gqa());
  3783. LLAMA_LOG_INFO("%s: f_norm_eps = %.1e\n", __func__, hparams.f_norm_eps);
  3784. LLAMA_LOG_INFO("%s: f_norm_rms_eps = %.1e\n", __func__, hparams.f_norm_rms_eps);
  3785. LLAMA_LOG_INFO("%s: f_clamp_kqv = %.1e\n", __func__, hparams.f_clamp_kqv);
  3786. LLAMA_LOG_INFO("%s: f_max_alibi_bias = %.1e\n", __func__, hparams.f_max_alibi_bias);
  3787. LLAMA_LOG_INFO("%s: f_logit_scale = %.1e\n", __func__, hparams.f_logit_scale);
  3788. LLAMA_LOG_INFO("%s: n_ff = %u\n", __func__, hparams.n_ff);
  3789. LLAMA_LOG_INFO("%s: n_expert = %u\n", __func__, hparams.n_expert);
  3790. LLAMA_LOG_INFO("%s: n_expert_used = %u\n", __func__, hparams.n_expert_used);
  3791. LLAMA_LOG_INFO("%s: causal attn = %d\n", __func__, hparams.causal_attn);
  3792. LLAMA_LOG_INFO("%s: pooling type = %d\n", __func__, hparams.pooling_type);
  3793. LLAMA_LOG_INFO("%s: rope type = %d\n", __func__, hparams.rope_type);
  3794. LLAMA_LOG_INFO("%s: rope scaling = %s\n", __func__, rope_scaling_type);
  3795. LLAMA_LOG_INFO("%s: freq_base_train = %.1f\n", __func__, hparams.rope_freq_base_train);
  3796. LLAMA_LOG_INFO("%s: freq_scale_train = %g\n", __func__, hparams.rope_freq_scale_train);
  3797. LLAMA_LOG_INFO("%s: n_yarn_orig_ctx = %u\n", __func__, hparams.n_yarn_orig_ctx);
  3798. LLAMA_LOG_INFO("%s: rope_finetuned = %s\n", __func__, hparams.rope_finetuned ? "yes" : "unknown");
  3799. LLAMA_LOG_INFO("%s: ssm_d_conv = %u\n", __func__, hparams.ssm_d_conv);
  3800. LLAMA_LOG_INFO("%s: ssm_d_inner = %u\n", __func__, hparams.ssm_d_inner);
  3801. LLAMA_LOG_INFO("%s: ssm_d_state = %u\n", __func__, hparams.ssm_d_state);
  3802. LLAMA_LOG_INFO("%s: ssm_dt_rank = %u\n", __func__, hparams.ssm_dt_rank);
  3803. LLAMA_LOG_INFO("%s: model type = %s\n", __func__, llama_model_type_name(model.type));
  3804. LLAMA_LOG_INFO("%s: model ftype = %s\n", __func__, llama_model_ftype_name(model.ftype).c_str());
  3805. if (ml.n_elements >= 1e12) {
  3806. LLAMA_LOG_INFO("%s: model params = %.2f T\n", __func__, ml.n_elements*1e-12);
  3807. } else if (ml.n_elements >= 1e9) {
  3808. LLAMA_LOG_INFO("%s: model params = %.2f B\n", __func__, ml.n_elements*1e-9);
  3809. } else if (ml.n_elements >= 1e6) {
  3810. LLAMA_LOG_INFO("%s: model params = %.2f M\n", __func__, ml.n_elements*1e-6);
  3811. } else {
  3812. LLAMA_LOG_INFO("%s: model params = %.2f K\n", __func__, ml.n_elements*1e-3);
  3813. }
  3814. if (ml.n_bytes < GiB) {
  3815. 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);
  3816. } else {
  3817. 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);
  3818. }
  3819. // general kv
  3820. LLAMA_LOG_INFO("%s: general.name = %s\n", __func__, model.name.c_str());
  3821. // special tokens
  3822. 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() ); }
  3823. 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() ); }
  3824. 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() ); }
  3825. 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() ); }
  3826. 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() ); }
  3827. if (vocab.special_cls_id != -1) { LLAMA_LOG_INFO( "%s: CLS token = %d '%s'\n", __func__, vocab.special_cls_id, vocab.id_to_token[vocab.special_cls_id].text.c_str() ); }
  3828. if (vocab.special_mask_id != -1) { LLAMA_LOG_INFO( "%s: MASK token = %d '%s'\n", __func__, vocab.special_mask_id, vocab.id_to_token[vocab.special_mask_id].text.c_str() ); }
  3829. 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() ); }
  3830. }
  3831. // Returns false if cancelled by progress_callback
  3832. static bool llm_load_tensors(
  3833. llama_model_loader & ml,
  3834. llama_model & model,
  3835. int n_gpu_layers,
  3836. enum llama_split_mode split_mode,
  3837. int main_gpu,
  3838. const float * tensor_split,
  3839. bool use_mlock,
  3840. llama_progress_callback progress_callback,
  3841. void * progress_callback_user_data) {
  3842. model.t_start_us = ggml_time_us();
  3843. auto & hparams = model.hparams;
  3844. model.split_mode = split_mode;
  3845. model.main_gpu = main_gpu;
  3846. model.n_gpu_layers = n_gpu_layers;
  3847. const int64_t n_layer = hparams.n_layer;
  3848. const int64_t i_gpu_start = std::max((int64_t) hparams.n_layer - n_gpu_layers, (int64_t) 0);
  3849. bool use_mmap_buffer = true;
  3850. // there is very little benefit to offloading the input layer, so always keep it on the CPU
  3851. model.buft_input = llama_default_buffer_type_cpu(true);
  3852. //model.buft_input = llama_default_buffer_type_offload(main_gpu);
  3853. model.buft_layer.resize(n_layer);
  3854. // assign cpu layers
  3855. for (int64_t i = 0; i < i_gpu_start; ++i) {
  3856. model.buft_layer[i] = llama_default_buffer_type_cpu(true);
  3857. }
  3858. if (split_mode == LLAMA_SPLIT_MODE_LAYER) {
  3859. // calculate the split points
  3860. int device_count = llama_get_device_count();
  3861. bool all_zero = tensor_split == nullptr || std::all_of(tensor_split, tensor_split + device_count, [](float x) { return x == 0.0f; });
  3862. std::vector<float> splits(device_count);
  3863. if (all_zero) {
  3864. // default split, by free memory
  3865. for (int i = 0; i < device_count; ++i) {
  3866. splits[i] = llama_get_device_memory(i);
  3867. }
  3868. } else {
  3869. std::copy(tensor_split, tensor_split + device_count, splits.begin());
  3870. }
  3871. // sum and normalize the splits to get the split points
  3872. float split_sum = 0.0f;
  3873. for (int i = 0; i < device_count; ++i) {
  3874. split_sum += splits[i];
  3875. splits[i] = split_sum;
  3876. }
  3877. for (int i = 0; i < device_count; ++i) {
  3878. splits[i] /= split_sum;
  3879. }
  3880. // assign the repeating layers to the devices according to the splits
  3881. int act_gpu_layers = std::min(n_gpu_layers, (int)n_layer + 1);
  3882. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  3883. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(i - i_gpu_start)/act_gpu_layers) - splits.begin();
  3884. model.buft_layer[i] = llama_default_buffer_type_offload(layer_gpu);
  3885. }
  3886. // assign the output layer
  3887. if (n_gpu_layers > n_layer) {
  3888. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(act_gpu_layers - 1)/act_gpu_layers) - splits.begin();
  3889. model.buft_output = llama_default_buffer_type_offload(layer_gpu);
  3890. } else {
  3891. model.buft_output = llama_default_buffer_type_cpu(true);
  3892. }
  3893. } else {
  3894. ggml_backend_buffer_type_t split_buft;
  3895. if (split_mode == LLAMA_SPLIT_MODE_ROW) {
  3896. split_buft = llama_default_buffer_type_split(main_gpu, tensor_split);
  3897. } else {
  3898. // LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_LAYER in backends where it is not supported
  3899. split_buft = llama_default_buffer_type_offload(main_gpu);
  3900. }
  3901. // assign the repeating layers
  3902. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  3903. model.buft_layer[i] = {
  3904. split_buft,
  3905. llama_default_buffer_type_offload(main_gpu)
  3906. };
  3907. }
  3908. // assign the output layer
  3909. if (n_gpu_layers > n_layer) {
  3910. model.buft_output = {
  3911. split_buft,
  3912. llama_default_buffer_type_offload(main_gpu)
  3913. };
  3914. } else {
  3915. model.buft_output = llama_default_buffer_type_cpu(true);
  3916. }
  3917. }
  3918. // count used buffer types
  3919. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  3920. buft_layer_count[model.buft_input.buft]++;
  3921. buft_layer_count[model.buft_input.buft_matrix]++;
  3922. buft_layer_count[model.buft_output.buft]++;
  3923. buft_layer_count[model.buft_output.buft_matrix]++;
  3924. for (int64_t i = 0; i < n_layer; ++i) {
  3925. buft_layer_count[model.buft_layer[i].buft]++;
  3926. buft_layer_count[model.buft_layer[i].buft_matrix]++;
  3927. }
  3928. // create one context per buffer type
  3929. size_t ctx_size = ggml_tensor_overhead()*(ml.n_tensors + 1); // +1 for models where tok_embd is duplicated as output
  3930. // for moe merged tensors
  3931. ctx_size += ggml_tensor_overhead()*hparams.n_expert*n_layer;
  3932. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  3933. for (auto & it : buft_layer_count) {
  3934. struct ggml_init_params params = {
  3935. /*.mem_size =*/ ctx_size,
  3936. /*.mem_buffer =*/ NULL,
  3937. /*.no_alloc =*/ true,
  3938. };
  3939. ggml_context * ctx = ggml_init(params);
  3940. if (!ctx) {
  3941. throw std::runtime_error(format("failed to create context"));
  3942. }
  3943. ctx_map[it.first] = ctx;
  3944. model.ctxs.push_back(ctx);
  3945. }
  3946. LLAMA_LOG_INFO("%s: ggml ctx size = %7.2f MiB\n", __func__, model.ctxs.size()*ctx_size/1024.0/1024.0);
  3947. // create tensors for the weights
  3948. {
  3949. const int64_t n_embd = hparams.n_embd;
  3950. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3951. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  3952. const int64_t n_embd_gqa = n_embd_v_gqa;
  3953. const int64_t n_vocab = hparams.n_vocab;
  3954. const int64_t n_vocab_type = hparams.n_vocab_type;
  3955. const int64_t n_ff = hparams.n_ff;
  3956. const int64_t n_expert = hparams.n_expert;
  3957. if (n_expert > 0 && hparams.n_expert_used == 0) {
  3958. throw std::runtime_error("model has expert layers but no expert layers are used");
  3959. }
  3960. GGML_ASSERT(n_embd_gqa == n_embd_k_gqa);
  3961. ggml_context * ctx_input = ctx_map.at(model.buft_input.buft);
  3962. ggml_context * ctx_output = ctx_map.at(model.buft_output.buft);
  3963. ggml_context * ctx_output_split = ctx_map.at(model.buft_output.buft_matrix);
  3964. auto ctx_for_layer = [&](int i) { return ctx_map.at(model.buft_layer[i].buft); };
  3965. auto ctx_for_layer_split = [&](int i) { return ctx_map.at(model.buft_layer[i].buft_matrix); };
  3966. model.layers.resize(n_layer);
  3967. const auto tn = LLM_TN(model.arch);
  3968. switch (model.arch) {
  3969. case LLM_ARCH_LLAMA:
  3970. case LLM_ARCH_REFACT:
  3971. case LLM_ARCH_MINICPM:
  3972. {
  3973. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3974. // output
  3975. {
  3976. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3977. if (model.arch != LLM_ARCH_MINICPM){
  3978. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  3979. // if output is NULL, init from the input tok embed
  3980. if (model.output == NULL) {
  3981. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3982. ml.n_created--; // artificial tensor
  3983. ml.size_data += ggml_nbytes(model.output);
  3984. }
  3985. }
  3986. }
  3987. for (int i = 0; i < n_layer; ++i) {
  3988. ggml_context * ctx_layer = ctx_for_layer(i);
  3989. ggml_context * ctx_split = ctx_for_layer_split(i);
  3990. auto & layer = model.layers[i];
  3991. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3992. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3993. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3994. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3995. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3996. // optional bias tensors
  3997. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, false);
  3998. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, false);
  3999. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, false);
  4000. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, false);
  4001. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4002. if (n_expert == 0) {
  4003. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4004. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4005. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4006. } else {
  4007. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  4008. layer.ffn_gate_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd, n_ff, n_expert}, false);
  4009. if (layer.ffn_gate_exps) {
  4010. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), { n_ff, n_embd, n_expert});
  4011. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  4012. } else {
  4013. // merge split expert into a single tensor for compatibility with older models
  4014. // requires disabling mmap
  4015. use_mmap_buffer = false;
  4016. ggml_type type_gate = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, 0).c_str())->type;
  4017. ggml_type type_down = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, 0).c_str())->type;
  4018. ggml_type type_up = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, 0).c_str())->type;
  4019. layer.ffn_gate_exps = ggml_new_tensor_3d(ctx_split, type_gate, n_embd, n_ff, n_expert);
  4020. layer.ffn_down_exps = ggml_new_tensor_3d(ctx_split, type_down, n_ff, n_embd, n_expert);
  4021. layer.ffn_up_exps = ggml_new_tensor_3d(ctx_split, type_up, n_embd, n_ff, n_expert);
  4022. ggml_set_name(layer.ffn_gate_exps, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i).c_str());
  4023. ggml_set_name(layer.ffn_down_exps, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i).c_str());
  4024. ggml_set_name(layer.ffn_up_exps, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i).c_str());
  4025. for (uint32_t x = 0; x < n_expert; ++x) {
  4026. // the individual experts are loaded into a view of the merged tensor
  4027. 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);
  4028. 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);
  4029. 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);
  4030. }
  4031. }
  4032. }
  4033. }
  4034. } break;
  4035. case LLM_ARCH_GROK:
  4036. {
  4037. if (n_expert == 0) {
  4038. throw std::runtime_error("Grok model cannot have zero experts");
  4039. }
  4040. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4041. // output
  4042. {
  4043. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4044. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  4045. // if output is NULL, init from the input tok embed
  4046. if (model.output == NULL) {
  4047. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4048. ml.n_created--; // artificial tensor
  4049. ml.size_data += ggml_nbytes(model.output);
  4050. }
  4051. }
  4052. for (int i = 0; i < n_layer; ++i) {
  4053. ggml_context * ctx_layer = ctx_for_layer(i);
  4054. ggml_context * ctx_split = ctx_for_layer_split(i);
  4055. auto & layer = model.layers[i];
  4056. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4057. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4058. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4059. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4060. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4061. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  4062. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4063. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  4064. layer.ffn_gate_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd, n_ff, n_expert}, false);
  4065. if (layer.ffn_gate_exps) {
  4066. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), { n_ff, n_embd, n_expert});
  4067. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  4068. } else {
  4069. // merge split expert into a single tensor for compatibility with older models
  4070. // requires disabling mmap
  4071. use_mmap_buffer = false;
  4072. ggml_type type_gate = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, 0).c_str())->type;
  4073. ggml_type type_down = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, 0).c_str())->type;
  4074. ggml_type type_up = ml.require_tensor_meta(tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, 0).c_str())->type;
  4075. layer.ffn_gate_exps = ggml_new_tensor_3d(ctx_split, type_gate, n_embd, n_ff, n_expert);
  4076. layer.ffn_down_exps = ggml_new_tensor_3d(ctx_split, type_down, n_ff, n_embd, n_expert);
  4077. layer.ffn_up_exps = ggml_new_tensor_3d(ctx_split, type_up, n_embd, n_ff, n_expert);
  4078. ggml_set_name(layer.ffn_gate_exps, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i).c_str());
  4079. ggml_set_name(layer.ffn_down_exps, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i).c_str());
  4080. ggml_set_name(layer.ffn_up_exps, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i).c_str());
  4081. for (uint32_t x = 0; x < n_expert; ++x) {
  4082. // the individual experts are loaded into a view of the merged tensor
  4083. 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);
  4084. 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);
  4085. 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);
  4086. }
  4087. }
  4088. layer.layer_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd});
  4089. }
  4090. } break;
  4091. case LLM_ARCH_DBRX:
  4092. {
  4093. if (n_expert == 0) {
  4094. throw std::runtime_error("DBRX model cannot have zero experts");
  4095. }
  4096. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4097. // output
  4098. {
  4099. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4100. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4101. }
  4102. for (int i = 0; i < n_layer; ++i) {
  4103. ggml_context * ctx_layer = ctx_for_layer(i);
  4104. ggml_context * ctx_split = ctx_for_layer_split(i);
  4105. auto & layer = model.layers[i];
  4106. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4107. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4108. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4109. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  4110. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert});
  4111. layer.ffn_gate_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  4112. layer.ffn_down_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff, n_embd, n_expert});
  4113. layer.ffn_up_exps = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff, n_expert});
  4114. }
  4115. } break;
  4116. case LLM_ARCH_BAICHUAN:
  4117. {
  4118. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4119. {
  4120. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4121. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4122. }
  4123. for (int i = 0; i < n_layer; ++i) {
  4124. ggml_context * ctx_layer = ctx_for_layer(i);
  4125. ggml_context * ctx_split = ctx_for_layer_split(i);
  4126. auto & layer = model.layers[i];
  4127. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4128. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4129. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4130. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4131. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4132. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4133. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4134. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4135. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4136. }
  4137. } break;
  4138. case LLM_ARCH_FALCON:
  4139. {
  4140. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4141. // output
  4142. {
  4143. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4144. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4145. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  4146. if (!model.output) {
  4147. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}); // needs to be on GPU
  4148. ml.n_created--; // artificial tensor
  4149. ml.size_data += ggml_nbytes(model.output);
  4150. }
  4151. }
  4152. for (int i = 0; i < n_layer; ++i) {
  4153. ggml_context * ctx_layer = ctx_for_layer(i);
  4154. ggml_context * ctx_split = ctx_for_layer_split(i);
  4155. auto & layer = model.layers[i];
  4156. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4157. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4158. layer.attn_norm_2 = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i), {n_embd}, false);
  4159. layer.attn_norm_2_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "bias", i), {n_embd}, false);
  4160. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4161. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4162. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4163. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4164. }
  4165. } break;
  4166. case LLM_ARCH_STARCODER:
  4167. {
  4168. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4169. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  4170. // output
  4171. {
  4172. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4173. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4174. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4175. }
  4176. for (int i = 0; i < n_layer; ++i) {
  4177. ggml_context * ctx_layer = ctx_for_layer(i);
  4178. ggml_context * ctx_split = ctx_for_layer_split(i);
  4179. auto & layer = model.layers[i];
  4180. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4181. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4182. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4183. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  4184. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4185. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4186. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4187. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4188. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4189. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4190. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4191. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4192. }
  4193. } break;
  4194. case LLM_ARCH_PERSIMMON:
  4195. {
  4196. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4197. {
  4198. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4199. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4200. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4201. }
  4202. for (int i = 0; i < n_layer; ++i) {
  4203. ggml_context * ctx_layer = ctx_for_layer(i);
  4204. ggml_context * ctx_split = ctx_for_layer_split(i);
  4205. auto & layer = model.layers[i];
  4206. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4207. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4208. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4209. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  4210. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4211. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4212. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4213. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4214. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4215. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4216. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4217. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4218. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {64});
  4219. layer.attn_q_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "bias", i), {64});
  4220. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {64});
  4221. layer.attn_k_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "bias", i), {64});
  4222. }
  4223. } break;
  4224. case LLM_ARCH_BERT:
  4225. case LLM_ARCH_NOMIC_BERT:
  4226. {
  4227. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4228. model.type_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_TYPES, "weight"), {n_embd, n_vocab_type});
  4229. if (model.arch == LLM_ARCH_BERT) {
  4230. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  4231. }
  4232. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  4233. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  4234. for (int i = 0; i < n_layer; ++i) {
  4235. ggml_context * ctx_layer = ctx_for_layer(i);
  4236. ggml_context * ctx_split = ctx_for_layer_split(i);
  4237. auto & layer = model.layers[i];
  4238. if (model.arch == LLM_ARCH_BERT) {
  4239. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4240. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  4241. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4242. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  4243. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4244. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  4245. } else {
  4246. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4247. }
  4248. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4249. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  4250. layer.attn_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "bias", i), {n_embd});
  4251. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4252. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4253. if (model.arch == LLM_ARCH_BERT) {
  4254. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4255. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4256. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4257. } else {
  4258. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4259. }
  4260. layer.layer_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd});
  4261. layer.layer_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "bias", i), {n_embd});
  4262. }
  4263. } break;
  4264. case LLM_ARCH_BLOOM:
  4265. {
  4266. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4267. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  4268. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  4269. // output
  4270. {
  4271. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4272. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4273. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4274. }
  4275. for (int i = 0; i < n_layer; ++i) {
  4276. ggml_context * ctx_layer = ctx_for_layer(i);
  4277. ggml_context * ctx_split = ctx_for_layer_split(i);
  4278. auto & layer = model.layers[i];
  4279. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4280. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4281. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4282. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  4283. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4284. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4285. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4286. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4287. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4288. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4289. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4290. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4291. }
  4292. } break;
  4293. case LLM_ARCH_MPT:
  4294. {
  4295. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4296. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train}, false);
  4297. // output
  4298. {
  4299. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4300. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, false);
  4301. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  4302. if (!model.output) {
  4303. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}); // needs to be on GPU
  4304. ml.n_created--; // artificial tensor
  4305. ml.size_data += ggml_nbytes(model.output);
  4306. }
  4307. }
  4308. for (int i = 0; i < n_layer; ++i) {
  4309. ggml_context * ctx_layer = ctx_for_layer(i);
  4310. ggml_context * ctx_split = ctx_for_layer_split(i);
  4311. auto & layer = model.layers[i];
  4312. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4313. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, false);
  4314. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4315. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, false);
  4316. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4317. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, false);
  4318. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4319. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, false);
  4320. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4321. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, false);
  4322. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4323. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, false);
  4324. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd}, false);
  4325. layer.attn_q_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "bias", i), {n_embd}, false);
  4326. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd}, false);
  4327. layer.attn_k_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "bias", i), {n_embd}, false);
  4328. // AWQ ScaleActivation layer
  4329. layer.ffn_act = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_ACT, "scales", i), {n_ff}, false);
  4330. }
  4331. } break;
  4332. case LLM_ARCH_STABLELM:
  4333. {
  4334. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4335. // output
  4336. {
  4337. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4338. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4339. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4340. }
  4341. for (int i = 0; i < n_layer; ++i) {
  4342. ggml_context * ctx_layer = ctx_for_layer(i);
  4343. ggml_context * ctx_split = ctx_for_layer_split(i);
  4344. auto & layer = model.layers[i];
  4345. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4346. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4347. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4348. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4349. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4350. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4351. // optional bias tensors, present in Stable LM 2 1.6B
  4352. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, false);
  4353. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, false);
  4354. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, false);
  4355. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4356. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4357. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4358. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4359. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4360. }
  4361. } break;
  4362. case LLM_ARCH_QWEN:
  4363. {
  4364. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4365. // output
  4366. {
  4367. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4368. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4369. }
  4370. for (int i = 0; i < n_layer; ++i) {
  4371. ggml_context * ctx_layer = ctx_for_layer(i);
  4372. ggml_context * ctx_split = ctx_for_layer_split(i);
  4373. auto & layer = model.layers[i];
  4374. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4375. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd*3});
  4376. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd*3});
  4377. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4378. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4379. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff/2});
  4380. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff/2, n_embd});
  4381. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff/2});
  4382. }
  4383. } break;
  4384. case LLM_ARCH_QWEN2:
  4385. {
  4386. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4387. // output
  4388. {
  4389. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4390. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4391. }
  4392. for (int i = 0; i < n_layer; ++i) {
  4393. ggml_context * ctx_layer = ctx_for_layer(i);
  4394. ggml_context * ctx_split = ctx_for_layer_split(i);
  4395. auto & layer = model.layers[i];
  4396. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4397. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4398. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4399. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4400. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4401. // optional bias tensors
  4402. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  4403. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  4404. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  4405. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4406. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4407. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4408. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4409. }
  4410. } break;
  4411. case LLM_ARCH_PHI2:
  4412. {
  4413. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4414. // output
  4415. {
  4416. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4417. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4418. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4419. model.output_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT, "bias"), {n_vocab});
  4420. }
  4421. for (int i = 0; i < n_layer; ++i) {
  4422. ggml_context * ctx_layer = ctx_for_layer(i);
  4423. ggml_context * ctx_split = ctx_for_layer_split(i);
  4424. auto & layer = model.layers[i];
  4425. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4426. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4427. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, false);
  4428. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, false);
  4429. if (layer.wqkv == nullptr) {
  4430. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4431. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  4432. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4433. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  4434. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4435. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  4436. }
  4437. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4438. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4439. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4440. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4441. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4442. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4443. }
  4444. } break;
  4445. case LLM_ARCH_PLAMO:
  4446. {
  4447. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4448. // output
  4449. {
  4450. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4451. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4452. }
  4453. for (int i = 0; i < n_layer; ++i) {
  4454. ggml_context * ctx_layer = ctx_for_layer(i);
  4455. ggml_context * ctx_split = ctx_for_layer_split(i);
  4456. auto & layer = model.layers[i];
  4457. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4458. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4459. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4460. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4461. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4462. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4463. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4464. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4465. }
  4466. } break;
  4467. case LLM_ARCH_GPT2:
  4468. {
  4469. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4470. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  4471. // output
  4472. {
  4473. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4474. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4475. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4476. }
  4477. for (int i = 0; i < n_layer; ++i) {
  4478. ggml_context * ctx_layer = ctx_for_layer(i);
  4479. ggml_context * ctx_split = ctx_for_layer_split(i);
  4480. auto & layer = model.layers[i];
  4481. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4482. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4483. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4484. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  4485. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4486. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4487. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4488. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4489. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4490. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4491. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4492. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4493. }
  4494. } break;
  4495. case LLM_ARCH_CODESHELL:
  4496. {
  4497. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4498. // output
  4499. {
  4500. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4501. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4502. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4503. }
  4504. for (int i = 0; i < n_layer; ++i) {
  4505. ggml_context * ctx_layer = ctx_for_layer(i);
  4506. ggml_context * ctx_split = ctx_for_layer_split(i);
  4507. auto & layer = model.layers[i];
  4508. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4509. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4510. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4511. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  4512. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4513. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4514. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4515. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4516. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4517. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4518. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4519. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4520. }
  4521. } break;
  4522. case LLM_ARCH_ORION:
  4523. {
  4524. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4525. {
  4526. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4527. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4528. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4529. }
  4530. for (int i = 0; i < n_layer; ++i) {
  4531. ggml_context * ctx_layer = ctx_for_layer(i);
  4532. ggml_context * ctx_split = ctx_for_layer_split(i);
  4533. auto & layer = model.layers[i];
  4534. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4535. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4536. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4537. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4538. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4539. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4540. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4541. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4542. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4543. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4544. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4545. }
  4546. } break;
  4547. case LLM_ARCH_INTERNLM2:
  4548. {
  4549. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4550. // output
  4551. {
  4552. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4553. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4554. }
  4555. for (int i = 0; i < n_layer; ++i) {
  4556. ggml_context * ctx_layer = ctx_for_layer(i);
  4557. ggml_context * ctx_split = ctx_for_layer_split(i);
  4558. auto & layer = model.layers[i];
  4559. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4560. // layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4561. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4562. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4563. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4564. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4565. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4566. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4567. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4568. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4569. }
  4570. } break;
  4571. case LLM_ARCH_GEMMA:
  4572. {
  4573. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4574. // output
  4575. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4576. 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
  4577. ml.n_created--; // artificial tensor
  4578. ml.size_data += ggml_nbytes(model.output);
  4579. const int64_t n_ff = hparams.n_ff;
  4580. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  4581. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  4582. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  4583. for (uint32_t i = 0; i < n_layer; ++i) {
  4584. ggml_context * ctx_layer = ctx_for_layer(i);
  4585. ggml_context * ctx_split = ctx_for_layer_split(i);
  4586. auto & layer = model.layers[i];
  4587. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4588. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * hparams.n_head});
  4589. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  4590. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  4591. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * hparams.n_head, n_embd});
  4592. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4593. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4594. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4595. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4596. }
  4597. } break;
  4598. case LLM_ARCH_STARCODER2:
  4599. {
  4600. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4601. // output
  4602. {
  4603. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4604. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4605. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  4606. // if output is NULL, init from the input tok embed
  4607. if (model.output == NULL) {
  4608. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4609. ml.n_created--; // artificial tensor
  4610. ml.size_data += ggml_nbytes(model.output);
  4611. }
  4612. }
  4613. for (int i = 0; i < n_layer; ++i) {
  4614. ggml_context * ctx_layer = ctx_for_layer(i);
  4615. ggml_context * ctx_split = ctx_for_layer_split(i);
  4616. auto & layer = model.layers[i];
  4617. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4618. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4619. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4620. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4621. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4622. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4623. // optional bias tensors
  4624. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  4625. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  4626. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  4627. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4628. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4629. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4630. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4631. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4632. // optional bias tensors
  4633. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4634. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP , "bias", i), { n_ff});
  4635. }
  4636. } break;
  4637. case LLM_ARCH_MAMBA:
  4638. {
  4639. const int64_t d_conv = hparams.ssm_d_conv;
  4640. const int64_t d_inner = hparams.ssm_d_inner;
  4641. const int64_t d_state = hparams.ssm_d_state;
  4642. const int64_t dt_rank = hparams.ssm_dt_rank;
  4643. // only an expansion factor of 2 is supported for now
  4644. GGML_ASSERT(2 * n_embd == d_inner);
  4645. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4646. // output
  4647. {
  4648. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4649. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  4650. // if output is NULL, init from the input tok embed, duplicated to allow offloading
  4651. if (model.output == NULL) {
  4652. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4653. ml.n_created--; // artificial tensor
  4654. ml.size_data += ggml_nbytes(model.output);
  4655. }
  4656. }
  4657. for (int i = 0; i < n_layer; ++i) {
  4658. ggml_context * ctx_layer = ctx_for_layer(i);
  4659. ggml_context * ctx_split = ctx_for_layer_split(i);
  4660. auto & layer = model.layers[i];
  4661. // norm
  4662. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4663. layer.ssm_in = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_IN, "weight", i), {n_embd, 2*d_inner});
  4664. layer.ssm_conv1d = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_CONV1D, "weight", i), {d_conv, d_inner});
  4665. layer.ssm_conv1d_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_CONV1D, "bias", i), {d_inner});
  4666. layer.ssm_x = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_X, "weight", i), {d_inner, dt_rank + 2*d_state});
  4667. layer.ssm_dt = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_DT, "weight", i), {dt_rank, d_inner});
  4668. layer.ssm_dt_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_DT, "bias", i), {d_inner});
  4669. // no "weight" suffix for these
  4670. layer.ssm_a = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_A, i), {d_state, d_inner});
  4671. layer.ssm_d = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_D, i), {d_inner});
  4672. // out_proj
  4673. layer.ssm_out = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_OUT, "weight", i), {d_inner, n_embd});
  4674. }
  4675. } break;
  4676. case LLM_ARCH_XVERSE:
  4677. {
  4678. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4679. {
  4680. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4681. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4682. }
  4683. for (int i = 0; i < n_layer; ++i) {
  4684. ggml_context * ctx_layer = ctx_for_layer(i);
  4685. ggml_context * ctx_split = ctx_for_layer_split(i);
  4686. auto & layer = model.layers[i];
  4687. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4688. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4689. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4690. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4691. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4692. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4693. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4694. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4695. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4696. }
  4697. } break;
  4698. case LLM_ARCH_COMMAND_R:
  4699. {
  4700. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4701. // output
  4702. {
  4703. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4704. // init output from the input tok embed
  4705. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4706. ml.n_created--; // artificial tensor
  4707. ml.size_data += ggml_nbytes(model.output);
  4708. }
  4709. for (int i = 0; i < n_layer; ++i) {
  4710. ggml_context * ctx_layer = ctx_for_layer(i);
  4711. ggml_context * ctx_split = ctx_for_layer_split(i);
  4712. auto & layer = model.layers[i];
  4713. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4714. if (n_layer >= 64){
  4715. 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});
  4716. 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});
  4717. }
  4718. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4719. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4720. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4721. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4722. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4723. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4724. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4725. }
  4726. } break;
  4727. default:
  4728. throw std::runtime_error("unknown architecture");
  4729. }
  4730. }
  4731. ml.done_getting_tensors();
  4732. ml.init_mappings(true, use_mlock ? &model.mlock_mmaps : nullptr);
  4733. model.mappings.reserve(ml.mappings.size());
  4734. // create the backend buffers
  4735. std::vector<std::pair<ggml_context *, llama_buf_map>> ctx_bufs;
  4736. ctx_bufs.reserve(ctx_map.size());
  4737. // Ensure we have enough capacity for the maximum backend buffer we will potentially create
  4738. size_t n_max_backend_buffer = ctx_map.size() * ml.files.size();
  4739. model.bufs.reserve(n_max_backend_buffer);
  4740. for (auto & it : ctx_map) {
  4741. ggml_backend_buffer_type_t buft = it.first;
  4742. ggml_context * ctx = it.second;
  4743. llama_buf_map bufs;
  4744. bufs.reserve(n_max_backend_buffer);
  4745. // only the mmap region containing the tensors in the model is mapped to the backend buffer
  4746. // 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
  4747. // this allows using partial offloading when the model size exceeds the metal buffer size, but not the RAM size
  4748. if (ml.use_mmap && use_mmap_buffer && buft == llama_default_buffer_type_cpu(true)) {
  4749. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  4750. void * addr = nullptr;
  4751. size_t first, last;
  4752. ml.get_mapping_range(&first, &last, &addr, idx, ctx);
  4753. if (first >= last) {
  4754. continue;
  4755. }
  4756. ggml_backend_buffer_t buf = ggml_backend_cpu_buffer_from_ptr((char *) addr + first, last - first);
  4757. if (buf == nullptr) {
  4758. throw std::runtime_error("unable to allocate backend CPU buffer");
  4759. }
  4760. model.bufs.push_back(buf);
  4761. bufs.emplace(idx, buf);
  4762. #ifdef GGML_USE_CUDA
  4763. if (n_layer >= n_gpu_layers) {
  4764. ggml_backend_cuda_register_host_buffer(
  4765. ggml_backend_buffer_get_base(buf),
  4766. ggml_backend_buffer_get_size(buf));
  4767. }
  4768. #endif
  4769. }
  4770. }
  4771. #ifdef GGML_USE_METAL
  4772. else if (ml.use_mmap && use_mmap_buffer && buft == ggml_backend_metal_buffer_type()) {
  4773. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  4774. const size_t max_size = ggml_get_max_tensor_size(ctx);
  4775. void * addr = nullptr;
  4776. size_t first, last;
  4777. ml.get_mapping_range(&first, &last, &addr, idx, ctx);
  4778. if (first >= last) {
  4779. continue;
  4780. }
  4781. ggml_backend_buffer_t buf = ggml_backend_metal_buffer_from_ptr((char *) addr + first, last - first, max_size);
  4782. if (buf == nullptr) {
  4783. throw std::runtime_error("unable to allocate backend metal buffer");
  4784. }
  4785. model.bufs.push_back(buf);
  4786. bufs.emplace(idx, buf);
  4787. }
  4788. }
  4789. #endif
  4790. else {
  4791. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  4792. if (buf == nullptr) {
  4793. throw std::runtime_error("unable to allocate backend buffer");
  4794. }
  4795. model.bufs.push_back(buf);
  4796. if (use_mlock && ggml_backend_buffer_is_host(buf)) {
  4797. model.mlock_bufs.emplace_back(new llama_mlock);
  4798. auto & mlock_buf = model.mlock_bufs.back();
  4799. mlock_buf->init (ggml_backend_buffer_get_base(buf));
  4800. mlock_buf->grow_to(ggml_backend_buffer_get_size(buf));
  4801. }
  4802. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  4803. bufs.emplace(idx, buf);
  4804. }
  4805. }
  4806. if (bufs.empty()) {
  4807. throw std::runtime_error("failed to allocate buffer");
  4808. }
  4809. for (auto & buf : bufs) {
  4810. // indicate that this buffer contains weights
  4811. // 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
  4812. ggml_backend_buffer_set_usage(buf.second, GGML_BACKEND_BUFFER_USAGE_WEIGHTS);
  4813. }
  4814. ctx_bufs.emplace_back(ctx, bufs);
  4815. }
  4816. if (llama_supports_gpu_offload()) {
  4817. const int n_gpu = std::min(n_gpu_layers, int(hparams.n_layer));
  4818. LLAMA_LOG_INFO("%s: offloading %d repeating layers to GPU\n", __func__, n_gpu);
  4819. if (n_gpu_layers > (int) hparams.n_layer) {
  4820. LLAMA_LOG_INFO("%s: offloading non-repeating layers to GPU\n", __func__);
  4821. }
  4822. const int max_backend_supported_layers = hparams.n_layer + 1;
  4823. const int max_offloadable_layers = hparams.n_layer + 1;
  4824. LLAMA_LOG_INFO("%s: offloaded %d/%d layers to GPU\n", __func__, std::min(n_gpu_layers, max_offloadable_layers), max_backend_supported_layers);
  4825. }
  4826. // print memory requirements
  4827. for (ggml_backend_buffer_t buf : model.bufs) {
  4828. 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);
  4829. }
  4830. // populate tensors_by_name
  4831. for (ggml_context * ctx : model.ctxs) {
  4832. for (auto * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  4833. model.tensors_by_name.emplace_back(ggml_get_name(cur), cur);
  4834. }
  4835. }
  4836. // load tensor data
  4837. for (auto & it : ctx_bufs) {
  4838. ggml_context * ctx = it.first;
  4839. auto & bufs = it.second;
  4840. if (!ml.load_all_data(ctx, bufs, use_mlock ? &model.mlock_mmaps : NULL, progress_callback, progress_callback_user_data)) {
  4841. return false;
  4842. }
  4843. }
  4844. if (use_mmap_buffer) {
  4845. for (auto & mapping : ml.mappings) {
  4846. model.mappings.emplace_back(std::move(mapping));
  4847. }
  4848. }
  4849. // loading time will be recalculate after the first eval, so
  4850. // we take page faults deferred by mmap() into consideration
  4851. model.t_load_us = ggml_time_us() - model.t_start_us;
  4852. return true;
  4853. }
  4854. // Returns 0 on success, -1 on error, and -2 on cancellation via llama_progress_callback
  4855. static int llama_model_load(const std::string & fname, llama_model & model, llama_model_params & params) {
  4856. try {
  4857. llama_model_loader ml(fname, params.use_mmap, params.kv_overrides);
  4858. model.hparams.vocab_only = params.vocab_only;
  4859. try {
  4860. llm_load_arch(ml, model);
  4861. } catch(const std::exception & e) {
  4862. throw std::runtime_error("error loading model architecture: " + std::string(e.what()));
  4863. }
  4864. try {
  4865. llm_load_hparams(ml, model);
  4866. } catch(const std::exception & e) {
  4867. throw std::runtime_error("error loading model hyperparameters: " + std::string(e.what()));
  4868. }
  4869. try {
  4870. llm_load_vocab(ml, model);
  4871. } catch(const std::exception & e) {
  4872. throw std::runtime_error("error loading model vocabulary: " + std::string(e.what()));
  4873. }
  4874. llm_load_print_meta(ml, model);
  4875. if (model.vocab.type != LLAMA_VOCAB_TYPE_NONE &&
  4876. model.hparams.n_vocab != model.vocab.id_to_token.size()) {
  4877. throw std::runtime_error("vocab size mismatch");
  4878. }
  4879. if (params.vocab_only) {
  4880. LLAMA_LOG_INFO("%s: vocab only - skipping tensors\n", __func__);
  4881. return 0;
  4882. }
  4883. #ifdef GGML_USE_KOMPUTE
  4884. if (params.n_gpu_layers > 0 && (
  4885. !(model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON)
  4886. || !(
  4887. model.ftype == LLAMA_FTYPE_ALL_F32 ||
  4888. model.ftype == LLAMA_FTYPE_MOSTLY_F16 ||
  4889. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ||
  4890. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_1
  4891. )
  4892. )) {
  4893. // TODO(cebtenzzre): propagate this error outside of llama_load_model_from_file
  4894. LLAMA_LOG_WARN("%s: disabling Kompute due to unsupported model arch or quantization\n", __func__);
  4895. params.n_gpu_layers = 0;
  4896. }
  4897. #endif
  4898. #ifdef GGML_USE_SYCL
  4899. if (params.split_mode == LLAMA_SPLIT_MODE_NONE) {
  4900. ggml_backend_sycl_set_single_device_mode(params.main_gpu);
  4901. //SYCL use device index (0, 1, 2) directly, uer input device id, then convert to device index.
  4902. params.main_gpu = ggml_backend_sycl_get_device_index(params.main_gpu);
  4903. } else {
  4904. ggml_backend_sycl_set_mul_device_mode();
  4905. }
  4906. #endif
  4907. if (!llm_load_tensors(
  4908. ml, model, params.n_gpu_layers, params.split_mode, params.main_gpu, params.tensor_split, params.use_mlock,
  4909. params.progress_callback, params.progress_callback_user_data
  4910. )) {
  4911. return -2;
  4912. }
  4913. } catch (const std::exception & err) {
  4914. LLAMA_LOG_ERROR("%s: error loading model: %s\n", __func__, err.what());
  4915. return -1;
  4916. }
  4917. return 0;
  4918. }
  4919. //
  4920. // llm_build
  4921. //
  4922. using llm_build_cb = std::function<void(struct ggml_tensor * cur, const char * name, int nl)>;
  4923. enum llm_ffn_op_type {
  4924. LLM_FFN_SILU,
  4925. LLM_FFN_GELU,
  4926. LLM_FFN_RELU,
  4927. LLM_FFN_RELU_SQR,
  4928. };
  4929. enum llm_ffn_gate_type {
  4930. LLM_FFN_SEQ,
  4931. LLM_FFN_PAR, // ffn_gate is parallel to ffn_up
  4932. };
  4933. enum llm_norm_type {
  4934. LLM_NORM,
  4935. LLM_NORM_RMS,
  4936. };
  4937. static struct ggml_tensor * llm_build_inp_embd(
  4938. struct ggml_context * ctx,
  4939. struct llama_context & lctx,
  4940. const llama_hparams & hparams,
  4941. const llama_batch & batch,
  4942. struct ggml_tensor * tok_embd,
  4943. const llm_build_cb & cb) {
  4944. const int64_t n_embd = hparams.n_embd;
  4945. struct ggml_tensor * inpL;
  4946. if (batch.token) {
  4947. lctx.inp_tokens = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, batch.n_tokens);
  4948. cb(lctx.inp_tokens, "inp_tokens", -1);
  4949. ggml_set_input(lctx.inp_tokens);
  4950. inpL = ggml_get_rows(ctx, tok_embd, lctx.inp_tokens);
  4951. } else {
  4952. #ifdef GGML_USE_MPI
  4953. GGML_ASSERT(false && "not implemented");
  4954. #endif
  4955. lctx.inp_embd = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, batch.n_tokens);
  4956. inpL = lctx.inp_embd;
  4957. ggml_set_input(lctx.inp_embd);
  4958. }
  4959. cb(inpL, "inp_embd", -1);
  4960. return inpL;
  4961. }
  4962. static void llm_build_kv_store(
  4963. struct ggml_context * ctx,
  4964. const llama_hparams & hparams,
  4965. const llama_kv_cache & kv,
  4966. struct ggml_cgraph * graph,
  4967. struct ggml_tensor * k_cur,
  4968. struct ggml_tensor * v_cur,
  4969. int64_t n_ctx,
  4970. int32_t n_tokens,
  4971. int32_t kv_head,
  4972. const llm_build_cb & cb,
  4973. int64_t il) {
  4974. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  4975. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  4976. GGML_ASSERT(kv.size == n_ctx);
  4977. // compute the transposed [n_tokens, n_embd] V matrix
  4978. assert(v_cur->ne[0] == n_embd_v_gqa && v_cur->ne[1] == n_tokens);
  4979. struct ggml_tensor * v_cur_t = ggml_transpose(ctx, v_cur);
  4980. cb(v_cur_t, "v_cur_t", il);
  4981. struct ggml_tensor * k_cache_view = ggml_view_1d(ctx, kv.k_l[il], n_tokens*n_embd_k_gqa,
  4982. (ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa))*kv_head);
  4983. cb(k_cache_view, "k_cache_view", il);
  4984. struct ggml_tensor * v_cache_view = ggml_view_2d(ctx, kv.v_l[il], n_tokens, n_embd_v_gqa,
  4985. ( n_ctx)*ggml_element_size(kv.v_l[il]),
  4986. (kv_head)*ggml_element_size(kv.v_l[il]));
  4987. cb(v_cache_view, "v_cache_view", il);
  4988. // important: storing RoPE-ed version of K in the KV cache!
  4989. ggml_build_forward_expand(graph, ggml_cpy(ctx, k_cur, k_cache_view));
  4990. ggml_build_forward_expand(graph, ggml_cpy(ctx, v_cur_t, v_cache_view));
  4991. }
  4992. static struct ggml_tensor * llm_build_norm(
  4993. struct ggml_context * ctx,
  4994. struct ggml_tensor * cur,
  4995. const llama_hparams & hparams,
  4996. struct ggml_tensor * mw,
  4997. struct ggml_tensor * mb,
  4998. llm_norm_type type,
  4999. const llm_build_cb & cb,
  5000. int il) {
  5001. switch (type) {
  5002. case LLM_NORM: cur = ggml_norm (ctx, cur, hparams.f_norm_eps); break;
  5003. case LLM_NORM_RMS: cur = ggml_rms_norm(ctx, cur, hparams.f_norm_rms_eps); break;
  5004. }
  5005. if (mw || mb) {
  5006. cb(cur, "norm", il);
  5007. }
  5008. if (mw) {
  5009. cur = ggml_mul(ctx, cur, mw);
  5010. if (mb) {
  5011. cb(cur, "norm_w", il);
  5012. }
  5013. }
  5014. if (mb) {
  5015. cur = ggml_add(ctx, cur, mb);
  5016. }
  5017. return cur;
  5018. }
  5019. static struct ggml_tensor * llm_build_ffn(
  5020. struct ggml_context * ctx,
  5021. struct ggml_tensor * cur,
  5022. struct ggml_tensor * up,
  5023. struct ggml_tensor * up_b,
  5024. struct ggml_tensor * gate,
  5025. struct ggml_tensor * gate_b,
  5026. struct ggml_tensor * down,
  5027. struct ggml_tensor * down_b,
  5028. struct ggml_tensor * act_scales,
  5029. llm_ffn_op_type type_op,
  5030. llm_ffn_gate_type type_gate,
  5031. const llm_build_cb & cb,
  5032. int il) {
  5033. struct ggml_tensor * tmp = ggml_mul_mat(ctx, up, cur);
  5034. cb(tmp, "ffn_up", il);
  5035. if (up_b) {
  5036. tmp = ggml_add(ctx, tmp, up_b);
  5037. cb(tmp, "ffn_up_b", il);
  5038. }
  5039. if (gate) {
  5040. switch (type_gate) {
  5041. case LLM_FFN_SEQ:
  5042. {
  5043. cur = ggml_mul_mat(ctx, gate, tmp);
  5044. cb(cur, "ffn_gate", il);
  5045. } break;
  5046. case LLM_FFN_PAR:
  5047. {
  5048. cur = ggml_mul_mat(ctx, gate, cur);
  5049. cb(cur, "ffn_gate", il);
  5050. } break;
  5051. }
  5052. if (gate_b) {
  5053. cur = ggml_add(ctx, cur, gate_b);
  5054. cb(cur, "ffn_gate_b", il);
  5055. }
  5056. } else {
  5057. cur = tmp;
  5058. }
  5059. switch (type_op) {
  5060. case LLM_FFN_SILU:
  5061. {
  5062. cur = ggml_silu(ctx, cur);
  5063. cb(cur, "ffn_silu", il);
  5064. } break;
  5065. case LLM_FFN_GELU:
  5066. {
  5067. cur = ggml_gelu(ctx, cur);
  5068. cb(cur, "ffn_gelu", il);
  5069. if (act_scales != NULL) {
  5070. cur = ggml_div(ctx, cur, act_scales);
  5071. cb(cur, "ffn_act", il);
  5072. }
  5073. } break;
  5074. case LLM_FFN_RELU:
  5075. {
  5076. cur = ggml_relu(ctx, cur);
  5077. cb(cur, "ffn_relu", il);
  5078. } break;
  5079. case LLM_FFN_RELU_SQR:
  5080. {
  5081. cur = ggml_relu(ctx, cur);
  5082. cb(cur, "ffn_relu", il);
  5083. cur = ggml_sqr(ctx, cur);
  5084. cb(cur, "ffn_sqr(relu)", il);
  5085. } break;
  5086. }
  5087. if (type_gate == LLM_FFN_PAR) {
  5088. cur = ggml_mul(ctx, cur, tmp);
  5089. cb(cur, "ffn_gate_par", il);
  5090. }
  5091. cur = ggml_mul_mat(ctx, down, cur);
  5092. if (down_b) {
  5093. cb(cur, "ffn_down", il);
  5094. }
  5095. if (down_b) {
  5096. cur = ggml_add(ctx, cur, down_b);
  5097. }
  5098. return cur;
  5099. }
  5100. // if max_alibi_bias > 0 then apply ALiBi
  5101. static struct ggml_tensor * llm_build_kqv(
  5102. struct ggml_context * ctx,
  5103. const llama_model & model,
  5104. const llama_hparams & hparams,
  5105. const llama_kv_cache & kv,
  5106. struct ggml_cgraph * graph,
  5107. struct ggml_tensor * wo,
  5108. struct ggml_tensor * wo_b,
  5109. struct ggml_tensor * q_cur,
  5110. struct ggml_tensor * kq_mask,
  5111. struct ggml_tensor * kq_pos,
  5112. int64_t n_ctx,
  5113. int32_t n_tokens,
  5114. int32_t n_kv,
  5115. float kq_scale,
  5116. const llm_build_cb & cb,
  5117. int il) {
  5118. const int64_t n_head = hparams.n_head;
  5119. const int64_t n_head_kv = hparams.n_head_kv;
  5120. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  5121. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  5122. const int64_t n_embd_head_v = hparams.n_embd_head_v;
  5123. struct ggml_tensor * q = ggml_permute(ctx, q_cur, 0, 2, 1, 3);
  5124. cb(q, "q", il);
  5125. struct ggml_tensor * k =
  5126. ggml_view_3d(ctx, kv.k_l[il],
  5127. n_embd_head_k, n_kv, n_head_kv,
  5128. ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa),
  5129. ggml_row_size(kv.k_l[il]->type, n_embd_head_k),
  5130. 0);
  5131. cb(k, "k", il);
  5132. struct ggml_tensor * kq = ggml_mul_mat(ctx, k, q);
  5133. cb(kq, "kq", il);
  5134. if (model.arch == LLM_ARCH_PHI2) {
  5135. // for this arch, we need to perform the KQ multiplication with F32 precision, otherwise we get NaNs
  5136. // ref: https://github.com/ggerganov/llama.cpp/pull/4490#issuecomment-1859055847
  5137. ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  5138. }
  5139. if (model.arch == LLM_ARCH_GROK) {
  5140. // need to do the following:
  5141. // multiply by attn_output_multiplyer of 0.08838834764831845
  5142. // and then :
  5143. // kq = 30 * tanh(kq / 30)
  5144. // before the softmax below
  5145. //try from phi2
  5146. //ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  5147. kq = ggml_tanh(ctx, ggml_scale(ctx, kq, 0.08838834764831845f/30.0f));
  5148. kq = ggml_scale(ctx, kq, 30);
  5149. }
  5150. #if defined(GGML_USE_KOMPUTE)
  5151. #pragma message("TODO: ALiBi support in ggml_soft_max_ext is not implemented for Kompute")
  5152. #pragma message(" Falling back to ggml_alibi(). Will become an error in Mar 2024")
  5153. #pragma message("ref: https://github.com/ggerganov/llama.cpp/pull/5488")
  5154. if (hparams.f_max_alibi_bias > 0.0f) {
  5155. kq = ggml_scale(ctx, kq, kq_scale);
  5156. cb(kq, "kq_scaled", il);
  5157. kq = ggml_alibi(ctx, kq, /*n_past*/ 0, n_head, hparams.f_max_alibi_bias);
  5158. cb(kq, "kq_scaled_alibi", il);
  5159. kq = ggml_add(ctx, kq, kq_mask);
  5160. cb(kq, "kq_masked", il);
  5161. kq = ggml_soft_max(ctx, kq);
  5162. cb(kq, "kq_soft_max", il);
  5163. } else
  5164. #endif
  5165. {
  5166. kq = ggml_soft_max_ext(ctx, kq, kq_mask, kq_pos, kq_scale, hparams.f_max_alibi_bias);
  5167. cb(kq, "kq_soft_max_ext", il);
  5168. }
  5169. GGML_ASSERT(kv.size == n_ctx);
  5170. // split cached v into n_head heads
  5171. struct ggml_tensor * v =
  5172. ggml_view_3d(ctx, kv.v_l[il],
  5173. n_kv, n_embd_head_v, n_head_kv,
  5174. ggml_element_size(kv.v_l[il])*n_ctx,
  5175. ggml_element_size(kv.v_l[il])*n_ctx*n_embd_head_v,
  5176. 0);
  5177. cb(v, "v", il);
  5178. struct ggml_tensor * kqv = ggml_mul_mat(ctx, v, kq);
  5179. cb(kqv, "kqv", il);
  5180. struct ggml_tensor * kqv_merged = ggml_permute(ctx, kqv, 0, 2, 1, 3);
  5181. cb(kqv_merged, "kqv_merged", il);
  5182. struct ggml_tensor * cur = ggml_cont_2d(ctx, kqv_merged, n_embd_head_k*n_head, n_tokens);
  5183. cb(cur, "kqv_merged_cont", il);
  5184. ggml_build_forward_expand(graph, cur);
  5185. cur = ggml_mul_mat(ctx, wo, cur);
  5186. if (wo_b) {
  5187. cb(cur, "kqv_wo", il);
  5188. }
  5189. if (wo_b) {
  5190. cur = ggml_add(ctx, cur, wo_b);
  5191. }
  5192. return cur;
  5193. }
  5194. static struct ggml_tensor * llm_build_kv(
  5195. struct ggml_context * ctx,
  5196. const llama_model & model,
  5197. const llama_hparams & hparams,
  5198. const llama_kv_cache & kv,
  5199. struct ggml_cgraph * graph,
  5200. struct ggml_tensor * wo,
  5201. struct ggml_tensor * wo_b,
  5202. struct ggml_tensor * k_cur,
  5203. struct ggml_tensor * v_cur,
  5204. struct ggml_tensor * q_cur,
  5205. struct ggml_tensor * kq_mask,
  5206. struct ggml_tensor * kq_pos,
  5207. int64_t n_ctx,
  5208. int32_t n_tokens,
  5209. int32_t kv_head,
  5210. int32_t n_kv,
  5211. float kq_scale,
  5212. const llm_build_cb & cb,
  5213. int il) {
  5214. // these nodes are added to the graph together so that they are not reordered
  5215. // by doing so, the number of splits in the graph is reduced
  5216. ggml_build_forward_expand(graph, q_cur);
  5217. ggml_build_forward_expand(graph, k_cur);
  5218. ggml_build_forward_expand(graph, v_cur);
  5219. llm_build_kv_store(ctx, hparams, kv, graph, k_cur, v_cur, n_ctx, n_tokens, kv_head, cb, il);
  5220. struct ggml_tensor * cur;
  5221. cur = llm_build_kqv(ctx, model, hparams, kv, graph, wo, wo_b,
  5222. q_cur, kq_mask, kq_pos, n_ctx, n_tokens, n_kv, kq_scale, cb, il);
  5223. cb(cur, "kqv_out", il);
  5224. return cur;
  5225. }
  5226. struct llm_build_context {
  5227. const llama_model & model;
  5228. llama_context & lctx;
  5229. const llama_hparams & hparams;
  5230. const llama_cparams & cparams;
  5231. const llama_batch & batch;
  5232. const llama_kv_cache & kv_self;
  5233. const int64_t n_embd;
  5234. const int64_t n_layer;
  5235. const int64_t n_rot;
  5236. const int64_t n_ctx; // user-specified context size (can be different from n_ctx_train)
  5237. const int64_t n_head;
  5238. const int64_t n_head_kv;
  5239. const int64_t n_embd_head_k;
  5240. const int64_t n_embd_k_gqa;
  5241. const int64_t n_embd_head_v;
  5242. const int64_t n_embd_v_gqa;
  5243. const int64_t n_expert;
  5244. const int64_t n_expert_used;
  5245. const float freq_base;
  5246. const float freq_scale;
  5247. const float ext_factor;
  5248. const float attn_factor;
  5249. const float beta_fast;
  5250. const float beta_slow;
  5251. const float norm_eps;
  5252. const float norm_rms_eps;
  5253. const int32_t n_tokens;
  5254. const int32_t n_kv; // size of KV cache to consider (n_kv <= kv_self.size)
  5255. const int32_t n_outputs;
  5256. const int32_t kv_head; // index of where we store new KV data in the cache
  5257. const int32_t n_orig_ctx;
  5258. const enum llama_pooling_type pooling_type;
  5259. const enum llama_rope_type rope_type;
  5260. const llm_build_cb & cb;
  5261. std::vector<uint8_t> & buf_compute_meta;
  5262. struct ggml_context * ctx0 = nullptr;
  5263. // TODO: consider making the entire interface noexcept
  5264. llm_build_context(
  5265. llama_context & lctx,
  5266. const llama_batch & batch,
  5267. const llm_build_cb & cb,
  5268. bool worst_case) :
  5269. model (lctx.model),
  5270. lctx (lctx),
  5271. hparams (model.hparams),
  5272. cparams (lctx.cparams),
  5273. batch (batch),
  5274. kv_self (lctx.kv_self),
  5275. n_embd (hparams.n_embd),
  5276. n_layer (hparams.n_layer),
  5277. n_rot (hparams.n_rot),
  5278. n_ctx (cparams.n_ctx),
  5279. n_head (hparams.n_head),
  5280. n_head_kv (hparams.n_head_kv),
  5281. n_embd_head_k (hparams.n_embd_head_k),
  5282. n_embd_k_gqa (hparams.n_embd_k_gqa()),
  5283. n_embd_head_v (hparams.n_embd_head_v),
  5284. n_embd_v_gqa (hparams.n_embd_v_gqa()),
  5285. n_expert (hparams.n_expert),
  5286. n_expert_used (hparams.n_expert_used),
  5287. freq_base (cparams.rope_freq_base),
  5288. freq_scale (cparams.rope_freq_scale),
  5289. ext_factor (cparams.yarn_ext_factor),
  5290. attn_factor (cparams.yarn_attn_factor),
  5291. beta_fast (cparams.yarn_beta_fast),
  5292. beta_slow (cparams.yarn_beta_slow),
  5293. norm_eps (hparams.f_norm_eps),
  5294. norm_rms_eps (hparams.f_norm_rms_eps),
  5295. n_tokens (batch.n_tokens),
  5296. n_kv (worst_case ? kv_self.size : kv_self.n),
  5297. n_outputs (worst_case ? n_tokens : lctx.n_outputs),
  5298. kv_head (worst_case ? (kv_self.recurrent ? 0 : kv_self.size - n_tokens) : kv_self.head),
  5299. n_orig_ctx (cparams.n_yarn_orig_ctx),
  5300. pooling_type (cparams.pooling_type),
  5301. rope_type (hparams.rope_type),
  5302. cb (cb),
  5303. buf_compute_meta (lctx.buf_compute_meta) {
  5304. // all initializations should be done in init()
  5305. }
  5306. void init() {
  5307. struct ggml_init_params params = {
  5308. /*.mem_size =*/ buf_compute_meta.size(),
  5309. /*.mem_buffer =*/ buf_compute_meta.data(),
  5310. /*.no_alloc =*/ true,
  5311. };
  5312. ctx0 = ggml_init(params);
  5313. lctx.inp_tokens = nullptr;
  5314. lctx.inp_embd = nullptr;
  5315. lctx.inp_pos = nullptr;
  5316. lctx.inp_out_ids = nullptr;
  5317. lctx.inp_KQ_mask = nullptr;
  5318. lctx.inp_KQ_pos = nullptr;
  5319. lctx.inp_K_shift = nullptr;
  5320. lctx.inp_mean = nullptr;
  5321. lctx.inp_cls = nullptr;
  5322. lctx.inp_s_copy = nullptr;
  5323. lctx.inp_s_mask = nullptr;
  5324. lctx.inp_s_seq = nullptr;
  5325. }
  5326. void free() {
  5327. if (ctx0) {
  5328. ggml_free(ctx0);
  5329. ctx0 = nullptr;
  5330. }
  5331. }
  5332. struct ggml_cgraph * build_k_shift() {
  5333. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5334. GGML_ASSERT(kv_self.size == n_ctx);
  5335. lctx.inp_K_shift = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_ctx);
  5336. cb(lctx.inp_K_shift, "K_shift", -1);
  5337. ggml_set_input(lctx.inp_K_shift);
  5338. for (int il = 0; il < n_layer; ++il) {
  5339. struct ggml_tensor * tmp =
  5340. // we rotate only the first n_rot dimensions
  5341. ggml_rope_custom_inplace(ctx0,
  5342. ggml_view_3d(ctx0, kv_self.k_l[il],
  5343. n_embd_head_k, n_head_kv, n_ctx,
  5344. ggml_row_size(kv_self.k_l[il]->type, n_embd_head_k),
  5345. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  5346. 0),
  5347. lctx.inp_K_shift, n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5348. ext_factor, attn_factor, beta_fast, beta_slow);
  5349. cb(tmp, "K_shifted", il);
  5350. ggml_build_forward_expand(gf, tmp);
  5351. }
  5352. return gf;
  5353. }
  5354. struct ggml_cgraph * build_s_copy() {
  5355. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5356. GGML_ASSERT(kv_self.recurrent);
  5357. struct ggml_tensor * state_copy = build_inp_s_copy();
  5358. for (int il = 0; il < n_layer; ++il) {
  5359. struct ggml_tensor * conv_states = ggml_reshape_2d(ctx0, kv_self.k_l[il], hparams.n_embd_k_s(), kv_self.size);
  5360. struct ggml_tensor * ssm_states = ggml_reshape_2d(ctx0, kv_self.v_l[il], hparams.n_embd_v_s(), kv_self.size);
  5361. conv_states = ggml_get_rows(ctx0, conv_states, state_copy);
  5362. ssm_states = ggml_get_rows(ctx0, ssm_states, state_copy);
  5363. // TODO: name the intermediate tensors with cb()
  5364. ggml_build_forward_expand(gf, ggml_cpy(ctx0, conv_states, kv_self.k_l[il]));
  5365. ggml_build_forward_expand(gf, ggml_cpy(ctx0, ssm_states, kv_self.v_l[il]));
  5366. }
  5367. return gf;
  5368. }
  5369. struct ggml_cgraph * build_defrag(const std::vector<uint32_t> & ids) {
  5370. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5371. for (uint32_t i = 0; i < ids.size(); ++i) {
  5372. const uint32_t id = ids[i];
  5373. if (i == id || id == ids.size()) {
  5374. continue;
  5375. }
  5376. uint32_t nm = 1;
  5377. while (i + nm < ids.size() && ids[i + nm] == id + nm) {
  5378. nm++;
  5379. }
  5380. for (int il = 0; il < n_layer; ++il) {
  5381. ggml_tensor * view_k_src = ggml_view_2d(ctx0, kv_self.k_l[il],
  5382. n_embd_k_gqa, nm,
  5383. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  5384. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*i));
  5385. ggml_tensor * view_k_dst = ggml_view_2d(ctx0, kv_self.k_l[il],
  5386. n_embd_k_gqa, nm,
  5387. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  5388. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*id));
  5389. ggml_tensor * view_v_src = ggml_view_2d(ctx0, kv_self.v_l[il],
  5390. nm, n_embd_v_gqa,
  5391. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  5392. ggml_row_size(kv_self.v_l[il]->type, i));
  5393. ggml_tensor * view_v_dst = ggml_view_2d(ctx0, kv_self.v_l[il],
  5394. nm, n_embd_v_gqa,
  5395. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  5396. ggml_row_size(kv_self.v_l[il]->type, id));
  5397. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_k_src, view_k_dst));
  5398. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_v_src, view_v_dst));
  5399. }
  5400. i += nm - 1;
  5401. }
  5402. //LLAMA_LOG_INFO("gf->n_nodes = %d\n", gf->n_nodes);
  5403. return gf;
  5404. }
  5405. struct ggml_tensor * build_inp_pos() {
  5406. lctx.inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  5407. cb(lctx.inp_pos, "inp_pos", -1);
  5408. ggml_set_input(lctx.inp_pos);
  5409. return lctx.inp_pos;
  5410. }
  5411. struct ggml_tensor * build_inp_out_ids() {
  5412. lctx.inp_out_ids = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_outputs);
  5413. cb(lctx.inp_out_ids, "inp_out_ids", -1);
  5414. ggml_set_input(lctx.inp_out_ids);
  5415. return lctx.inp_out_ids;
  5416. }
  5417. struct ggml_tensor * build_inp_KQ_mask(bool causal = true) {
  5418. if (causal) {
  5419. lctx.inp_KQ_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_kv, n_tokens);
  5420. } else {
  5421. lctx.inp_KQ_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, n_tokens);
  5422. }
  5423. cb(lctx.inp_KQ_mask, "KQ_mask", -1);
  5424. ggml_set_input(lctx.inp_KQ_mask);
  5425. return lctx.inp_KQ_mask;
  5426. }
  5427. struct ggml_tensor * build_inp_KQ_pos() {
  5428. lctx.inp_KQ_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, n_kv);
  5429. cb(lctx.inp_KQ_pos, "KQ_pos", -1);
  5430. ggml_set_input(lctx.inp_KQ_pos);
  5431. return lctx.inp_KQ_pos;
  5432. }
  5433. struct ggml_tensor * build_inp_mean() {
  5434. lctx.inp_mean = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, n_tokens);
  5435. cb(lctx.inp_mean, "inp_mean", -1);
  5436. ggml_set_input(lctx.inp_mean);
  5437. return lctx.inp_mean;
  5438. }
  5439. struct ggml_tensor * build_inp_cls() {
  5440. lctx.inp_cls = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  5441. cb(lctx.inp_cls, "inp_cls", -1);
  5442. ggml_set_input(lctx.inp_cls);
  5443. return lctx.inp_cls;
  5444. }
  5445. struct ggml_tensor * build_inp_s_copy() {
  5446. lctx.inp_s_copy = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, kv_self.size);
  5447. cb(lctx.inp_s_copy, "inp_s_copy", -1);
  5448. ggml_set_input(lctx.inp_s_copy);
  5449. return lctx.inp_s_copy;
  5450. }
  5451. struct ggml_tensor * build_inp_s_mask() {
  5452. lctx.inp_s_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, 1, n_kv);
  5453. cb(lctx.inp_s_mask, "inp_s_mask", -1);
  5454. ggml_set_input(lctx.inp_s_mask);
  5455. return lctx.inp_s_mask;
  5456. }
  5457. struct ggml_tensor * build_inp_s_seq() {
  5458. lctx.inp_s_seq = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_kv, n_tokens);
  5459. cb(lctx.inp_s_seq, "inp_s_seq", -1);
  5460. ggml_set_input(lctx.inp_s_seq);
  5461. return lctx.inp_s_seq;
  5462. }
  5463. struct ggml_cgraph * build_llama() {
  5464. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5465. // mutable variable, needed during the last layer of the computation to skip unused tokens
  5466. int32_t n_tokens = this->n_tokens;
  5467. const int64_t n_embd_head = hparams.n_embd_head_v;
  5468. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5469. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5470. struct ggml_tensor * cur;
  5471. struct ggml_tensor * inpL;
  5472. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5473. // inp_pos - contains the positions
  5474. struct ggml_tensor * inp_pos = build_inp_pos();
  5475. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5476. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5477. for (int il = 0; il < n_layer; ++il) {
  5478. struct ggml_tensor * inpSA = inpL;
  5479. // norm
  5480. cur = llm_build_norm(ctx0, inpL, hparams,
  5481. model.layers[il].attn_norm, NULL,
  5482. LLM_NORM_RMS, cb, il);
  5483. cb(cur, "attn_norm", il);
  5484. // self-attention
  5485. {
  5486. // compute Q and K and RoPE them
  5487. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5488. cb(Qcur, "Qcur", il);
  5489. if (model.layers[il].bq) {
  5490. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5491. cb(Qcur, "Qcur", il);
  5492. }
  5493. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5494. cb(Kcur, "Kcur", il);
  5495. if (model.layers[il].bk) {
  5496. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5497. cb(Kcur, "Kcur", il);
  5498. }
  5499. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5500. cb(Vcur, "Vcur", il);
  5501. if (model.layers[il].bv) {
  5502. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  5503. cb(Vcur, "Vcur", il);
  5504. }
  5505. Qcur = ggml_rope_custom(
  5506. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5507. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5508. ext_factor, attn_factor, beta_fast, beta_slow
  5509. );
  5510. cb(Qcur, "Qcur", il);
  5511. Kcur = ggml_rope_custom(
  5512. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5513. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5514. ext_factor, attn_factor, beta_fast, beta_slow
  5515. );
  5516. cb(Kcur, "Kcur", il);
  5517. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5518. model.layers[il].wo, model.layers[il].bo,
  5519. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5520. }
  5521. if (il == n_layer - 1) {
  5522. // skip computing output for unused tokens
  5523. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  5524. n_tokens = n_outputs;
  5525. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  5526. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  5527. }
  5528. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5529. cb(ffn_inp, "ffn_inp", il);
  5530. // feed-forward network
  5531. if (model.layers[il].ffn_gate_inp == nullptr) {
  5532. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5533. model.layers[il].ffn_norm, NULL,
  5534. LLM_NORM_RMS, cb, il);
  5535. cb(cur, "ffn_norm", il);
  5536. cur = llm_build_ffn(ctx0, cur,
  5537. model.layers[il].ffn_up, NULL,
  5538. model.layers[il].ffn_gate, NULL,
  5539. model.layers[il].ffn_down, NULL,
  5540. NULL,
  5541. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5542. cb(cur, "ffn_out", il);
  5543. } else {
  5544. // MoE branch
  5545. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5546. model.layers[il].ffn_norm, NULL,
  5547. LLM_NORM_RMS, cb, il);
  5548. cb(cur, "ffn_norm", il);
  5549. cur = build_moe_ffn(cur, n_tokens, LLM_FFN_SILU, il);
  5550. }
  5551. cur = ggml_add(ctx0, cur, ffn_inp);
  5552. cb(cur, "ffn_out", il);
  5553. ggml_tensor * layer_dir = lctx.cvec.tensor_for(il);
  5554. if (layer_dir != nullptr) {
  5555. cur = ggml_add(ctx0, cur, layer_dir);
  5556. }
  5557. cb(cur, "l_out", il);
  5558. // input for next layer
  5559. inpL = cur;
  5560. }
  5561. cur = inpL;
  5562. cur = llm_build_norm(ctx0, cur, hparams,
  5563. model.output_norm, NULL,
  5564. LLM_NORM_RMS, cb, -1);
  5565. cb(cur, "result_norm", -1);
  5566. // lm_head
  5567. cur = ggml_mul_mat(ctx0, model.output, cur);
  5568. cb(cur, "result_output", -1);
  5569. ggml_build_forward_expand(gf, cur);
  5570. return gf;
  5571. }
  5572. // REVIEW: will be replaced by https://github.com/ggerganov/llama.cpp/pull/6505
  5573. ggml_tensor * build_moe_ffn(ggml_tensor * cur, int32_t n_tokens, llm_ffn_op_type type_op, int il) {
  5574. ggml_tensor * logits = ggml_mul_mat(ctx0, model.layers[il].ffn_gate_inp, cur); // [n_tokens, num_experts]
  5575. cb(logits, "ffn_moe_logits", il);
  5576. ggml_tensor * probs = ggml_soft_max(ctx0, logits); // [n_tokens, num_experts]
  5577. cb(probs, "ffn_moe_probs", il);
  5578. // select experts
  5579. ggml_tensor * selected_experts = ggml_top_k(ctx0, probs, n_expert_used); // [n_tokens, num_experts_per_tok]
  5580. cb(selected_experts->src[0], "ffn_moe_argsort", il);
  5581. ggml_tensor * weights = ggml_get_rows(ctx0,
  5582. ggml_reshape_3d(ctx0, probs, 1, n_expert, n_tokens), selected_experts);
  5583. cb(weights, "ffn_moe_weights", il);
  5584. weights = ggml_reshape_2d(ctx0, weights, n_expert_used, n_tokens); // [n_tokens, num_experts_per_tok]
  5585. ggml_tensor * weights_sum = ggml_sum_rows(ctx0, weights);
  5586. cb(weights_sum, "ffn_moe_weights_sum", il);
  5587. weights = ggml_div(ctx0, weights, weights_sum); // [n_tokens, num_experts_per_tok]
  5588. cb(weights, "ffn_moe_weights_norm", il);
  5589. // compute expert outputs
  5590. ggml_tensor * moe_out = nullptr;
  5591. for (int i = 0; i < n_expert_used; ++i) {
  5592. ggml_tensor * cur_expert;
  5593. ggml_tensor * cur_up = ggml_mul_mat_id(ctx0, model.layers[il].ffn_up_exps, selected_experts, i, cur);
  5594. cb(cur_up, "ffn_moe_up", il);
  5595. ggml_tensor * gate = ggml_mul_mat_id(ctx0, model.layers[il].ffn_gate_exps, selected_experts, i, cur);
  5596. cb(gate, "ffn_moe_gate", il);
  5597. switch (type_op) {
  5598. case LLM_FFN_SILU:
  5599. {
  5600. gate = ggml_silu(ctx0, gate);
  5601. cb(gate, "ffn_moe_silu", il);
  5602. } break;
  5603. case LLM_FFN_GELU:
  5604. {
  5605. gate = ggml_gelu(ctx0, gate);
  5606. cb(gate, "ffn_moe_gelu", il);
  5607. } break;
  5608. default:
  5609. GGML_ASSERT(false);
  5610. }
  5611. cur_expert = ggml_mul(ctx0, cur_up, gate);
  5612. cb(cur_expert, "ffn_moe_gate_par", il);
  5613. cur_expert = ggml_mul_mat_id(ctx0, model.layers[il].ffn_down_exps, selected_experts, i, cur_expert); // [n_tokens, n_embd]
  5614. cb(cur_expert, "ffn_moe_down", il);
  5615. cur_expert = ggml_mul(ctx0, cur_expert,
  5616. ggml_view_2d(ctx0, weights, 1, n_tokens, weights->nb[1], i*weights->nb[0]));
  5617. cb(cur_expert, "ffn_moe_weighted", il);
  5618. if (i == 0) {
  5619. moe_out = cur_expert;
  5620. } else {
  5621. moe_out = ggml_add(ctx0, moe_out, cur_expert);
  5622. cb(moe_out, "ffn_moe_out", il);
  5623. }
  5624. }
  5625. return moe_out;
  5626. }
  5627. struct ggml_cgraph * build_baichuan() {
  5628. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5629. const int64_t n_embd_head = hparams.n_embd_head_v;
  5630. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5631. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5632. struct ggml_tensor * cur;
  5633. struct ggml_tensor * inpL;
  5634. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5635. // inp_pos - contains the positions
  5636. struct ggml_tensor * inp_pos = model.type == MODEL_7B ? build_inp_pos() : nullptr;
  5637. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5638. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5639. // positions of the tokens in the KV cache
  5640. struct ggml_tensor * KQ_pos = build_inp_KQ_pos();
  5641. for (int il = 0; il < n_layer; ++il) {
  5642. struct ggml_tensor * inpSA = inpL;
  5643. cur = llm_build_norm(ctx0, inpL, hparams,
  5644. model.layers[il].attn_norm, NULL,
  5645. LLM_NORM_RMS, cb, il);
  5646. cb(cur, "attn_norm", il);
  5647. // self-attention
  5648. {
  5649. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5650. cb(Qcur, "Qcur", il);
  5651. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5652. cb(Kcur, "Kcur", il);
  5653. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5654. cb(Vcur, "Vcur", il);
  5655. switch (model.type) {
  5656. case MODEL_7B:
  5657. Qcur = ggml_rope_custom(
  5658. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5659. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5660. ext_factor, attn_factor, beta_fast, beta_slow
  5661. );
  5662. Kcur = ggml_rope_custom(
  5663. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5664. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5665. ext_factor, attn_factor, beta_fast, beta_slow
  5666. );
  5667. break;
  5668. case MODEL_13B:
  5669. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd/n_head, n_head, n_tokens);
  5670. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd/n_head, n_head, n_tokens);
  5671. break;
  5672. default:
  5673. GGML_ASSERT(false);
  5674. }
  5675. cb(Qcur, "Qcur", il);
  5676. cb(Kcur, "Kcur", il);
  5677. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5678. model.layers[il].wo, NULL,
  5679. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5680. }
  5681. if (il == n_layer - 1) {
  5682. // skip computing output for unused tokens
  5683. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  5684. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  5685. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  5686. }
  5687. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5688. cb(ffn_inp, "ffn_inp", il);
  5689. // feed-forward network
  5690. {
  5691. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5692. model.layers[il].ffn_norm, NULL,
  5693. LLM_NORM_RMS, cb, il);
  5694. cb(cur, "ffn_norm", il);
  5695. cur = llm_build_ffn(ctx0, cur,
  5696. model.layers[il].ffn_up, NULL,
  5697. model.layers[il].ffn_gate, NULL,
  5698. model.layers[il].ffn_down, NULL,
  5699. NULL,
  5700. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5701. cb(cur, "ffn_out", il);
  5702. }
  5703. cur = ggml_add(ctx0, cur, ffn_inp);
  5704. cb(cur, "l_out", il);
  5705. // input for next layer
  5706. inpL = cur;
  5707. }
  5708. cur = inpL;
  5709. cur = llm_build_norm(ctx0, cur, hparams,
  5710. model.output_norm, NULL,
  5711. LLM_NORM_RMS, cb, -1);
  5712. cb(cur, "result_norm", -1);
  5713. // lm_head
  5714. cur = ggml_mul_mat(ctx0, model.output, cur);
  5715. cb(cur, "result_output", -1);
  5716. ggml_build_forward_expand(gf, cur);
  5717. return gf;
  5718. }
  5719. struct ggml_cgraph * build_xverse() {
  5720. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5721. const int64_t n_embd_head = hparams.n_embd_head_v;
  5722. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5723. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5724. struct ggml_tensor * cur;
  5725. struct ggml_tensor * inpL;
  5726. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5727. // inp_pos - contains the positions
  5728. struct ggml_tensor * inp_pos = build_inp_pos();
  5729. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5730. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5731. // positions of the tokens in the KV cache
  5732. struct ggml_tensor * KQ_pos = build_inp_KQ_pos();
  5733. for (int il = 0; il < n_layer; ++il) {
  5734. struct ggml_tensor * inpSA = inpL;
  5735. cur = llm_build_norm(ctx0, inpL, hparams,
  5736. model.layers[il].attn_norm, NULL,
  5737. LLM_NORM_RMS, cb, il);
  5738. cb(cur, "attn_norm", il);
  5739. // self-attention
  5740. {
  5741. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5742. cb(Qcur, "Qcur", il);
  5743. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5744. cb(Kcur, "Kcur", il);
  5745. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5746. cb(Vcur, "Vcur", il);
  5747. Qcur = ggml_rope_custom(
  5748. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5749. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5750. ext_factor, attn_factor, beta_fast, beta_slow
  5751. );
  5752. cb(Qcur, "Qcur", il);
  5753. Kcur = ggml_rope_custom(
  5754. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5755. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5756. ext_factor, attn_factor, beta_fast, beta_slow
  5757. );
  5758. cb(Kcur, "Kcur", il);
  5759. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5760. model.layers[il].wo, NULL,
  5761. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5762. }
  5763. if (il == n_layer - 1) {
  5764. // skip computing output for unused tokens
  5765. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  5766. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  5767. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  5768. }
  5769. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5770. cb(ffn_inp, "ffn_inp", il);
  5771. // feed-forward network
  5772. {
  5773. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5774. model.layers[il].ffn_norm, NULL,
  5775. LLM_NORM_RMS, cb, il);
  5776. cb(cur, "ffn_norm", il);
  5777. cur = llm_build_ffn(ctx0, cur,
  5778. model.layers[il].ffn_up, NULL,
  5779. model.layers[il].ffn_gate, NULL,
  5780. model.layers[il].ffn_down, NULL,
  5781. NULL,
  5782. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5783. cb(cur, "ffn_out", il);
  5784. }
  5785. cur = ggml_add(ctx0, cur, ffn_inp);
  5786. cb(cur, "l_out", il);
  5787. // input for next layer
  5788. inpL = cur;
  5789. }
  5790. cur = inpL;
  5791. cur = llm_build_norm(ctx0, cur, hparams, model.output_norm, NULL, LLM_NORM_RMS, cb, -1);
  5792. cb(cur, "result_norm", -1);
  5793. // lm_head
  5794. cur = ggml_mul_mat(ctx0, model.output, cur);
  5795. cb(cur, "result_output", -1);
  5796. ggml_build_forward_expand(gf, cur);
  5797. return gf;
  5798. }
  5799. struct ggml_cgraph * build_falcon() {
  5800. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5801. const int64_t n_embd_head = hparams.n_embd_head_v;
  5802. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5803. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5804. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5805. struct ggml_tensor * cur;
  5806. struct ggml_tensor * inpL;
  5807. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5808. // inp_pos - contains the positions
  5809. struct ggml_tensor * inp_pos = build_inp_pos();
  5810. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5811. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5812. for (int il = 0; il < n_layer; ++il) {
  5813. struct ggml_tensor * attn_norm;
  5814. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  5815. model.layers[il].attn_norm,
  5816. model.layers[il].attn_norm_b,
  5817. LLM_NORM, cb, il);
  5818. cb(attn_norm, "attn_norm", il);
  5819. // self-attention
  5820. {
  5821. if (model.layers[il].attn_norm_2) {
  5822. // Falcon-40B
  5823. cur = llm_build_norm(ctx0, inpL, hparams,
  5824. model.layers[il].attn_norm_2,
  5825. model.layers[il].attn_norm_2_b,
  5826. LLM_NORM, cb, il);
  5827. cb(cur, "attn_norm_2", il);
  5828. } else {
  5829. cur = attn_norm;
  5830. }
  5831. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5832. cb(cur, "wqkv", il);
  5833. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5834. 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)));
  5835. 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)));
  5836. cb(Qcur, "Qcur", il);
  5837. cb(Kcur, "Kcur", il);
  5838. cb(Vcur, "Vcur", il);
  5839. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5840. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  5841. // using mode = 2 for neox mode
  5842. Qcur = ggml_rope_custom(
  5843. ctx0, Qcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5844. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5845. );
  5846. cb(Qcur, "Qcur", il);
  5847. Kcur = ggml_rope_custom(
  5848. ctx0, Kcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5849. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5850. );
  5851. cb(Kcur, "Kcur", il);
  5852. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5853. model.layers[il].wo, NULL,
  5854. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5855. }
  5856. if (il == n_layer - 1) {
  5857. // skip computing output for unused tokens
  5858. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  5859. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  5860. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  5861. attn_norm = ggml_get_rows(ctx0, attn_norm, inp_out_ids);
  5862. }
  5863. struct ggml_tensor * ffn_inp = cur;
  5864. // feed forward
  5865. {
  5866. cur = llm_build_ffn(ctx0, attn_norm, // !! use the attn norm, not the result
  5867. model.layers[il].ffn_up, NULL,
  5868. NULL, NULL,
  5869. model.layers[il].ffn_down, NULL,
  5870. NULL,
  5871. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5872. cb(cur, "ffn_out", il);
  5873. }
  5874. cur = ggml_add(ctx0, cur, ffn_inp);
  5875. cb(cur, "l_out", il);
  5876. cur = ggml_add(ctx0, cur, inpL);
  5877. cb(cur, "l_out", il);
  5878. // input for next layer
  5879. inpL = cur;
  5880. }
  5881. cur = inpL;
  5882. // norm
  5883. cur = llm_build_norm(ctx0, cur, hparams,
  5884. model.output_norm,
  5885. model.output_norm_b,
  5886. LLM_NORM, cb, -1);
  5887. cb(cur, "result_norm", -1);
  5888. cur = ggml_mul_mat(ctx0, model.output, cur);
  5889. cb(cur, "result_output", -1);
  5890. ggml_build_forward_expand(gf, cur);
  5891. return gf;
  5892. }
  5893. struct ggml_cgraph * build_grok() {
  5894. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5895. // mutable variable, needed during the last layer of the computation to skip unused tokens
  5896. int32_t n_tokens = this->n_tokens;
  5897. const int64_t n_embd_head = hparams.n_embd_head_v;
  5898. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5899. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5900. struct ggml_tensor * cur;
  5901. struct ggml_tensor * inpL;
  5902. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5903. // multiply by embedding_multiplier_scale of 78.38367176906169
  5904. inpL = ggml_scale(ctx0, inpL, 78.38367176906169f);
  5905. // inp_pos - contains the positions
  5906. struct ggml_tensor * inp_pos = build_inp_pos();
  5907. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5908. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5909. for (int il = 0; il < n_layer; ++il) {
  5910. struct ggml_tensor * inpSA = inpL;
  5911. // norm
  5912. cur = llm_build_norm(ctx0, inpL, hparams,
  5913. model.layers[il].attn_norm, NULL,
  5914. LLM_NORM_RMS, cb, il);
  5915. cb(cur, "attn_norm", il);
  5916. // self-attention
  5917. {
  5918. // compute Q and K and RoPE them
  5919. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5920. cb(Qcur, "Qcur", il);
  5921. if (model.layers[il].bq) {
  5922. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5923. cb(Qcur, "Qcur", il);
  5924. }
  5925. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5926. cb(Kcur, "Kcur", il);
  5927. if (model.layers[il].bk) {
  5928. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5929. cb(Kcur, "Kcur", il);
  5930. }
  5931. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5932. cb(Vcur, "Vcur", il);
  5933. if (model.layers[il].bv) {
  5934. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  5935. cb(Vcur, "Vcur", il);
  5936. }
  5937. Qcur = ggml_rope_custom(
  5938. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5939. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5940. ext_factor, attn_factor, beta_fast, beta_slow
  5941. );
  5942. cb(Qcur, "Qcur", il);
  5943. Kcur = ggml_rope_custom(
  5944. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5945. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5946. ext_factor, attn_factor, beta_fast, beta_slow
  5947. );
  5948. cb(Kcur, "Kcur", il);
  5949. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5950. model.layers[il].wo, model.layers[il].bo,
  5951. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  5952. }
  5953. if (il == n_layer - 1) {
  5954. // skip computing output for unused tokens
  5955. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  5956. n_tokens = n_outputs;
  5957. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  5958. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  5959. }
  5960. // Grok
  5961. // if attn_out_norm is present then apply it before adding the input
  5962. if (model.layers[il].attn_out_norm) {
  5963. cur = llm_build_norm(ctx0, cur, hparams,
  5964. model.layers[il].attn_out_norm, NULL,
  5965. LLM_NORM_RMS, cb, il);
  5966. cb(cur, "attn_out_norm", il);
  5967. }
  5968. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5969. cb(ffn_inp, "ffn_inp", il);
  5970. // feed-forward network
  5971. // MoE branch
  5972. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5973. model.layers[il].ffn_norm, NULL,
  5974. LLM_NORM_RMS, cb, il);
  5975. cb(cur, "ffn_norm", il);
  5976. cur = build_moe_ffn(cur, n_tokens, LLM_FFN_GELU, il);
  5977. // Grok
  5978. // if layer_out_norm is present then apply it before adding the input
  5979. // Idea: maybe ffn_out_norm is a better name
  5980. if (model.layers[il].layer_out_norm) {
  5981. cur = llm_build_norm(ctx0, cur, hparams,
  5982. model.layers[il].layer_out_norm, NULL,
  5983. LLM_NORM_RMS, cb, il);
  5984. cb(cur, "layer_out_norm", il);
  5985. }
  5986. cur = ggml_add(ctx0, cur, ffn_inp);
  5987. cb(cur, "ffn_out", il);
  5988. ggml_tensor * layer_dir = lctx.cvec.tensor_for(il);
  5989. if (layer_dir != nullptr) {
  5990. cur = ggml_add(ctx0, cur, layer_dir);
  5991. }
  5992. cb(cur, "l_out", il);
  5993. // input for next layer
  5994. inpL = cur;
  5995. }
  5996. cur = inpL;
  5997. cur = llm_build_norm(ctx0, cur, hparams,
  5998. model.output_norm, NULL,
  5999. LLM_NORM_RMS, cb, -1);
  6000. cb(cur, "result_norm", -1);
  6001. // lm_head
  6002. cur = ggml_mul_mat(ctx0, model.output, cur);
  6003. // Grok
  6004. // multiply logits by output_multiplier_scale of 0.5773502691896257
  6005. cur = ggml_scale(ctx0, cur, 0.5773502691896257f);
  6006. cb(cur, "result_output", -1);
  6007. ggml_build_forward_expand(gf, cur);
  6008. return gf;
  6009. }
  6010. struct ggml_cgraph * build_dbrx() {
  6011. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6012. // mutable variable, needed during the last layer of the computation to skip unused tokens
  6013. int32_t n_tokens = this->n_tokens;
  6014. const int64_t n_embd_head = hparams.n_embd_head_v;
  6015. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  6016. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6017. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6018. struct ggml_tensor * cur;
  6019. struct ggml_tensor * inpL;
  6020. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6021. // inp_pos - contains the positions
  6022. struct ggml_tensor * inp_pos = build_inp_pos();
  6023. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6024. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6025. for (int il = 0; il < n_layer; ++il) {
  6026. struct ggml_tensor * inpSA = inpL;
  6027. // norm
  6028. cur = llm_build_norm(ctx0, inpL, hparams,
  6029. model.layers[il].attn_norm, NULL,
  6030. LLM_NORM, cb, il);
  6031. cb(cur, "attn_norm", il);
  6032. // self-attention
  6033. {
  6034. struct ggml_tensor * Qcur = nullptr;
  6035. struct ggml_tensor * Kcur = nullptr;
  6036. struct ggml_tensor * Vcur = nullptr;
  6037. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6038. cb(cur, "wqkv", il);
  6039. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  6040. cb(cur, "wqkv_clamped", il);
  6041. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6042. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  6043. 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)));
  6044. cb(Qcur, "Qcur", il);
  6045. cb(Kcur, "Kcur", il);
  6046. cb(Vcur, "Vcur", il);
  6047. Qcur = ggml_rope_custom(
  6048. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6049. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6050. ext_factor, attn_factor, beta_fast, beta_slow
  6051. );
  6052. cb(Qcur, "Qcur", il);
  6053. Kcur = ggml_rope_custom(
  6054. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6055. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6056. ext_factor, attn_factor, beta_fast, beta_slow
  6057. );
  6058. cb(Kcur, "Kcur", il);
  6059. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6060. model.layers[il].wo, NULL,
  6061. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6062. }
  6063. if (il == n_layer - 1) {
  6064. // skip computing output for unused tokens
  6065. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6066. n_tokens = n_outputs;
  6067. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6068. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  6069. }
  6070. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6071. cb(ffn_inp, "ffn_inp", il);
  6072. // feed-forward network
  6073. // MoE branch
  6074. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6075. model.layers[il].attn_out_norm, NULL,
  6076. LLM_NORM, cb, il);
  6077. cb(cur, "attn_out_norm", il);
  6078. cur = build_moe_ffn(cur, n_tokens, LLM_FFN_SILU, il);
  6079. cur = ggml_add(ctx0, cur, ffn_inp);
  6080. cb(cur, "ffn_out", il);
  6081. ggml_tensor * layer_dir = lctx.cvec.tensor_for(il);
  6082. if (layer_dir != nullptr) {
  6083. cur = ggml_add(ctx0, cur, layer_dir);
  6084. }
  6085. cb(cur, "l_out", il);
  6086. // input for next layer
  6087. inpL = cur;
  6088. }
  6089. cur = inpL;
  6090. cur = llm_build_norm(ctx0, cur, hparams,
  6091. model.output_norm, NULL,
  6092. LLM_NORM, cb, -1);
  6093. cb(cur, "result_norm", -1);
  6094. // lm_head
  6095. cur = ggml_mul_mat(ctx0, model.output, cur);
  6096. cb(cur, "result_output", -1);
  6097. ggml_build_forward_expand(gf, cur);
  6098. return gf;
  6099. }
  6100. struct ggml_cgraph * build_starcoder() {
  6101. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6102. const int64_t n_embd_head = hparams.n_embd_head_v;
  6103. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  6104. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6105. struct ggml_tensor * cur;
  6106. struct ggml_tensor * inpL;
  6107. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6108. // inp_pos - contains the positions
  6109. struct ggml_tensor * inp_pos = build_inp_pos();
  6110. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6111. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6112. struct ggml_tensor * pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  6113. cb(pos, "pos_embd", -1);
  6114. inpL = ggml_add(ctx0, inpL, pos);
  6115. cb(inpL, "inpL", -1);
  6116. for (int il = 0; il < n_layer; ++il) {
  6117. cur = llm_build_norm(ctx0, inpL, hparams,
  6118. model.layers[il].attn_norm,
  6119. model.layers[il].attn_norm_b,
  6120. LLM_NORM, cb, il);
  6121. cb(cur, "attn_norm", il);
  6122. // self-attention
  6123. {
  6124. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6125. cb(cur, "wqkv", il);
  6126. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6127. cb(cur, "bqkv", il);
  6128. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6129. 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)));
  6130. 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)));
  6131. cb(Qcur, "Qcur", il);
  6132. cb(Kcur, "Kcur", il);
  6133. cb(Vcur, "Vcur", il);
  6134. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6135. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6136. model.layers[il].wo, model.layers[il].bo,
  6137. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6138. }
  6139. if (il == n_layer - 1) {
  6140. // skip computing output for unused tokens
  6141. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6142. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6143. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  6144. }
  6145. // add the input
  6146. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  6147. cb(ffn_inp, "ffn_inp", il);
  6148. // FF
  6149. {
  6150. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6151. model.layers[il].ffn_norm,
  6152. model.layers[il].ffn_norm_b,
  6153. LLM_NORM, cb, il);
  6154. cb(cur, "ffn_norm", il);
  6155. cur = llm_build_ffn(ctx0, cur,
  6156. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6157. NULL, NULL,
  6158. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6159. NULL,
  6160. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6161. cb(cur, "ffn_out", il);
  6162. }
  6163. inpL = ggml_add(ctx0, cur, ffn_inp);
  6164. cb(inpL, "l_out", il);
  6165. }
  6166. cur = llm_build_norm(ctx0, inpL, hparams,
  6167. model.output_norm,
  6168. model.output_norm_b,
  6169. LLM_NORM, cb, -1);
  6170. cb(cur, "result_norm", -1);
  6171. cur = ggml_mul_mat(ctx0, model.output, cur);
  6172. cb(cur, "result_output", -1);
  6173. ggml_build_forward_expand(gf, cur);
  6174. return gf;
  6175. }
  6176. struct ggml_cgraph * build_persimmon() {
  6177. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6178. const int64_t n_embd_head = hparams.n_embd_head_v;
  6179. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6180. GGML_ASSERT(n_embd_head/2 == hparams.n_rot);
  6181. struct ggml_tensor * cur;
  6182. struct ggml_tensor * inpL;
  6183. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6184. // inp_pos - contains the positions
  6185. struct ggml_tensor * inp_pos = build_inp_pos();
  6186. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6187. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6188. for (int il = 0; il < n_layer; ++il) {
  6189. struct ggml_tensor * residual = inpL;
  6190. cur = llm_build_norm(ctx0, inpL, hparams,
  6191. model.layers[il].attn_norm,
  6192. model.layers[il].attn_norm_b,
  6193. LLM_NORM, cb, il);
  6194. cb(cur, "attn_norm", il);
  6195. // self attention
  6196. {
  6197. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6198. cb(cur, "wqkv", il);
  6199. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6200. cb(cur, "bqkv", il);
  6201. // split qkv
  6202. GGML_ASSERT(n_head_kv == n_head);
  6203. struct ggml_tensor * tmpqkv = ggml_reshape_4d(ctx0, cur, n_embd_head, 3, n_head, n_tokens);
  6204. cb(tmpqkv, "tmpqkv", il);
  6205. struct ggml_tensor * tmpqkv_perm = ggml_cont(ctx0, ggml_permute(ctx0, tmpqkv, 0, 3, 1, 2));
  6206. cb(tmpqkv_perm, "tmpqkv", il);
  6207. struct ggml_tensor * tmpq = ggml_view_3d(
  6208. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  6209. ggml_element_size(tmpqkv_perm) * n_embd_head,
  6210. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  6211. 0
  6212. );
  6213. cb(tmpq, "tmpq", il);
  6214. struct ggml_tensor * tmpk = ggml_view_3d(
  6215. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  6216. ggml_element_size(tmpqkv_perm) * n_embd_head,
  6217. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  6218. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens
  6219. );
  6220. cb(tmpk, "tmpk", il);
  6221. // Q/K Layernorm
  6222. tmpq = llm_build_norm(ctx0, tmpq, hparams,
  6223. model.layers[il].attn_q_norm,
  6224. model.layers[il].attn_q_norm_b,
  6225. LLM_NORM, cb, il);
  6226. cb(tmpq, "tmpq", il);
  6227. tmpk = llm_build_norm(ctx0, tmpk, hparams,
  6228. model.layers[il].attn_k_norm,
  6229. model.layers[il].attn_k_norm_b,
  6230. LLM_NORM, cb, il);
  6231. cb(tmpk, "tmpk", il);
  6232. // RoPE the first n_rot of q/k, pass the other half, and concat.
  6233. struct ggml_tensor * qrot = ggml_view_3d(
  6234. ctx0, tmpq, n_rot, n_head, n_tokens,
  6235. ggml_element_size(tmpq) * n_embd_head,
  6236. ggml_element_size(tmpq) * n_embd_head * n_head,
  6237. 0
  6238. );
  6239. cb(qrot, "qrot", il);
  6240. struct ggml_tensor * krot = ggml_view_3d(
  6241. ctx0, tmpk, n_rot, n_head, n_tokens,
  6242. ggml_element_size(tmpk) * n_embd_head,
  6243. ggml_element_size(tmpk) * n_embd_head * n_head,
  6244. 0
  6245. );
  6246. cb(krot, "krot", il);
  6247. // get the second half of tmpq, e.g tmpq[n_rot:, :, :]
  6248. struct ggml_tensor * qpass = ggml_view_3d(
  6249. ctx0, tmpq, n_rot, n_head, n_tokens,
  6250. ggml_element_size(tmpq) * n_embd_head,
  6251. ggml_element_size(tmpq) * n_embd_head * n_head,
  6252. ggml_element_size(tmpq) * n_rot
  6253. );
  6254. cb(qpass, "qpass", il);
  6255. struct ggml_tensor * kpass = ggml_view_3d(
  6256. ctx0, tmpk, n_rot, n_head, n_tokens,
  6257. ggml_element_size(tmpk) * n_embd_head,
  6258. ggml_element_size(tmpk) * n_embd_head * n_head,
  6259. ggml_element_size(tmpk) * n_rot
  6260. );
  6261. cb(kpass, "kpass", il);
  6262. struct ggml_tensor * qrotated = ggml_rope_custom(
  6263. ctx0, qrot, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  6264. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  6265. );
  6266. cb(qrotated, "qrotated", il);
  6267. struct ggml_tensor * krotated = ggml_rope_custom(
  6268. ctx0, krot, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  6269. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  6270. );
  6271. cb(krotated, "krotated", il);
  6272. // ggml currently only supports concatenation on dim=2
  6273. // so we need to permute qrot, qpass, concat, then permute back.
  6274. qrotated = ggml_cont(ctx0, ggml_permute(ctx0, qrotated, 2, 1, 0, 3));
  6275. cb(qrotated, "qrotated", il);
  6276. krotated = ggml_cont(ctx0, ggml_permute(ctx0, krotated, 2, 1, 0, 3));
  6277. cb(krotated, "krotated", il);
  6278. qpass = ggml_cont(ctx0, ggml_permute(ctx0, qpass, 2, 1, 0, 3));
  6279. cb(qpass, "qpass", il);
  6280. kpass = ggml_cont(ctx0, ggml_permute(ctx0, kpass, 2, 1, 0, 3));
  6281. cb(kpass, "kpass", il);
  6282. struct ggml_tensor * Qcur = ggml_concat(ctx0, qrotated, qpass);
  6283. cb(Qcur, "Qcur", il);
  6284. struct ggml_tensor * Kcur = ggml_concat(ctx0, krotated, kpass);
  6285. cb(Kcur, "Kcur", il);
  6286. struct ggml_tensor * Q = ggml_cont(ctx0, ggml_permute(ctx0, Qcur, 2, 1, 0, 3));
  6287. cb(Q, "Q", il);
  6288. Kcur = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 2, 1, 0, 3));
  6289. cb(Kcur, "Kcur", il);
  6290. struct ggml_tensor * Vcur = ggml_view_3d(
  6291. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  6292. ggml_element_size(tmpqkv_perm) * n_embd_head,
  6293. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  6294. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens * 2
  6295. );
  6296. cb(Vcur, "Vcur", il);
  6297. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6298. model.layers[il].wo, model.layers[il].bo,
  6299. Kcur, Vcur, Q, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6300. }
  6301. if (il == n_layer - 1) {
  6302. // skip computing output for unused tokens
  6303. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6304. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6305. residual = ggml_get_rows(ctx0, residual, inp_out_ids);
  6306. }
  6307. struct ggml_tensor * ffn_inp = ggml_add(ctx0, residual, cur);
  6308. cb(ffn_inp, "ffn_inp", il);
  6309. // feed-forward network
  6310. {
  6311. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6312. model.layers[il].ffn_norm,
  6313. model.layers[il].ffn_norm_b,
  6314. LLM_NORM, cb, il);
  6315. cb(cur, "ffn_norm", il);
  6316. cur = llm_build_ffn(ctx0, cur,
  6317. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6318. NULL, NULL,
  6319. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6320. NULL,
  6321. LLM_FFN_RELU_SQR, LLM_FFN_SEQ, cb, il);
  6322. cb(cur, "ffn_out", il);
  6323. }
  6324. cur = ggml_add(ctx0, cur, ffn_inp);
  6325. cb(cur, "l_out", il);
  6326. inpL = cur;
  6327. }
  6328. cur = inpL;
  6329. cur = llm_build_norm(ctx0, cur, hparams,
  6330. model.output_norm,
  6331. model.output_norm_b,
  6332. LLM_NORM, cb, -1);
  6333. cb(cur, "result_norm", -1);
  6334. cur = ggml_mul_mat(ctx0, model.output, cur);
  6335. cb(cur, "result_output", -1);
  6336. ggml_build_forward_expand(gf, cur);
  6337. return gf;
  6338. }
  6339. struct ggml_cgraph * build_refact() {
  6340. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6341. const int64_t n_embd_head = hparams.n_embd_head_v;
  6342. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6343. struct ggml_tensor * cur;
  6344. struct ggml_tensor * inpL;
  6345. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6346. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6347. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6348. // positions of the tokens in the KV cache
  6349. struct ggml_tensor * KQ_pos = build_inp_KQ_pos();
  6350. for (int il = 0; il < n_layer; ++il) {
  6351. struct ggml_tensor * inpSA = inpL;
  6352. cur = llm_build_norm(ctx0, inpL, hparams,
  6353. model.layers[il].attn_norm, NULL,
  6354. LLM_NORM_RMS, cb, il);
  6355. cb(cur, "attn_norm", il);
  6356. // self-attention
  6357. {
  6358. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6359. cb(Qcur, "Qcur", il);
  6360. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6361. cb(Kcur, "Kcur", il);
  6362. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6363. cb(Vcur, "Vcur", il);
  6364. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  6365. cb(Kcur, "Kcur", il);
  6366. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6367. cb(Qcur, "Qcur", il);
  6368. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6369. model.layers[il].wo, NULL,
  6370. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6371. }
  6372. if (il == n_layer - 1) {
  6373. // skip computing output for unused tokens
  6374. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6375. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6376. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  6377. }
  6378. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6379. cb(ffn_inp, "ffn_inp", il);
  6380. // feed-forward network
  6381. {
  6382. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6383. model.layers[il].ffn_norm, NULL,
  6384. LLM_NORM_RMS, cb, il);
  6385. cb(cur, "ffn_norm", il);
  6386. cur = llm_build_ffn(ctx0, cur,
  6387. model.layers[il].ffn_up, NULL,
  6388. model.layers[il].ffn_gate, NULL,
  6389. model.layers[il].ffn_down, NULL,
  6390. NULL,
  6391. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6392. cb(cur, "ffn_out", il);
  6393. }
  6394. cur = ggml_add(ctx0, cur, ffn_inp);
  6395. cb(cur, "l_out", il);
  6396. // input for next layer
  6397. inpL = cur;
  6398. }
  6399. cur = inpL;
  6400. cur = llm_build_norm(ctx0, cur, hparams,
  6401. model.output_norm, NULL,
  6402. LLM_NORM_RMS, cb, -1);
  6403. cb(cur, "result_norm", -1);
  6404. // lm_head
  6405. cur = ggml_mul_mat(ctx0, model.output, cur);
  6406. cb(cur, "result_output", -1);
  6407. ggml_build_forward_expand(gf, cur);
  6408. return gf;
  6409. }
  6410. struct ggml_cgraph * build_bert() {
  6411. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6412. const int64_t n_embd_head = hparams.n_embd_head_v;
  6413. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  6414. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6415. struct ggml_tensor * cur;
  6416. struct ggml_tensor * inpL;
  6417. struct ggml_tensor * inp_pos = build_inp_pos();
  6418. struct ggml_tensor * inp_mean = build_inp_mean();
  6419. struct ggml_tensor * inp_cls = build_inp_cls();
  6420. // construct input embeddings (token, type, position)
  6421. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6422. // token types are hardcoded to zero ("Sentence A")
  6423. struct ggml_tensor * type_row0 = ggml_view_1d(ctx0, model.type_embd, n_embd, 0);
  6424. inpL = ggml_add(ctx0, inpL, type_row0);
  6425. if (model.arch == LLM_ARCH_BERT) {
  6426. inpL = ggml_add(ctx0, ggml_get_rows(ctx0, model.pos_embd, inp_pos), inpL);
  6427. }
  6428. cb(inpL, "inp_embd", -1);
  6429. // embed layer norm
  6430. inpL = llm_build_norm(ctx0, inpL, hparams, model.tok_norm, model.tok_norm_b, LLM_NORM, cb, -1);
  6431. cb(inpL, "inp_norm", -1);
  6432. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6433. struct ggml_tensor * KQ_mask = build_inp_KQ_mask(false);
  6434. // iterate layers
  6435. for (int il = 0; il < n_layer; ++il) {
  6436. struct ggml_tensor * cur = inpL;
  6437. struct ggml_tensor * Qcur;
  6438. struct ggml_tensor * Kcur;
  6439. struct ggml_tensor * Vcur;
  6440. // self-attention
  6441. if (model.arch == LLM_ARCH_BERT) {
  6442. Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, cur), model.layers[il].bq);
  6443. cb(Qcur, "Qcur", il);
  6444. Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, cur), model.layers[il].bk);
  6445. cb(Kcur, "Kcur", il);
  6446. Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, cur), model.layers[il].bv);
  6447. cb(Vcur, "Vcur", il);
  6448. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6449. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  6450. } else {
  6451. // compute Q and K and RoPE them
  6452. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6453. cb(cur, "wqkv", il);
  6454. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6455. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  6456. 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)));
  6457. cb(Qcur, "Qcur", il);
  6458. cb(Kcur, "Kcur", il);
  6459. cb(Vcur, "Vcur", il);
  6460. Qcur = ggml_rope_custom(
  6461. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6462. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6463. ext_factor, attn_factor, beta_fast, beta_slow
  6464. );
  6465. cb(Qcur, "Qcur", il);
  6466. Kcur = ggml_rope_custom(
  6467. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6468. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6469. ext_factor, attn_factor, beta_fast, beta_slow
  6470. );
  6471. cb(Kcur, "Kcur", il);
  6472. }
  6473. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  6474. struct ggml_tensor * k = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 0, 2, 1, 3));
  6475. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  6476. cb(kq, "kq", il);
  6477. kq = ggml_soft_max_ext(ctx0, kq, KQ_mask, nullptr, 1.0f/sqrtf(float(n_embd_head)), hparams.f_max_alibi_bias);
  6478. cb(kq, "kq_soft_max_ext", il);
  6479. struct ggml_tensor * v = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_reshape_2d(ctx0, Vcur, n_embd_gqa, n_tokens)));
  6480. cb(v, "v", il);
  6481. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, ggml_reshape_3d(ctx0, v, n_tokens, n_embd_head, n_head_kv), kq);
  6482. cb(kqv, "kqv", il);
  6483. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  6484. cb(kqv_merged, "kqv_merged", il);
  6485. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  6486. cb(cur, "kqv_merged_cont", il);
  6487. ggml_build_forward_expand(gf, cur);
  6488. cur = ggml_mul_mat(ctx0, model.layers[il].wo, cur);
  6489. if (model.layers[il].bo) {
  6490. cb(cur, "kqv_wo", il);
  6491. }
  6492. if (model.layers[il].bo) {
  6493. cur = ggml_add(ctx0, cur, model.layers[il].bo);
  6494. }
  6495. cb(cur, "kqv_out", il);
  6496. if (il == n_layer - 1 && pooling_type == LLAMA_POOLING_TYPE_NONE) {
  6497. // skip computing output for unused tokens
  6498. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6499. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6500. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  6501. }
  6502. // re-add the layer input
  6503. cur = ggml_add(ctx0, cur, inpL);
  6504. // attention layer norm
  6505. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].attn_out_norm, model.layers[il].attn_out_norm_b, LLM_NORM, cb, il);
  6506. struct ggml_tensor * ffn_inp = cur;
  6507. cb(ffn_inp, "ffn_inp", il);
  6508. // feed-forward network
  6509. if (model.arch == LLM_ARCH_BERT) {
  6510. cur = llm_build_ffn(ctx0, cur,
  6511. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6512. NULL, NULL,
  6513. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6514. NULL,
  6515. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6516. } else {
  6517. cur = llm_build_ffn(ctx0, cur,
  6518. model.layers[il].ffn_up, NULL,
  6519. model.layers[il].ffn_gate, NULL,
  6520. model.layers[il].ffn_down, NULL,
  6521. NULL,
  6522. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6523. }
  6524. cb(cur, "ffn_out", il);
  6525. // attentions bypass the intermediate layer
  6526. cur = ggml_add(ctx0, cur, ffn_inp);
  6527. // output layer norm
  6528. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].layer_out_norm, model.layers[il].layer_out_norm_b, LLM_NORM, cb, il);
  6529. // input for next layer
  6530. inpL = cur;
  6531. }
  6532. // final output
  6533. cur = inpL;
  6534. cb(cur, "result_embd", -1);
  6535. // pooling layer
  6536. switch (pooling_type) {
  6537. case LLAMA_POOLING_TYPE_NONE:
  6538. {
  6539. // nop
  6540. } break;
  6541. case LLAMA_POOLING_TYPE_MEAN:
  6542. {
  6543. cur = ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, cur)), inp_mean);
  6544. cb(cur, "result_embd_pooled", -1);
  6545. } break;
  6546. case LLAMA_POOLING_TYPE_CLS:
  6547. {
  6548. cur = ggml_get_rows(ctx0, cur, inp_cls);
  6549. cb(cur, "result_embd_pooled", -1);
  6550. } break;
  6551. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  6552. {
  6553. GGML_ASSERT(false && "Invalid pooling type");
  6554. } break;
  6555. }
  6556. ggml_build_forward_expand(gf, cur);
  6557. return gf;
  6558. }
  6559. struct ggml_cgraph * build_bloom() {
  6560. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6561. const int64_t n_embd_head = hparams.n_embd_head_v;
  6562. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  6563. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6564. struct ggml_tensor * cur;
  6565. struct ggml_tensor * inpL;
  6566. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6567. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6568. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6569. // positions of the tokens in the KV cache
  6570. struct ggml_tensor * KQ_pos = build_inp_KQ_pos();
  6571. inpL = llm_build_norm(ctx0, inpL, hparams,
  6572. model.tok_norm,
  6573. model.tok_norm_b,
  6574. LLM_NORM, cb, -1);
  6575. cb(inpL, "inp_norm", -1);
  6576. for (int il = 0; il < n_layer; ++il) {
  6577. cur = llm_build_norm(ctx0, inpL, hparams,
  6578. model.layers[il].attn_norm,
  6579. model.layers[il].attn_norm_b,
  6580. LLM_NORM, cb, il);
  6581. cb(cur, "attn_norm", il);
  6582. // self-attention
  6583. {
  6584. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6585. cb(cur, "wqkv", il);
  6586. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6587. cb(cur, "bqkv", il);
  6588. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6589. 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)));
  6590. 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)));
  6591. cb(Qcur, "Qcur", il);
  6592. cb(Kcur, "Kcur", il);
  6593. cb(Vcur, "Vcur", il);
  6594. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6595. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6596. model.layers[il].wo, model.layers[il].bo,
  6597. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6598. }
  6599. if (il == n_layer - 1) {
  6600. // skip computing output for unused tokens
  6601. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6602. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6603. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  6604. }
  6605. // Add the input
  6606. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  6607. cb(ffn_inp, "ffn_inp", il);
  6608. // FF
  6609. {
  6610. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6611. model.layers[il].ffn_norm,
  6612. model.layers[il].ffn_norm_b,
  6613. LLM_NORM, cb, il);
  6614. cb(cur, "ffn_norm", il);
  6615. cur = llm_build_ffn(ctx0, cur,
  6616. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6617. NULL, NULL,
  6618. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6619. NULL,
  6620. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6621. cb(cur, "ffn_out", il);
  6622. }
  6623. inpL = ggml_add(ctx0, cur, ffn_inp);
  6624. cb(inpL, "l_out", il);
  6625. }
  6626. cur = llm_build_norm(ctx0, inpL, hparams,
  6627. model.output_norm,
  6628. model.output_norm_b,
  6629. LLM_NORM, cb, -1);
  6630. cb(cur, "result_norm", -1);
  6631. cur = ggml_mul_mat(ctx0, model.output, cur);
  6632. cb(cur, "result_output", -1);
  6633. ggml_build_forward_expand(gf, cur);
  6634. return gf;
  6635. }
  6636. struct ggml_cgraph * build_mpt() {
  6637. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6638. const int64_t n_embd_head = hparams.n_embd_head_v;
  6639. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  6640. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6641. struct ggml_tensor * cur;
  6642. struct ggml_tensor * pos;
  6643. struct ggml_tensor * inpL;
  6644. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6645. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6646. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6647. // positions of the tokens in the KV cache
  6648. struct ggml_tensor * KQ_pos = build_inp_KQ_pos();
  6649. if (model.pos_embd) {
  6650. // inp_pos - contains the positions
  6651. struct ggml_tensor * inp_pos = build_inp_pos();
  6652. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  6653. cb(pos, "pos_embd", -1);
  6654. inpL = ggml_add(ctx0, inpL, pos);
  6655. cb(inpL, "inpL", -1);
  6656. }
  6657. for (int il = 0; il < n_layer; ++il) {
  6658. struct ggml_tensor * attn_norm;
  6659. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  6660. model.layers[il].attn_norm,
  6661. model.layers[il].attn_norm_b,
  6662. LLM_NORM, cb, il);
  6663. cb(attn_norm, "attn_norm", il);
  6664. // self-attention
  6665. {
  6666. cur = attn_norm;
  6667. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6668. cb(cur, "wqkv", il);
  6669. if (model.layers[il].bqkv){
  6670. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6671. cb(cur, "bqkv", il);
  6672. }
  6673. if (hparams.f_clamp_kqv > 0.0f) {
  6674. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  6675. cb(cur, "wqkv_clamped", il);
  6676. }
  6677. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6678. 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)));
  6679. 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)));
  6680. cb(Qcur, "Qcur", il);
  6681. cb(Kcur, "Kcur", il);
  6682. cb(Vcur, "Vcur", il);
  6683. // Q/K Layernorm
  6684. if (model.layers[il].attn_q_norm) {
  6685. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  6686. model.layers[il].attn_q_norm,
  6687. model.layers[il].attn_q_norm_b,
  6688. LLM_NORM, cb, il);
  6689. cb(Qcur, "Qcur", il);
  6690. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  6691. model.layers[il].attn_k_norm,
  6692. model.layers[il].attn_k_norm_b,
  6693. LLM_NORM, cb, il);
  6694. cb(Kcur, "Kcur", il);
  6695. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6696. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  6697. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6698. model.layers[il].wo, model.layers[il].bo,
  6699. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6700. } else {
  6701. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6702. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6703. model.layers[il].wo, model.layers[il].bo,
  6704. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6705. }
  6706. }
  6707. if (il == n_layer - 1) {
  6708. // skip computing output for unused tokens
  6709. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6710. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6711. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  6712. }
  6713. // Add the input
  6714. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  6715. cb(ffn_inp, "ffn_inp", il);
  6716. // feed forward
  6717. {
  6718. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6719. model.layers[il].ffn_norm,
  6720. model.layers[il].ffn_norm_b,
  6721. LLM_NORM, cb, il);
  6722. cb(cur, "ffn_norm", il);
  6723. cur = llm_build_ffn(ctx0, cur,
  6724. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6725. NULL, NULL,
  6726. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6727. model.layers[il].ffn_act,
  6728. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6729. cb(cur, "ffn_out", il);
  6730. }
  6731. cur = ggml_add(ctx0, cur, ffn_inp);
  6732. cb(cur, "l_out", il);
  6733. // input for next layer
  6734. inpL = cur;
  6735. }
  6736. cur = inpL;
  6737. cur = llm_build_norm(ctx0, cur, hparams,
  6738. model.output_norm,
  6739. model.output_norm_b,
  6740. LLM_NORM, cb, -1);
  6741. cb(cur, "result_norm", -1);
  6742. cur = ggml_mul_mat(ctx0, model.output, cur);
  6743. cb(cur, "result_output", -1);
  6744. ggml_build_forward_expand(gf, cur);
  6745. return gf;
  6746. }
  6747. struct ggml_cgraph * build_stablelm() {
  6748. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  6749. const int64_t n_embd_head = hparams.n_embd_head_v;
  6750. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6751. struct ggml_tensor * cur;
  6752. struct ggml_tensor * inpL;
  6753. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6754. // inp_pos - contains the positions
  6755. struct ggml_tensor * inp_pos = build_inp_pos();
  6756. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6757. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6758. for (int il = 0; il < n_layer; ++il) {
  6759. struct ggml_tensor * inpSA = inpL;
  6760. // norm
  6761. cur = llm_build_norm(ctx0, inpL, hparams,
  6762. model.layers[il].attn_norm,
  6763. model.layers[il].attn_norm_b,
  6764. LLM_NORM, cb, il);
  6765. cb(cur, "attn_norm", il);
  6766. // self-attention
  6767. {
  6768. // compute Q and K and RoPE them
  6769. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6770. cb(Qcur, "Qcur", il);
  6771. if (model.layers[il].bq) {
  6772. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6773. cb(Qcur, "Qcur", il);
  6774. }
  6775. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6776. cb(Kcur, "Kcur", il);
  6777. if (model.layers[il].bk) {
  6778. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6779. cb(Kcur, "Kcur", il);
  6780. }
  6781. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6782. cb(Vcur, "Vcur", il);
  6783. if (model.layers[il].bv) {
  6784. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6785. cb(Vcur, "Vcur", il);
  6786. }
  6787. Qcur = ggml_rope_custom(
  6788. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6789. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6790. ext_factor, attn_factor, beta_fast, beta_slow
  6791. );
  6792. cb(Qcur, "Qcur", il);
  6793. Kcur = ggml_rope_custom(
  6794. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6795. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6796. ext_factor, attn_factor, beta_fast, beta_slow
  6797. );
  6798. cb(Kcur, "Kcur", il);
  6799. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6800. model.layers[il].wo, NULL,
  6801. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6802. }
  6803. if (il == n_layer - 1) {
  6804. // skip computing output for unused tokens
  6805. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6806. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6807. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  6808. }
  6809. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6810. cb(ffn_inp, "ffn_inp", il);
  6811. // feed-forward network
  6812. {
  6813. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6814. model.layers[il].ffn_norm,
  6815. model.layers[il].ffn_norm_b,
  6816. LLM_NORM, cb, il);
  6817. cb(cur, "ffn_norm", il);
  6818. cur = llm_build_ffn(ctx0, cur,
  6819. model.layers[il].ffn_up, NULL,
  6820. model.layers[il].ffn_gate, NULL,
  6821. model.layers[il].ffn_down, NULL,
  6822. NULL,
  6823. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6824. cb(cur, "ffn_out", il);
  6825. }
  6826. cur = ggml_add(ctx0, cur, ffn_inp);
  6827. cb(cur, "l_out", il);
  6828. // input for next layer
  6829. inpL = cur;
  6830. }
  6831. cur = inpL;
  6832. cur = llm_build_norm(ctx0, cur, hparams,
  6833. model.output_norm,
  6834. model.output_norm_b,
  6835. LLM_NORM, cb, -1);
  6836. cb(cur, "result_norm", -1);
  6837. // lm_head
  6838. cur = ggml_mul_mat(ctx0, model.output, cur);
  6839. cb(cur, "result_output", -1);
  6840. ggml_build_forward_expand(gf, cur);
  6841. return gf;
  6842. }
  6843. struct ggml_cgraph * build_qwen() {
  6844. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6845. const int64_t n_embd_head = hparams.n_embd_head_v;
  6846. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6847. struct ggml_tensor * cur;
  6848. struct ggml_tensor * inpL;
  6849. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6850. // inp_pos - contains the positions
  6851. struct ggml_tensor * inp_pos = build_inp_pos();
  6852. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6853. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6854. for (int il = 0; il < n_layer; ++il) {
  6855. struct ggml_tensor * inpSA = inpL;
  6856. cur = llm_build_norm(ctx0, inpL, hparams,
  6857. model.layers[il].attn_norm, NULL,
  6858. LLM_NORM_RMS, cb, il);
  6859. cb(cur, "attn_norm", il);
  6860. // self-attention
  6861. {
  6862. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6863. cb(cur, "wqkv", il);
  6864. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6865. cb(cur, "bqkv", il);
  6866. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6867. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  6868. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 2*sizeof(float)*(n_embd)));
  6869. cb(Qcur, "Qcur", il);
  6870. cb(Kcur, "Kcur", il);
  6871. cb(Vcur, "Vcur", il);
  6872. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6873. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  6874. // using mode = 2 for neox mode
  6875. Qcur = ggml_rope_custom(
  6876. ctx0, Qcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  6877. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  6878. );
  6879. cb(Qcur, "Qcur", il);
  6880. Kcur = ggml_rope_custom(
  6881. ctx0, Kcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  6882. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  6883. );
  6884. cb(Kcur, "Kcur", il);
  6885. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6886. model.layers[il].wo, NULL,
  6887. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6888. }
  6889. if (il == n_layer - 1) {
  6890. // skip computing output for unused tokens
  6891. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6892. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6893. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  6894. }
  6895. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6896. cb(ffn_inp, "ffn_inp", il);
  6897. // feed-forward forward
  6898. {
  6899. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6900. model.layers[il].ffn_norm, NULL,
  6901. LLM_NORM_RMS, cb, il);
  6902. cb(cur, "ffn_norm", il);
  6903. cur = llm_build_ffn(ctx0, cur,
  6904. model.layers[il].ffn_up, NULL,
  6905. model.layers[il].ffn_gate, NULL,
  6906. model.layers[il].ffn_down, NULL,
  6907. NULL,
  6908. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6909. cb(cur, "ffn_out", il);
  6910. }
  6911. cur = ggml_add(ctx0, cur, ffn_inp);
  6912. cb(cur, "l_out", il);
  6913. // input for next layer
  6914. inpL = cur;
  6915. }
  6916. cur = inpL;
  6917. cur = llm_build_norm(ctx0, cur, hparams,
  6918. model.output_norm, NULL,
  6919. LLM_NORM_RMS, cb, -1);
  6920. cb(cur, "result_norm", -1);
  6921. // lm_head
  6922. cur = ggml_mul_mat(ctx0, model.output, cur);
  6923. cb(cur, "result_output", -1);
  6924. ggml_build_forward_expand(gf, cur);
  6925. return gf;
  6926. }
  6927. struct ggml_cgraph * build_qwen2() {
  6928. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6929. const int64_t n_embd_head = hparams.n_embd_head_v;
  6930. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6931. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6932. struct ggml_tensor * cur;
  6933. struct ggml_tensor * inpL;
  6934. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6935. // inp_pos - contains the positions
  6936. struct ggml_tensor * inp_pos = build_inp_pos();
  6937. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6938. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6939. for (int il = 0; il < n_layer; ++il) {
  6940. struct ggml_tensor * inpSA = inpL;
  6941. // norm
  6942. cur = llm_build_norm(ctx0, inpL, hparams,
  6943. model.layers[il].attn_norm, NULL,
  6944. LLM_NORM_RMS, cb, il);
  6945. cb(cur, "attn_norm", il);
  6946. // self-attention
  6947. {
  6948. // compute Q and K and RoPE them
  6949. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6950. cb(Qcur, "Qcur", il);
  6951. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6952. cb(Qcur, "Qcur", il);
  6953. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6954. cb(Kcur, "Kcur", il);
  6955. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6956. cb(Kcur, "Kcur", il);
  6957. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6958. cb(Vcur, "Vcur", il);
  6959. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6960. cb(Vcur, "Vcur", il);
  6961. // these nodes are added to the graph together so that they are not reordered
  6962. // by doing so, the number of splits in the graph is reduced
  6963. ggml_build_forward_expand(gf, Qcur);
  6964. ggml_build_forward_expand(gf, Kcur);
  6965. ggml_build_forward_expand(gf, Vcur);
  6966. Qcur = ggml_rope_custom(
  6967. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6968. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6969. ext_factor, attn_factor, beta_fast, beta_slow
  6970. );
  6971. cb(Qcur, "Qcur", il);
  6972. Kcur = ggml_rope_custom(
  6973. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6974. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6975. ext_factor, attn_factor, beta_fast, beta_slow
  6976. );
  6977. cb(Kcur, "Kcur", il);
  6978. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6979. model.layers[il].wo, model.layers[il].bo,
  6980. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6981. }
  6982. if (il == n_layer - 1) {
  6983. // skip computing output for unused tokens
  6984. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6985. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6986. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  6987. }
  6988. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6989. cb(ffn_inp, "ffn_inp", il);
  6990. // feed-forward network
  6991. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6992. model.layers[il].ffn_norm, NULL,
  6993. LLM_NORM_RMS, cb, il);
  6994. cb(cur, "ffn_norm", il);
  6995. cur = llm_build_ffn(ctx0, cur,
  6996. model.layers[il].ffn_up, NULL,
  6997. model.layers[il].ffn_gate, NULL,
  6998. model.layers[il].ffn_down, NULL,
  6999. NULL,
  7000. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  7001. cb(cur, "ffn_out", il);
  7002. cur = ggml_add(ctx0, cur, ffn_inp);
  7003. cb(cur, "l_out", il);
  7004. // input for next layer
  7005. inpL = cur;
  7006. }
  7007. cur = inpL;
  7008. cur = llm_build_norm(ctx0, cur, hparams,
  7009. model.output_norm, NULL,
  7010. LLM_NORM_RMS, cb, -1);
  7011. cb(cur, "result_norm", -1);
  7012. // lm_head
  7013. cur = ggml_mul_mat(ctx0, model.output, cur);
  7014. cb(cur, "result_output", -1);
  7015. ggml_build_forward_expand(gf, cur);
  7016. return gf;
  7017. }
  7018. struct ggml_cgraph * build_phi2() {
  7019. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7020. const int64_t n_embd_head = hparams.n_embd_head_v;
  7021. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  7022. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7023. struct ggml_tensor * cur;
  7024. struct ggml_tensor * attn_norm_output;
  7025. struct ggml_tensor * ffn_output;
  7026. struct ggml_tensor * inpL;
  7027. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7028. // inp_pos - contains the positions
  7029. struct ggml_tensor * inp_pos = build_inp_pos();
  7030. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7031. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7032. for (int il = 0; il < n_layer; ++il) {
  7033. attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  7034. model.layers[il].attn_norm,
  7035. model.layers[il].attn_norm_b,
  7036. LLM_NORM, cb, il);
  7037. cb(attn_norm_output, "attn_norm", il);
  7038. // self-attention
  7039. {
  7040. struct ggml_tensor * Qcur = nullptr;
  7041. struct ggml_tensor * Kcur = nullptr;
  7042. struct ggml_tensor * Vcur = nullptr;
  7043. if (model.layers[il].wqkv) {
  7044. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, attn_norm_output);
  7045. cb(cur, "wqkv", il);
  7046. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  7047. cb(cur, "bqkv", il);
  7048. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  7049. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  7050. 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)));
  7051. } else {
  7052. Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  7053. Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  7054. Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  7055. }
  7056. cb(Qcur, "Qcur", il);
  7057. cb(Kcur, "Kcur", il);
  7058. cb(Vcur, "Vcur", il);
  7059. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  7060. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  7061. Qcur = ggml_rope_custom(
  7062. ctx0, Qcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  7063. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  7064. );
  7065. cb(Qcur, "Qcur", il);
  7066. // with phi2, we scale the Q to avoid precision issues
  7067. // ref: https://github.com/ml-explore/mlx-examples/blob/08e862336ade809bc37d1035f94b359e7d1a5152/phi2/phi2.py#L64-L66
  7068. Qcur = ggml_scale(ctx0, Qcur, 1.0f/sqrtf(float(n_embd_head)));
  7069. cb(Qcur, "Qcur", il);
  7070. Kcur = ggml_rope_custom(
  7071. ctx0, Kcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  7072. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  7073. );
  7074. cb(Kcur, "Kcur", il);
  7075. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  7076. model.layers[il].wo, model.layers[il].bo,
  7077. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  7078. }
  7079. if (il == n_layer - 1) {
  7080. // skip computing output for unused tokens
  7081. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7082. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7083. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  7084. attn_norm_output = ggml_get_rows(ctx0, attn_norm_output, inp_out_ids);
  7085. }
  7086. // FF
  7087. {
  7088. ffn_output = llm_build_ffn(ctx0, attn_norm_output,
  7089. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  7090. NULL, NULL,
  7091. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  7092. NULL,
  7093. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  7094. cb(ffn_output, "ffn_out", il);
  7095. }
  7096. cur = ggml_add(ctx0, cur, ffn_output);
  7097. cb(cur, "l_out", il);
  7098. cur = ggml_add(ctx0, cur, inpL);
  7099. cb(cur, "l_out", il);
  7100. inpL = cur;
  7101. }
  7102. cur = llm_build_norm(ctx0, inpL, hparams,
  7103. model.output_norm,
  7104. model.output_norm_b,
  7105. LLM_NORM, cb, -1);
  7106. cb(cur, "result_norm", -1);
  7107. cur = ggml_mul_mat(ctx0, model.output, cur);
  7108. cb(cur, "result_output_no_bias", -1);
  7109. cur = ggml_add(ctx0, cur, model.output_b);
  7110. cb(cur, "result_output", -1);
  7111. ggml_build_forward_expand(gf, cur);
  7112. return gf;
  7113. }
  7114. struct ggml_cgraph * build_plamo() {
  7115. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  7116. const int64_t n_embd_head = hparams.n_embd_head_v;
  7117. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7118. GGML_ASSERT(n_embd_head == hparams.n_rot);
  7119. struct ggml_tensor * cur;
  7120. struct ggml_tensor * inpL;
  7121. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7122. // inp_pos - contains the positions
  7123. struct ggml_tensor * inp_pos = build_inp_pos();
  7124. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7125. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7126. for (int il = 0; il < n_layer; ++il) {
  7127. // norm
  7128. cur = llm_build_norm(ctx0, inpL, hparams,
  7129. model.layers[il].attn_norm, NULL,
  7130. LLM_NORM_RMS, cb, il);
  7131. cb(cur, "attn_norm", il);
  7132. struct ggml_tensor * attention_norm = cur;
  7133. // self-attention
  7134. {
  7135. // compute Q and K and RoPE them
  7136. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  7137. cb(Qcur, "Qcur", il);
  7138. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  7139. cb(Kcur, "Kcur", il);
  7140. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  7141. cb(Vcur, "Vcur", il);
  7142. Qcur = ggml_rope_custom(
  7143. ctx0, ggml_reshape_3d(ctx0, Qcur, n_rot, n_head, n_tokens), inp_pos,
  7144. n_embd_head, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7145. ext_factor, attn_factor, beta_fast, beta_slow);
  7146. cb(Qcur, "Qcur", il);
  7147. Kcur = ggml_rope_custom(
  7148. ctx0, ggml_reshape_3d(ctx0, Kcur, n_rot, n_head_kv, n_tokens), inp_pos,
  7149. n_embd_head, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7150. ext_factor, attn_factor, beta_fast, beta_slow);
  7151. cb(Kcur, "Kcur", il);
  7152. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  7153. model.layers[il].wo, NULL,
  7154. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7155. }
  7156. struct ggml_tensor * sa_out = cur;
  7157. cur = attention_norm;
  7158. if (il == n_layer - 1) {
  7159. // skip computing output for unused tokens
  7160. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7161. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7162. sa_out = ggml_get_rows(ctx0, sa_out, inp_out_ids);
  7163. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  7164. }
  7165. // feed-forward network
  7166. {
  7167. cur = llm_build_ffn(ctx0, cur,
  7168. model.layers[il].ffn_up, NULL,
  7169. model.layers[il].ffn_gate, NULL,
  7170. model.layers[il].ffn_down, NULL,
  7171. NULL,
  7172. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  7173. cb(cur, "ffn_out", il);
  7174. }
  7175. cur = ggml_add(ctx0, cur, sa_out);
  7176. cb(cur, "l_out", il);
  7177. cur = ggml_add(ctx0, cur, inpL);
  7178. cb(cur, "l_out", il);
  7179. // input for next layer
  7180. inpL = cur;
  7181. }
  7182. cur = inpL;
  7183. cur = llm_build_norm(ctx0, cur, hparams,
  7184. model.output_norm, NULL,
  7185. LLM_NORM_RMS, cb, -1);
  7186. cb(cur, "result_norm", -1);
  7187. // lm_head
  7188. cur = ggml_mul_mat(ctx0, model.output, cur);
  7189. cb(cur, "result_output", -1);
  7190. ggml_build_forward_expand(gf, cur);
  7191. return gf;
  7192. }
  7193. struct ggml_cgraph * build_gpt2() {
  7194. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7195. const int64_t n_embd_head = hparams.n_embd_head_v;
  7196. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  7197. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7198. struct ggml_tensor * cur;
  7199. struct ggml_tensor * pos;
  7200. struct ggml_tensor * inpL;
  7201. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7202. // inp_pos - contains the positions
  7203. struct ggml_tensor * inp_pos = build_inp_pos();
  7204. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7205. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7206. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  7207. cb(pos, "pos_embd", -1);
  7208. inpL = ggml_add(ctx0, inpL, pos);
  7209. cb(inpL, "inpL", -1);
  7210. for (int il = 0; il < n_layer; ++il) {
  7211. cur = llm_build_norm(ctx0, inpL, hparams,
  7212. model.layers[il].attn_norm,
  7213. model.layers[il].attn_norm_b,
  7214. LLM_NORM, cb, il);
  7215. cb(cur, "attn_norm", il);
  7216. // self-attention
  7217. {
  7218. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  7219. cb(cur, "wqkv", il);
  7220. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  7221. cb(cur, "bqkv", il);
  7222. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  7223. 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)));
  7224. 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)));
  7225. cb(Qcur, "Qcur", il);
  7226. cb(Kcur, "Kcur", il);
  7227. cb(Vcur, "Vcur", il);
  7228. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  7229. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  7230. model.layers[il].wo, model.layers[il].bo,
  7231. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7232. }
  7233. if (il == n_layer - 1) {
  7234. // skip computing output for unused tokens
  7235. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7236. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7237. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  7238. }
  7239. // add the input
  7240. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  7241. cb(ffn_inp, "ffn_inp", il);
  7242. // FF
  7243. {
  7244. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7245. model.layers[il].ffn_norm,
  7246. model.layers[il].ffn_norm_b,
  7247. LLM_NORM, cb, il);
  7248. cb(cur, "ffn_norm", il);
  7249. cur = llm_build_ffn(ctx0, cur,
  7250. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  7251. NULL, NULL,
  7252. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  7253. NULL,
  7254. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  7255. cb(cur, "ffn_out", il);
  7256. }
  7257. inpL = ggml_add(ctx0, cur, ffn_inp);
  7258. cb(inpL, "l_out", il);
  7259. }
  7260. cur = llm_build_norm(ctx0, inpL, hparams,
  7261. model.output_norm,
  7262. model.output_norm_b,
  7263. LLM_NORM, cb, -1);
  7264. cb(cur, "result_norm", -1);
  7265. cur = ggml_mul_mat(ctx0, model.output, cur);
  7266. cb(cur, "result_output", -1);
  7267. ggml_build_forward_expand(gf, cur);
  7268. return gf;
  7269. }
  7270. struct ggml_cgraph * build_codeshell() {
  7271. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7272. const int64_t n_embd_head = hparams.n_embd_head_v;
  7273. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  7274. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7275. GGML_ASSERT(n_embd_head == hparams.n_rot);
  7276. struct ggml_tensor * cur;
  7277. struct ggml_tensor * inpL;
  7278. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7279. // inp_pos - contains the positions
  7280. struct ggml_tensor * inp_pos = build_inp_pos();
  7281. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7282. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7283. for (int il = 0; il < n_layer; ++il) {
  7284. cur = llm_build_norm(ctx0, inpL, hparams,
  7285. model.layers[il].attn_norm,
  7286. model.layers[il].attn_norm_b,
  7287. LLM_NORM, cb, il);
  7288. cb(cur, "attn_norm", il);
  7289. // self-attention
  7290. {
  7291. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  7292. cb(cur, "wqkv", il);
  7293. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  7294. cb(cur, "bqkv", il);
  7295. struct ggml_tensor * tmpq = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  7296. 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)));
  7297. 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)));
  7298. cb(tmpq, "tmpq", il);
  7299. cb(tmpk, "tmpk", il);
  7300. cb(Vcur, "Vcur", il);
  7301. struct ggml_tensor * Qcur = ggml_rope_custom(
  7302. ctx0, ggml_reshape_3d(ctx0, tmpq, n_embd_head, n_head, n_tokens), inp_pos,
  7303. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7304. ext_factor, attn_factor, beta_fast, beta_slow
  7305. );
  7306. cb(Qcur, "Qcur", il);
  7307. struct ggml_tensor * Kcur = ggml_rope_custom(
  7308. ctx0, ggml_reshape_3d(ctx0, tmpk, n_embd_head, n_head_kv, n_tokens), inp_pos,
  7309. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7310. ext_factor, attn_factor, beta_fast, beta_slow
  7311. );
  7312. cb(Kcur, "Kcur", il);
  7313. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  7314. model.layers[il].wo, model.layers[il].bo,
  7315. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7316. }
  7317. if (il == n_layer - 1) {
  7318. // skip computing output for unused tokens
  7319. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7320. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7321. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  7322. }
  7323. // add the input
  7324. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  7325. cb(ffn_inp, "ffn_inp", il);
  7326. // FF
  7327. {
  7328. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7329. model.layers[il].ffn_norm,
  7330. model.layers[il].ffn_norm_b,
  7331. LLM_NORM, cb, il);
  7332. cb(cur, "ffn_norm", il);
  7333. cur = llm_build_ffn(ctx0, cur,
  7334. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  7335. NULL, NULL,
  7336. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  7337. NULL,
  7338. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  7339. cb(cur, "ffn_out", il);
  7340. }
  7341. inpL = ggml_add(ctx0, cur, ffn_inp);
  7342. cb(inpL, "l_out", il);
  7343. }
  7344. cur = llm_build_norm(ctx0, inpL, hparams,
  7345. model.output_norm,
  7346. model.output_norm_b,
  7347. LLM_NORM, cb, -1);
  7348. cb(cur, "result_norm", -1);
  7349. cur = ggml_mul_mat(ctx0, model.output, cur);
  7350. cb(cur, "result_output", -1);
  7351. ggml_build_forward_expand(gf, cur);
  7352. return gf;
  7353. }
  7354. struct ggml_cgraph * build_orion() {
  7355. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7356. const int64_t n_embd_head = hparams.n_embd_head_v;
  7357. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7358. GGML_ASSERT(n_embd_head == hparams.n_rot);
  7359. struct ggml_tensor * cur;
  7360. struct ggml_tensor * inpL;
  7361. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7362. // inp_pos - contains the positions
  7363. struct ggml_tensor * inp_pos = build_inp_pos();
  7364. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7365. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7366. for (int il = 0; il < n_layer; ++il) {
  7367. struct ggml_tensor * inpSA = inpL;
  7368. // norm
  7369. cur = llm_build_norm(ctx0, inpL, hparams,
  7370. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  7371. LLM_NORM, cb, il);
  7372. cb(cur, "attn_norm", il);
  7373. // self-attention
  7374. {
  7375. // compute Q and K and RoPE them
  7376. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  7377. cb(Qcur, "Qcur", il);
  7378. // if (model.layers[il].bq) {
  7379. // Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  7380. // cb(Qcur, "Qcur", il);
  7381. // }
  7382. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  7383. cb(Kcur, "Kcur", il);
  7384. // if (model.layers[il].bk) {
  7385. // Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  7386. // cb(Kcur, "Kcur", il);
  7387. // }
  7388. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  7389. cb(Vcur, "Vcur", il);
  7390. // if (model.layers[il].bv) {
  7391. // Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  7392. // cb(Vcur, "Vcur", il);
  7393. // }
  7394. Qcur = ggml_rope_custom(
  7395. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  7396. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7397. ext_factor, attn_factor, beta_fast, beta_slow
  7398. );
  7399. cb(Qcur, "Qcur", il);
  7400. Kcur = ggml_rope_custom(
  7401. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  7402. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7403. ext_factor, attn_factor, beta_fast, beta_slow
  7404. );
  7405. cb(Kcur, "Kcur", il);
  7406. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  7407. model.layers[il].wo, NULL,
  7408. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7409. }
  7410. if (il == n_layer - 1) {
  7411. // skip computing output for unused tokens
  7412. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7413. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7414. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  7415. }
  7416. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  7417. cb(ffn_inp, "ffn_inp", il);
  7418. // feed-forward network
  7419. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7420. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  7421. LLM_NORM, cb, il);
  7422. cb(cur, "ffn_norm", il);
  7423. cur = llm_build_ffn(ctx0, cur,
  7424. model.layers[il].ffn_up, NULL,
  7425. model.layers[il].ffn_gate, NULL,
  7426. model.layers[il].ffn_down, NULL,
  7427. NULL,
  7428. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  7429. cb(cur, "ffn_out", il);
  7430. cur = ggml_add(ctx0, cur, ffn_inp);
  7431. cb(cur, "l_out", il);
  7432. // input for next layer
  7433. inpL = cur;
  7434. }
  7435. cur = inpL;
  7436. cur = llm_build_norm(ctx0, cur, hparams,
  7437. model.output_norm, model.output_norm_b,
  7438. LLM_NORM, cb, -1);
  7439. cb(cur, "result_norm", -1);
  7440. // lm_head
  7441. cur = ggml_mul_mat(ctx0, model.output, cur);
  7442. cb(cur, "result_output", -1);
  7443. ggml_build_forward_expand(gf, cur);
  7444. return gf;
  7445. }
  7446. struct ggml_cgraph * build_internlm2() {
  7447. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7448. const int64_t n_embd_head = hparams.n_embd_head_v;
  7449. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7450. GGML_ASSERT(n_embd_head == hparams.n_rot);
  7451. struct ggml_tensor * cur;
  7452. struct ggml_tensor * inpL;
  7453. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7454. // inp_pos - contains the positions
  7455. struct ggml_tensor * inp_pos = build_inp_pos();
  7456. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7457. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7458. for (int il = 0; il < n_layer; ++il) {
  7459. struct ggml_tensor * inpSA = inpL;
  7460. // norm
  7461. cur = llm_build_norm(ctx0, inpL, hparams,
  7462. model.layers[il].attn_norm, NULL,
  7463. LLM_NORM_RMS, cb, il);
  7464. cb(cur, "attn_norm", il);
  7465. // self-attention
  7466. {
  7467. // compute Q and K and RoPE them
  7468. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  7469. cb(Qcur, "Qcur", il);
  7470. if (model.layers[il].bq) {
  7471. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  7472. cb(Qcur, "Qcur", il);
  7473. }
  7474. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  7475. cb(Kcur, "Kcur", il);
  7476. if (model.layers[il].bk) {
  7477. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  7478. cb(Kcur, "Kcur", il);
  7479. }
  7480. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  7481. cb(Vcur, "Vcur", il);
  7482. if (model.layers[il].bv) {
  7483. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  7484. cb(Vcur, "Vcur", il);
  7485. }
  7486. Qcur = ggml_rope_custom(
  7487. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  7488. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7489. ext_factor, attn_factor, beta_fast, beta_slow
  7490. );
  7491. cb(Qcur, "Qcur", il);
  7492. Kcur = ggml_rope_custom(
  7493. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  7494. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7495. ext_factor, attn_factor, beta_fast, beta_slow
  7496. );
  7497. cb(Kcur, "Kcur", il);
  7498. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  7499. model.layers[il].wo, model.layers[il].bo,
  7500. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7501. }
  7502. if (il == n_layer - 1) {
  7503. // skip computing output for unused tokens
  7504. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7505. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7506. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  7507. }
  7508. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  7509. cb(ffn_inp, "ffn_inp", il);
  7510. // feed-forward network
  7511. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7512. model.layers[il].ffn_norm, NULL,
  7513. LLM_NORM_RMS, cb, il);
  7514. cb(cur, "ffn_norm", il);
  7515. cur = llm_build_ffn(ctx0, cur,
  7516. model.layers[il].ffn_up, NULL,
  7517. model.layers[il].ffn_gate, NULL,
  7518. model.layers[il].ffn_down, NULL,
  7519. NULL,
  7520. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  7521. cb(cur, "ffn_out", il);
  7522. cur = ggml_add(ctx0, cur, ffn_inp);
  7523. cb(cur, "l_out", il);
  7524. // input for next layer
  7525. inpL = cur;
  7526. }
  7527. cur = inpL;
  7528. cur = llm_build_norm(ctx0, cur, hparams,
  7529. model.output_norm, NULL,
  7530. LLM_NORM_RMS, cb, -1);
  7531. cb(cur, "result_norm", -1);
  7532. // lm_head
  7533. cur = ggml_mul_mat(ctx0, model.output, cur);
  7534. cb(cur, "result_output", -1);
  7535. ggml_build_forward_expand(gf, cur);
  7536. return gf;
  7537. }
  7538. // ref: https://arxiv.org/abs/2203.03466
  7539. // https://github.com/ggerganov/llama.cpp/issues/5276#issuecomment-1925774738
  7540. // based on the original build_llama() function
  7541. struct ggml_cgraph * build_minicpm() {
  7542. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7543. const int64_t n_embd_head = hparams.n_embd_head_v;
  7544. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7545. GGML_ASSERT(n_embd_head == hparams.n_rot);
  7546. const int64_t n_embd = hparams.n_embd;
  7547. //TODO: if the model varies, these parameters need to be read from the model
  7548. const int64_t n_embd_base = 256;
  7549. const float scale_embd = 12.0f;
  7550. const float scale_depth = 1.4f;
  7551. struct ggml_tensor * cur;
  7552. struct ggml_tensor * inpL;
  7553. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7554. // scale the input embeddings
  7555. inpL = ggml_scale(ctx0, inpL, scale_embd);
  7556. cb(inpL, "inp_scaled", -1);
  7557. // inp_pos - contains the positions
  7558. struct ggml_tensor * inp_pos = build_inp_pos();
  7559. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7560. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7561. for (int il = 0; il < n_layer; ++il) {
  7562. struct ggml_tensor * inpSA = inpL;
  7563. // norm
  7564. cur = llm_build_norm(ctx0, inpL, hparams,
  7565. model.layers[il].attn_norm, NULL,
  7566. LLM_NORM_RMS, cb, il);
  7567. cb(cur, "attn_norm", il);
  7568. // self-attention
  7569. {
  7570. // compute Q and K and RoPE them
  7571. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  7572. cb(Qcur, "Qcur", il);
  7573. if (model.layers[il].bq) {
  7574. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  7575. cb(Qcur, "Qcur", il);
  7576. }
  7577. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  7578. cb(Kcur, "Kcur", il);
  7579. if (model.layers[il].bk) {
  7580. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  7581. cb(Kcur, "Kcur", il);
  7582. }
  7583. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  7584. cb(Vcur, "Vcur", il);
  7585. if (model.layers[il].bv) {
  7586. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  7587. cb(Vcur, "Vcur", il);
  7588. }
  7589. Qcur = ggml_rope_custom(
  7590. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  7591. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7592. ext_factor, attn_factor, beta_fast, beta_slow
  7593. );
  7594. cb(Qcur, "Qcur", il);
  7595. Kcur = ggml_rope_custom(
  7596. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  7597. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7598. ext_factor, attn_factor, beta_fast, beta_slow
  7599. );
  7600. cb(Kcur, "Kcur", il);
  7601. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  7602. model.layers[il].wo, model.layers[il].bo,
  7603. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7604. }
  7605. if (il == n_layer - 1) {
  7606. // skip computing output for unused tokens
  7607. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7608. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7609. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  7610. }
  7611. // scale_res - scale the hidden states for residual connection
  7612. const float scale_res = scale_depth/sqrtf(float(n_layer));
  7613. cur = ggml_scale(ctx0, cur, scale_res);
  7614. cb(cur, "hidden_scaled", -1);
  7615. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  7616. cb(ffn_inp, "ffn_inp", il);
  7617. // feed-forward network
  7618. {
  7619. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7620. model.layers[il].ffn_norm, NULL,
  7621. LLM_NORM_RMS, cb, il);
  7622. cb(cur, "ffn_norm", il);
  7623. cur = llm_build_ffn(ctx0, cur,
  7624. model.layers[il].ffn_up, NULL,
  7625. model.layers[il].ffn_gate, NULL,
  7626. model.layers[il].ffn_down, NULL,
  7627. NULL,
  7628. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  7629. cb(cur, "ffn_out", il);
  7630. }
  7631. // scale the hidden states for residual connection
  7632. cur = ggml_scale(ctx0, cur, scale_res);
  7633. cb(cur, "hidden_scaled_ffn", -1);
  7634. cur = ggml_add(ctx0, cur, ffn_inp);
  7635. cb(cur, "l_out", il);
  7636. // input for next layer
  7637. inpL = cur;
  7638. }
  7639. cur = inpL;
  7640. cur = llm_build_norm(ctx0, cur, hparams,
  7641. model.output_norm, NULL,
  7642. LLM_NORM_RMS, cb, -1);
  7643. cb(cur, "result_norm", -1);
  7644. // lm_head scaling
  7645. const float scale_lmhead = float(n_embd_base)/float(n_embd);
  7646. cur = ggml_scale(ctx0, cur, scale_lmhead);
  7647. cb(cur, "lmhead_scaling", -1);
  7648. // lm_head
  7649. cur = ggml_mul_mat(ctx0, model.tok_embd, cur);
  7650. cb(cur, "result_output", -1);
  7651. ggml_build_forward_expand(gf, cur);
  7652. return gf;
  7653. }
  7654. struct ggml_cgraph * build_gemma() {
  7655. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7656. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  7657. struct ggml_tensor * cur;
  7658. struct ggml_tensor * inpL;
  7659. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7660. inpL = ggml_scale(ctx0, inpL, sqrtf(n_embd));
  7661. cb(inpL, "inp_scaled", -1);
  7662. // inp_pos - contains the positions
  7663. struct ggml_tensor * inp_pos = build_inp_pos();
  7664. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7665. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7666. for (int il = 0; il < n_layer; ++il) {
  7667. // norm
  7668. cur = llm_build_norm(ctx0, inpL, hparams,
  7669. model.layers[il].attn_norm, NULL,
  7670. LLM_NORM_RMS, cb, il);
  7671. cb(cur, "attn_norm", il);
  7672. // self-attention
  7673. {
  7674. // compute Q and K and RoPE them
  7675. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  7676. cb(Qcur, "Qcur", il);
  7677. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  7678. cb(Kcur, "Kcur", il);
  7679. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  7680. cb(Vcur, "Vcur", il);
  7681. Qcur = ggml_rope_custom(
  7682. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head_k, n_head, n_tokens), inp_pos,
  7683. n_embd_head_k, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7684. ext_factor, attn_factor, beta_fast, beta_slow);
  7685. cb(Qcur, "Qcur", il);
  7686. Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head_k)));
  7687. cb(Qcur, "Qcur_scaled", il);
  7688. Kcur = ggml_rope_custom(
  7689. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head_k, n_head_kv, n_tokens), inp_pos,
  7690. n_embd_head_k, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7691. ext_factor, attn_factor, beta_fast, beta_slow);
  7692. cb(Kcur, "Kcur", il);
  7693. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  7694. model.layers[il].wo, NULL,
  7695. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  7696. }
  7697. if (il == n_layer - 1) {
  7698. // skip computing output for unused tokens
  7699. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7700. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7701. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  7702. }
  7703. struct ggml_tensor * sa_out = ggml_add(ctx0, cur, inpL);
  7704. cb(sa_out, "sa_out", il);
  7705. cur = llm_build_norm(ctx0, sa_out, hparams,
  7706. model.layers[il].ffn_norm, NULL,
  7707. LLM_NORM_RMS, cb, il);
  7708. cb(cur, "ffn_norm", il);
  7709. // feed-forward network
  7710. {
  7711. cur = llm_build_ffn(ctx0, cur,
  7712. model.layers[il].ffn_up, NULL,
  7713. model.layers[il].ffn_gate, NULL,
  7714. model.layers[il].ffn_down, NULL,
  7715. NULL,
  7716. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  7717. cb(cur, "ffn_out", il);
  7718. }
  7719. cur = ggml_add(ctx0, cur, sa_out);
  7720. cb(cur, "l_out", il);
  7721. // input for next layer
  7722. inpL = cur;
  7723. }
  7724. cur = inpL;
  7725. cur = llm_build_norm(ctx0, cur, hparams,
  7726. model.output_norm, NULL,
  7727. LLM_NORM_RMS, cb, -1);
  7728. cb(cur, "result_norm", -1);
  7729. // lm_head
  7730. cur = ggml_mul_mat(ctx0, model.output, cur);
  7731. cb(cur, "result_output", -1);
  7732. ggml_build_forward_expand(gf, cur);
  7733. return gf;
  7734. }
  7735. struct ggml_cgraph * build_starcoder2() {
  7736. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7737. const int64_t n_embd_head = hparams.n_embd_head_v;
  7738. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7739. GGML_ASSERT(n_embd_head == hparams.n_rot);
  7740. struct ggml_tensor * cur;
  7741. struct ggml_tensor * inpL;
  7742. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7743. // inp_pos - contains the positions
  7744. struct ggml_tensor * inp_pos = build_inp_pos();
  7745. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7746. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7747. for (int il = 0; il < n_layer; ++il) {
  7748. struct ggml_tensor * inpSA = inpL;
  7749. // norm
  7750. cur = llm_build_norm(ctx0, inpL, hparams,
  7751. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  7752. LLM_NORM, cb, il);
  7753. cb(cur, "attn_norm", il);
  7754. // self-attention
  7755. {
  7756. // compute Q and K and RoPE them
  7757. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  7758. cb(Qcur, "Qcur", il);
  7759. if (model.layers[il].bq) {
  7760. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  7761. cb(Qcur, "Qcur", il);
  7762. }
  7763. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  7764. cb(Kcur, "Kcur", il);
  7765. if (model.layers[il].bk) {
  7766. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  7767. cb(Kcur, "Kcur", il);
  7768. }
  7769. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  7770. cb(Vcur, "Vcur", il);
  7771. if (model.layers[il].bv) {
  7772. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  7773. cb(Vcur, "Vcur", il);
  7774. }
  7775. Qcur = ggml_rope_custom(
  7776. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  7777. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7778. ext_factor, attn_factor, beta_fast, beta_slow
  7779. );
  7780. cb(Qcur, "Qcur", il);
  7781. Kcur = ggml_rope_custom(
  7782. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  7783. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7784. ext_factor, attn_factor, beta_fast, beta_slow
  7785. );
  7786. cb(Kcur, "Kcur", il);
  7787. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  7788. model.layers[il].wo, model.layers[il].bo,
  7789. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7790. }
  7791. if (il == n_layer - 1) {
  7792. // skip computing output for unused tokens
  7793. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7794. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7795. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  7796. }
  7797. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  7798. cb(ffn_inp, "ffn_inp", il);
  7799. // feed-forward network
  7800. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7801. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  7802. LLM_NORM, cb, il);
  7803. cb(cur, "ffn_norm", il);
  7804. cur = llm_build_ffn(ctx0, cur,
  7805. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  7806. NULL, NULL,
  7807. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  7808. NULL,
  7809. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  7810. cb(cur, "ffn_out", il);
  7811. cur = ggml_add(ctx0, cur, ffn_inp);
  7812. cb(cur, "l_out", il);
  7813. // input for next layer
  7814. inpL = cur;
  7815. }
  7816. cur = inpL;
  7817. cur = llm_build_norm(ctx0, cur, hparams,
  7818. model.output_norm, model.output_norm_b,
  7819. LLM_NORM, cb, -1);
  7820. cb(cur, "result_norm", -1);
  7821. // lm_head
  7822. cur = ggml_mul_mat(ctx0, model.output, cur);
  7823. cb(cur, "result_output", -1);
  7824. ggml_build_forward_expand(gf, cur);
  7825. return gf;
  7826. }
  7827. struct ggml_cgraph * build_mamba() {
  7828. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7829. const int64_t d_model = n_embd;
  7830. const int64_t d_conv = hparams.ssm_d_conv;
  7831. const int64_t d_inner = hparams.ssm_d_inner;
  7832. GGML_ASSERT(2 * d_model == d_inner);
  7833. const int64_t d_state = hparams.ssm_d_state;
  7834. const int64_t dt_rank = hparams.ssm_dt_rank;
  7835. struct ggml_tensor * cur;
  7836. struct ggml_tensor * inpL;
  7837. // {n_embd, n_tokens}
  7838. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7839. struct ggml_tensor * state_mask = build_inp_s_mask();
  7840. struct ggml_tensor * state_seq = build_inp_s_seq();
  7841. for (int il = 0; il < n_layer; ++il) {
  7842. // (ab)using the KV cache to store the states
  7843. struct ggml_tensor * conv_states = ggml_reshape_2d(ctx0, kv_self.k_l[il], hparams.n_embd_k_s(), kv_self.size);
  7844. struct ggml_tensor * ssm_states = ggml_reshape_2d(ctx0, kv_self.v_l[il], hparams.n_embd_v_s(), kv_self.size);
  7845. // clear states of sequences which are starting at the beginning of this batch
  7846. {
  7847. conv_states = ggml_mul(ctx0,
  7848. ggml_view_2d(ctx0, conv_states, conv_states->ne[0], n_kv, conv_states->nb[1], kv_head*conv_states->nb[1]),
  7849. state_mask);
  7850. ssm_states = ggml_mul(ctx0,
  7851. ggml_view_2d(ctx0, ssm_states, ssm_states->ne[0], n_kv, ssm_states->nb[1], kv_head*ssm_states->nb[1]),
  7852. state_mask);
  7853. }
  7854. conv_states = ggml_reshape_3d(ctx0, conv_states, d_conv - 1, d_inner, n_kv);
  7855. ssm_states = ggml_reshape_3d(ctx0, ssm_states, d_state, d_inner, n_kv);
  7856. // norm
  7857. cur = llm_build_norm(ctx0, inpL, hparams,
  7858. model.layers[il].attn_norm, NULL,
  7859. LLM_NORM_RMS, cb, il);
  7860. cb(cur, "attn_norm", il);
  7861. // {n_embd, 2*d_inner} * {n_embd, n_tokens} => {2*d_inner, n_tokens}
  7862. struct ggml_tensor * xz = ggml_mul_mat(ctx0, model.layers[il].ssm_in, cur);
  7863. // split the above in two
  7864. // => {d_inner, n_tokens}
  7865. struct ggml_tensor * x = ggml_view_2d(ctx0, xz, d_inner, xz->ne[1], xz->nb[1], 0);
  7866. struct ggml_tensor * z = ggml_view_2d(ctx0, xz, d_inner, xz->ne[1], xz->nb[1], ggml_element_size(xz)*d_inner);
  7867. // conv
  7868. {
  7869. // Custom operator which is needed only to ease simultaneous sequence processing.
  7870. // For a single sequence, the equivalent is to concatenate the columns of conv_states and x,
  7871. // then make a self-overlapping view of that over d_conv columns at each stride in the 3rd dimension,
  7872. // then element-wise multiply that with the conv1d weigth,
  7873. // then sum the elements of each row,
  7874. // (the last two steps are a dot product over rows (also doable with mul_mat))
  7875. // then permute away the ne[0] dimension,
  7876. // and then you're left with the resulting x tensor.
  7877. // The new conv_states is the last (d_conv - 1) columns
  7878. // of the last 3rd dimensional "layer" of the self-overlapping view.
  7879. // For simultaneous sequences, it's more complicated.
  7880. struct ggml_tensor * x_conv = ggml_ssm_conv(ctx0, conv_states, x, model.layers[il].ssm_conv1d, state_seq);
  7881. // store last (d_conv - 1) columns of the conv_state part of x_conv back into the KV cache
  7882. ggml_build_forward_expand(gf,
  7883. ggml_cpy(ctx0,
  7884. 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)),
  7885. 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))));
  7886. // extract x from x_conv
  7887. x = ggml_view_2d(ctx0, x_conv, d_inner, n_tokens, d_inner*ggml_element_size(x_conv), 0);
  7888. // bias
  7889. x = ggml_add(ctx0, x, model.layers[il].ssm_conv1d_b);
  7890. x = ggml_silu(ctx0, x);
  7891. }
  7892. // ssm
  7893. {
  7894. // {d_inner, dt_rank + 2*d_state} * {d_inner, n_tokens} => {dt_rank + 2*d_state, n_tokens}
  7895. struct ggml_tensor * x_db = ggml_mul_mat(ctx0, model.layers[il].ssm_x, x);
  7896. // split
  7897. struct ggml_tensor * dt = ggml_view_2d(ctx0, x_db, dt_rank, n_tokens, x_db->nb[1], 0);
  7898. 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);
  7899. 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));
  7900. // {dt_rank, d_inner} * {dt_rank, n_tokens} => {d_inner, n_tokens}
  7901. dt = ggml_mul_mat(ctx0, model.layers[il].ssm_dt, dt);
  7902. dt = ggml_add(ctx0, dt, model.layers[il].ssm_dt_b);
  7903. // Custom operator to optimize the parallel associative scan
  7904. // as described in the Annex D of the Mamba paper.
  7905. // => {d_inner, n_tokens} and {d_state, d_inner, n_kv} combined,
  7906. // because only a single tensor can be returned.
  7907. struct ggml_tensor * y_ssm_states = ggml_ssm_scan(ctx0, ssm_states, x, dt, model.layers[il].ssm_a, B, C, state_seq);
  7908. // store last states (the second part of y_ssm_states)
  7909. ggml_build_forward_expand(gf,
  7910. ggml_cpy(ctx0,
  7911. ggml_view_1d(ctx0, y_ssm_states, d_state*d_inner*n_kv, d_inner*n_tokens*ggml_element_size(y_ssm_states)),
  7912. 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))));
  7913. struct ggml_tensor * y = ggml_view_2d(ctx0, y_ssm_states, d_inner, n_tokens, d_inner*ggml_element_size(y_ssm_states), 0);
  7914. if (il == n_layer - 1) {
  7915. // skip computing output for unused tokens
  7916. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7917. x = ggml_get_rows(ctx0, x, inp_out_ids);
  7918. y = ggml_get_rows(ctx0, y, inp_out_ids);
  7919. z = ggml_get_rows(ctx0, z, inp_out_ids);
  7920. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  7921. }
  7922. // {d_inner, n_tokens} * {d_inner} => {d_inner, n_tokens}
  7923. y = ggml_add(ctx0, y, ggml_mul(ctx0, x, model.layers[il].ssm_d));
  7924. y = ggml_mul(ctx0, y, ggml_silu(ctx0, z));
  7925. // {d_inner, n_embd} * {d_inner, n_tokens} => {n_embd, n_tokens}
  7926. cur = ggml_mul_mat(ctx0, model.layers[il].ssm_out, y);
  7927. }
  7928. // residual
  7929. cur = ggml_add(ctx0, cur, inpL);
  7930. cb(cur, "l_out", il);
  7931. // input for next layer
  7932. inpL = cur;
  7933. }
  7934. // final rmsnorm
  7935. cur = llm_build_norm(ctx0, inpL, hparams,
  7936. model.output_norm, NULL,
  7937. LLM_NORM_RMS, cb, -1);
  7938. cb(cur, "result_norm", -1);
  7939. // lm_head
  7940. cur = ggml_mul_mat(ctx0, model.output, cur);
  7941. cb(cur, "result_output", -1);
  7942. ggml_build_forward_expand(gf, cur);
  7943. return gf;
  7944. }
  7945. struct ggml_cgraph * build_command_r() {
  7946. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7947. const int64_t n_embd_head = hparams.n_embd_head_v;
  7948. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7949. const float f_logit_scale = hparams.f_logit_scale;
  7950. struct ggml_tensor * cur;
  7951. struct ggml_tensor * inpL;
  7952. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7953. // inp_pos - contains the positions
  7954. struct ggml_tensor * inp_pos = build_inp_pos();
  7955. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7956. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7957. for (int il = 0; il < n_layer; ++il) {
  7958. // norm
  7959. cur = llm_build_norm(ctx0, inpL, hparams,
  7960. model.layers[il].attn_norm, NULL,
  7961. LLM_NORM, cb, il);
  7962. cb(cur, "attn_norm", il);
  7963. struct ggml_tensor * ffn_inp = cur;
  7964. // self-attention
  7965. {
  7966. // compute Q and K and RoPE them
  7967. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  7968. cb(Qcur, "Qcur", il);
  7969. if (model.layers[il].bq) {
  7970. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  7971. cb(Qcur, "Qcur", il);
  7972. }
  7973. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  7974. cb(Kcur, "Kcur", il);
  7975. if (model.layers[il].bk) {
  7976. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  7977. cb(Kcur, "Kcur", il);
  7978. }
  7979. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  7980. cb(Vcur, "Vcur", il);
  7981. if (model.layers[il].bv) {
  7982. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  7983. cb(Vcur, "Vcur", il);
  7984. }
  7985. if (model.layers[il].attn_q_norm) {
  7986. Qcur = ggml_view_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens,
  7987. ggml_element_size(Qcur) * n_embd_head,
  7988. ggml_element_size(Qcur) * n_embd_head * n_head,
  7989. 0);
  7990. cb(Qcur, "Qcur", il);
  7991. Kcur = ggml_view_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens,
  7992. ggml_element_size(Kcur) * n_embd_head,
  7993. ggml_element_size(Kcur) * n_embd_head * n_head_kv,
  7994. 0);
  7995. cb(Kcur, "Kcur", il);
  7996. Qcur = llm_build_norm(ctx0, Qcur, hparams,
  7997. model.layers[il].attn_q_norm,
  7998. NULL,
  7999. LLM_NORM, cb, il);
  8000. cb(Qcur, "Qcur", il);
  8001. Kcur = llm_build_norm(ctx0, Kcur, hparams,
  8002. model.layers[il].attn_k_norm,
  8003. NULL,
  8004. LLM_NORM, cb, il);
  8005. cb(Kcur, "Kcur", il);
  8006. }
  8007. Qcur = ggml_rope_custom(
  8008. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  8009. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  8010. ext_factor, attn_factor, beta_fast, beta_slow
  8011. );
  8012. cb(Qcur, "Qcur", il);
  8013. Kcur = ggml_rope_custom(
  8014. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  8015. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  8016. ext_factor, attn_factor, beta_fast, beta_slow
  8017. );
  8018. cb(Kcur, "Kcur", il);
  8019. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  8020. model.layers[il].wo, model.layers[il].bo,
  8021. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  8022. }
  8023. if (il == n_layer - 1) {
  8024. // skip computing output for unused tokens
  8025. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  8026. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  8027. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  8028. ffn_inp = ggml_get_rows(ctx0, ffn_inp, inp_out_ids);
  8029. }
  8030. struct ggml_tensor * attn_out = cur;
  8031. // feed-forward network
  8032. {
  8033. cur = llm_build_ffn(ctx0, ffn_inp,
  8034. model.layers[il].ffn_up, NULL,
  8035. model.layers[il].ffn_gate, NULL,
  8036. model.layers[il].ffn_down, NULL,
  8037. NULL,
  8038. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  8039. cb(cur, "ffn_out", il);
  8040. }
  8041. // add together residual + FFN + self-attention
  8042. cur = ggml_add(ctx0, cur, inpL);
  8043. cur = ggml_add(ctx0, cur, attn_out);
  8044. cb(cur, "l_out", il);
  8045. // input for next layer
  8046. inpL = cur;
  8047. }
  8048. cur = inpL;
  8049. cur = llm_build_norm(ctx0, cur, hparams,
  8050. model.output_norm, NULL,
  8051. LLM_NORM, cb, -1);
  8052. cb(cur, "result_norm", -1);
  8053. // lm_head
  8054. cur = ggml_mul_mat(ctx0, model.output, cur);
  8055. if (f_logit_scale) {
  8056. cur = ggml_scale(ctx0, cur, f_logit_scale);
  8057. }
  8058. cb(cur, "result_output", -1);
  8059. ggml_build_forward_expand(gf, cur);
  8060. return gf;
  8061. }
  8062. };
  8063. static struct ggml_cgraph * llama_build_graph_defrag(llama_context & lctx, const std::vector<uint32_t> & ids) {
  8064. llama_batch dummy;
  8065. dummy.n_tokens = 0;
  8066. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  8067. struct llm_build_context llm(lctx, dummy, cb, false);
  8068. llm.init();
  8069. struct ggml_cgraph * result = llm.build_defrag(ids);
  8070. llm.free();
  8071. return result;
  8072. }
  8073. static struct ggml_cgraph * llama_build_graph_k_shift(llama_context & lctx) {
  8074. llama_batch dummy;
  8075. dummy.n_tokens = 0;
  8076. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  8077. struct llm_build_context llm(lctx, dummy, cb, false);
  8078. llm.init();
  8079. struct ggml_cgraph * result = llm.build_k_shift();
  8080. llm.free();
  8081. return result;
  8082. }
  8083. static struct ggml_cgraph * llama_build_graph_s_copy(llama_context & lctx) {
  8084. llama_batch dummy;
  8085. dummy.n_tokens = 0;
  8086. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  8087. struct llm_build_context llm(lctx, dummy, cb, false);
  8088. llm.init();
  8089. struct ggml_cgraph * result = llm.build_s_copy();
  8090. llm.free();
  8091. return result;
  8092. }
  8093. static struct ggml_cgraph * llama_build_graph(
  8094. llama_context & lctx,
  8095. const llama_batch & batch,
  8096. bool worst_case) {
  8097. const auto & model = lctx.model;
  8098. // this callback allows us to apply custom logic to each tensor (e.g. ggml-alloc, offloading, etc.)
  8099. llm_build_cb cb = [&](struct ggml_tensor * cur, const char * name, int il) {
  8100. if (il >= 0) {
  8101. ggml_format_name(cur, "%s-%d", name, il);
  8102. } else {
  8103. ggml_set_name(cur, name);
  8104. }
  8105. if (!lctx.cparams.offload_kqv) {
  8106. if (strcmp(name, "kqv_merged_cont") == 0) {
  8107. // all nodes between the KV store and the attention output are run on the CPU
  8108. ggml_backend_sched_set_tensor_backend(lctx.sched, cur, lctx.backend_cpu);
  8109. }
  8110. }
  8111. // norm may be automatically assigned to the backend of the previous layer, increasing data transfer between backends
  8112. // FIXME: fix in ggml_backend_sched
  8113. const bool full_offload = lctx.model.n_gpu_layers > (int)lctx.model.hparams.n_layer;
  8114. if (batch.n_tokens < 32 || full_offload) {
  8115. if (il != -1 && strcmp(name, "norm") == 0) {
  8116. for (auto * backend : lctx.backends) {
  8117. if (ggml_backend_buft_supports_backend(lctx.model.buft_layer[il].buft, backend)) {
  8118. ggml_backend_sched_set_tensor_backend(lctx.sched, cur, backend);
  8119. break;
  8120. }
  8121. }
  8122. }
  8123. }
  8124. };
  8125. struct ggml_cgraph * result = NULL;
  8126. struct llm_build_context llm(lctx, batch, cb, worst_case);
  8127. llm.init();
  8128. switch (model.arch) {
  8129. case LLM_ARCH_LLAMA:
  8130. {
  8131. result = llm.build_llama();
  8132. } break;
  8133. case LLM_ARCH_BAICHUAN:
  8134. {
  8135. result = llm.build_baichuan();
  8136. } break;
  8137. case LLM_ARCH_FALCON:
  8138. {
  8139. result = llm.build_falcon();
  8140. } break;
  8141. case LLM_ARCH_GROK:
  8142. {
  8143. result = llm.build_grok();
  8144. } break;
  8145. case LLM_ARCH_STARCODER:
  8146. {
  8147. result = llm.build_starcoder();
  8148. } break;
  8149. case LLM_ARCH_PERSIMMON:
  8150. {
  8151. result = llm.build_persimmon();
  8152. } break;
  8153. case LLM_ARCH_REFACT:
  8154. {
  8155. result = llm.build_refact();
  8156. } break;
  8157. case LLM_ARCH_BERT:
  8158. case LLM_ARCH_NOMIC_BERT:
  8159. {
  8160. result = llm.build_bert();
  8161. } break;
  8162. case LLM_ARCH_BLOOM:
  8163. {
  8164. result = llm.build_bloom();
  8165. } break;
  8166. case LLM_ARCH_MPT:
  8167. {
  8168. result = llm.build_mpt();
  8169. } break;
  8170. case LLM_ARCH_STABLELM:
  8171. {
  8172. result = llm.build_stablelm();
  8173. } break;
  8174. case LLM_ARCH_QWEN:
  8175. {
  8176. result = llm.build_qwen();
  8177. } break;
  8178. case LLM_ARCH_QWEN2:
  8179. {
  8180. result = llm.build_qwen2();
  8181. } break;
  8182. case LLM_ARCH_PHI2:
  8183. {
  8184. result = llm.build_phi2();
  8185. } break;
  8186. case LLM_ARCH_PLAMO:
  8187. {
  8188. result = llm.build_plamo();
  8189. } break;
  8190. case LLM_ARCH_GPT2:
  8191. {
  8192. result = llm.build_gpt2();
  8193. } break;
  8194. case LLM_ARCH_CODESHELL:
  8195. {
  8196. result = llm.build_codeshell();
  8197. } break;
  8198. case LLM_ARCH_ORION:
  8199. {
  8200. result = llm.build_orion();
  8201. } break;
  8202. case LLM_ARCH_INTERNLM2:
  8203. {
  8204. result = llm.build_internlm2();
  8205. } break;
  8206. case LLM_ARCH_MINICPM:
  8207. {
  8208. result = llm.build_minicpm();
  8209. } break;
  8210. case LLM_ARCH_GEMMA:
  8211. {
  8212. result = llm.build_gemma();
  8213. } break;
  8214. case LLM_ARCH_STARCODER2:
  8215. {
  8216. result = llm.build_starcoder2();
  8217. } break;
  8218. case LLM_ARCH_MAMBA:
  8219. {
  8220. result = llm.build_mamba();
  8221. } break;
  8222. case LLM_ARCH_XVERSE:
  8223. {
  8224. result = llm.build_xverse();
  8225. } break;
  8226. case LLM_ARCH_COMMAND_R:
  8227. {
  8228. result = llm.build_command_r();
  8229. } break;
  8230. case LLM_ARCH_DBRX:
  8231. {
  8232. result = llm.build_dbrx();
  8233. } break;
  8234. default:
  8235. GGML_ASSERT(false);
  8236. }
  8237. llm.free();
  8238. return result;
  8239. }
  8240. static void llama_set_k_shift(llama_context & lctx) {
  8241. const int64_t kv_size = lctx.kv_self.size;
  8242. assert(ggml_backend_buffer_is_host(lctx.inp_K_shift->buffer));
  8243. int32_t * data = (int32_t *) lctx.inp_K_shift->data;
  8244. for (int i = 0; i < kv_size; ++i) {
  8245. data[i] = lctx.kv_self.cells[i].delta;
  8246. }
  8247. }
  8248. static void llama_set_s_copy(llama_context & lctx) {
  8249. const int64_t kv_size = lctx.kv_self.size;
  8250. assert(ggml_backend_buffer_is_host(lctx.inp_s_copy->buffer));
  8251. int32_t * data = (int32_t *) lctx.inp_s_copy->data;
  8252. for (int i = 0; i < kv_size; ++i) {
  8253. data[i] = lctx.kv_self.cells[i].src;
  8254. }
  8255. }
  8256. static void llama_set_inputs(llama_context & lctx, const llama_batch & batch) {
  8257. //
  8258. // set input data
  8259. //
  8260. const auto & hparams = lctx.model.hparams;
  8261. const auto & cparams = lctx.cparams;
  8262. const auto & kv_self = lctx.kv_self;
  8263. if (batch.token) {
  8264. const int64_t n_tokens = batch.n_tokens;
  8265. ggml_backend_tensor_set(lctx.inp_tokens, batch.token, 0, n_tokens*ggml_element_size(lctx.inp_tokens));
  8266. }
  8267. if (batch.embd) {
  8268. const int64_t n_embd = hparams.n_embd;
  8269. const int64_t n_tokens = batch.n_tokens;
  8270. ggml_backend_tensor_set(lctx.inp_embd, batch.embd, 0, n_tokens*n_embd*ggml_element_size(lctx.inp_embd));
  8271. }
  8272. if (batch.pos && lctx.inp_pos) {
  8273. const int64_t n_tokens = batch.n_tokens;
  8274. ggml_backend_tensor_set(lctx.inp_pos, batch.pos, 0, n_tokens*ggml_element_size(lctx.inp_pos));
  8275. }
  8276. if (hparams.causal_attn || cparams.pooling_type == LLAMA_POOLING_TYPE_NONE) {
  8277. GGML_ASSERT(lctx.inp_out_ids && "every model that can must skip unused outputs");
  8278. const int64_t n_tokens = batch.n_tokens;
  8279. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_out_ids->buffer));
  8280. int32_t * data = (int32_t *) lctx.inp_out_ids->data;
  8281. if (lctx.n_outputs == n_tokens) {
  8282. for (int i = 0; i < n_tokens; ++i) {
  8283. data[i] = i;
  8284. }
  8285. } else if (batch.logits) {
  8286. int32_t n_outputs = 0;
  8287. for (int i = 0; i < n_tokens; ++i) {
  8288. if (batch.logits[i]) {
  8289. data[n_outputs++] = i;
  8290. }
  8291. }
  8292. // the graph needs to have been passed the correct number of outputs
  8293. GGML_ASSERT(lctx.n_outputs == n_outputs);
  8294. } else if (lctx.n_outputs == 1) {
  8295. // only keep last output
  8296. data[0] = n_tokens - 1;
  8297. } else {
  8298. GGML_ASSERT(lctx.n_outputs == 0);
  8299. }
  8300. }
  8301. GGML_ASSERT(
  8302. // (!a || b) is a logical implication (a -> b)
  8303. // !hparams.causal_attn -> !cparams.causal_attn
  8304. (hparams.causal_attn || !cparams.causal_attn) &&
  8305. "causal attention with embedding models is not supported"
  8306. );
  8307. if (lctx.inp_KQ_mask) {
  8308. // NOTE: hparams.causal_attn indicates the model is capable of generation and uses the kv cache.
  8309. if (cparams.causal_attn) {
  8310. const int64_t n_kv = kv_self.n;
  8311. const int64_t n_tokens = batch.n_tokens;
  8312. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  8313. float * data = (float *) lctx.inp_KQ_mask->data;
  8314. // For causal attention, use only the previous KV cells
  8315. // of the correct sequence for each token of the batch.
  8316. // It's assumed that if a token in the batch has multiple sequences, they are equivalent.
  8317. for (int h = 0; h < 1; ++h) {
  8318. for (int j = 0; j < n_tokens; ++j) {
  8319. const llama_pos pos = batch.pos[j];
  8320. const llama_seq_id seq_id = batch.seq_id[j][0];
  8321. for (int i = 0; i < n_kv; ++i) {
  8322. float f;
  8323. if (!lctx.kv_self.cells[i].has_seq_id(seq_id) || lctx.kv_self.cells[i].pos > pos) {
  8324. f = -INFINITY;
  8325. } else {
  8326. f = 0.0f;
  8327. }
  8328. data[h*(n_kv*n_tokens) + j*n_kv + i] = f;
  8329. }
  8330. }
  8331. }
  8332. } else {
  8333. // when using kv cache, the mask needs to match the kv cache size
  8334. const int64_t n_tokens = batch.n_tokens;
  8335. const int64_t n_stride = hparams.causal_attn ? kv_self.n : n_tokens;
  8336. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  8337. float * data = (float *) lctx.inp_KQ_mask->data;
  8338. for (int h = 0; h < 1; ++h) {
  8339. for (int j = 0; j < n_tokens; ++j) {
  8340. const llama_seq_id seq_id = batch.seq_id[j][0];
  8341. for (int i = 0; i < n_tokens; ++i) {
  8342. float f = -INFINITY;
  8343. for (int s = 0; s < batch.n_seq_id[i]; ++s) {
  8344. if (batch.seq_id[i][s] == seq_id) {
  8345. f = 0.0f;
  8346. break;
  8347. }
  8348. }
  8349. data[h*(n_tokens*n_tokens) + j*n_stride + i] = f;
  8350. }
  8351. for (int i = n_tokens; i < n_stride; ++i) {
  8352. data[h*(n_tokens*n_tokens) + j*n_stride + i] = -INFINITY;
  8353. }
  8354. }
  8355. }
  8356. }
  8357. }
  8358. if (hparams.need_kq_pos) {
  8359. const int64_t n_kv = kv_self.n;
  8360. GGML_ASSERT(lctx.inp_KQ_pos);
  8361. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_pos->buffer));
  8362. float * data = (float *) lctx.inp_KQ_pos->data;
  8363. for (int i = 0; i < n_kv; ++i) {
  8364. data[i] = float(lctx.kv_self.cells[i].pos);
  8365. }
  8366. }
  8367. if (cparams.pooling_type == LLAMA_POOLING_TYPE_MEAN) {
  8368. const int64_t n_tokens = batch.n_tokens;
  8369. GGML_ASSERT(lctx.inp_mean);
  8370. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_mean->buffer));
  8371. float * data = (float *) lctx.inp_mean->data;
  8372. memset(lctx.inp_mean->data, 0, n_tokens * n_tokens * ggml_element_size(lctx.inp_mean));
  8373. std::vector<uint64_t> sum(n_tokens, 0);
  8374. for (int i = 0; i < n_tokens; ++i) {
  8375. const llama_seq_id seq_id = batch.seq_id[i][0];
  8376. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == MEAN");
  8377. sum[seq_id] += 1;
  8378. }
  8379. std::vector<float> div(n_tokens, 0.0f);
  8380. for (int i = 0; i < n_tokens; ++i) {
  8381. const uint64_t s = sum[i];
  8382. if (s > 0) {
  8383. div[i] = 1.0f/float(s);
  8384. }
  8385. }
  8386. for (int i = 0; i < n_tokens; ++i) {
  8387. const llama_seq_id seq_id = batch.seq_id[i][0];
  8388. data[seq_id*n_tokens + i] = div[seq_id];
  8389. }
  8390. }
  8391. if (cparams.pooling_type == LLAMA_POOLING_TYPE_CLS) {
  8392. const int64_t n_tokens = batch.n_tokens;
  8393. GGML_ASSERT(lctx.inp_cls);
  8394. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_cls->buffer));
  8395. uint32_t * data = (uint32_t *) lctx.inp_cls->data;
  8396. memset(lctx.inp_cls->data, 0, n_tokens * ggml_element_size(lctx.inp_cls));
  8397. for (int i = 0; i < n_tokens; ++i) {
  8398. const llama_seq_id seq_id = batch.seq_id[i][0];
  8399. const llama_pos pos = batch.pos[i];
  8400. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == CLS");
  8401. if (pos == 0) {
  8402. data[seq_id] = i;
  8403. }
  8404. }
  8405. }
  8406. if (kv_self.recurrent) {
  8407. const int64_t n_kv = kv_self.n;
  8408. if (lctx.inp_s_mask) {
  8409. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_s_mask->buffer));
  8410. float * data = (float *) lctx.inp_s_mask->data;
  8411. // states which are not affected by the current batch are left untouched
  8412. for (int i = 0; i < n_kv; ++i) {
  8413. llama_seq_id seq_id = i + lctx.kv_self.head;
  8414. llama_kv_cell & kv_cell = lctx.kv_self.cells[seq_id];
  8415. bool has_self_seq = kv_cell.has_seq_id(seq_id);
  8416. data[i] = (float) has_self_seq;
  8417. // ensure current sequences will be kept
  8418. if (!has_self_seq && kv_cell.pos >= 0) {
  8419. kv_cell.seq_id.insert(seq_id);
  8420. }
  8421. }
  8422. }
  8423. // For Mamba (and other recurrent architectures),
  8424. // update the correct state(s)/sequence(s) for each token of the batch.
  8425. // Like with the KQ_mask, if a token in the batch has multiple sequences,
  8426. // they are assumed to be equivalent (not here, but in ggml_ssm_scan and ggml_ssm_conv).
  8427. if (lctx.inp_s_seq) {
  8428. const int64_t n_tokens = batch.n_tokens;
  8429. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_s_seq->buffer));
  8430. int32_t * data = (int32_t *) lctx.inp_s_seq->data;
  8431. for (int j = 0; j < n_tokens; ++j) {
  8432. const int32_t n_seq = batch.n_seq_id[j];
  8433. GGML_ASSERT(0 < n_seq); // a token should be part of at least 1 sequence
  8434. for (int i = 0; i < n_kv; ++i) {
  8435. if (i < n_seq) {
  8436. // for this type of model, the head is the minimum seq_id of the batch
  8437. data[j*n_kv + i] = batch.seq_id[j][i] - kv_self.head;
  8438. } else {
  8439. data[j*n_kv + i] = -1;
  8440. }
  8441. }
  8442. }
  8443. }
  8444. }
  8445. }
  8446. // Make sure enough space is available for outputs.
  8447. // Returns max number of outputs for which space was reserved.
  8448. static size_t llama_output_reserve(llama_context & lctx, size_t n_outputs) {
  8449. const auto & cparams = lctx.cparams;
  8450. const auto & hparams = lctx.model.hparams;
  8451. const size_t n_outputs_max = std::max(n_outputs, (size_t) cparams.n_seq_max);
  8452. const auto n_batch = cparams.n_batch;
  8453. const auto n_vocab = hparams.n_vocab;
  8454. const auto n_embd = hparams.n_embd;
  8455. // TODO: use a per-batch flag for logits presence instead
  8456. const bool has_logits = cparams.causal_attn;
  8457. const bool has_embd = cparams.embeddings && (hparams.causal_attn || cparams.pooling_type == LLAMA_POOLING_TYPE_NONE);
  8458. const size_t logits_size = has_logits ? n_vocab*n_outputs_max : 0;
  8459. const size_t embd_size = has_embd ? n_embd*n_outputs_max : 0;
  8460. if (lctx.output_ids.empty()) {
  8461. // init, never resized afterwards
  8462. lctx.output_ids.resize(n_batch);
  8463. }
  8464. const size_t prev_size = lctx.buf_output ? ggml_backend_buffer_get_size(lctx.buf_output) : 0;
  8465. const size_t new_size = (logits_size + embd_size) * sizeof(float);
  8466. // alloc only when more than the current capacity is required
  8467. // TODO: also consider shrinking the buffer
  8468. if (!lctx.buf_output || prev_size < new_size) {
  8469. if (lctx.buf_output) {
  8470. #ifndef NDEBUG
  8471. // This doesn't happen often, but may be annoying in some cases (like the HellaSwag benchmark)
  8472. 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);
  8473. #endif
  8474. ggml_backend_buffer_free(lctx.buf_output);
  8475. lctx.buf_output = nullptr;
  8476. lctx.logits = nullptr;
  8477. lctx.embd = nullptr;
  8478. }
  8479. lctx.buf_output = ggml_backend_buft_alloc_buffer(llama_default_buffer_type_cpu(true), new_size);
  8480. if (lctx.buf_output == nullptr) {
  8481. LLAMA_LOG_ERROR("%s: failed to allocate output buffer of size %.2f MiB\n", __func__, new_size / (1024.0 * 1024.0));
  8482. return 0;
  8483. }
  8484. }
  8485. float * output_base = (float *) ggml_backend_buffer_get_base(lctx.buf_output);
  8486. lctx.logits = has_logits ? output_base : nullptr;
  8487. lctx.embd = has_embd ? output_base + logits_size : nullptr;
  8488. lctx.output_size = n_outputs_max;
  8489. lctx.logits_size = logits_size;
  8490. lctx.embd_size = embd_size;
  8491. // set all ids as invalid (negative)
  8492. std::fill(lctx.output_ids.begin(), lctx.output_ids.end(), -1);
  8493. ggml_backend_buffer_clear(lctx.buf_output, 0);
  8494. lctx.n_outputs = 0;
  8495. return n_outputs_max;
  8496. }
  8497. static void llama_graph_compute(
  8498. llama_context & lctx,
  8499. ggml_cgraph * gf,
  8500. int n_threads) {
  8501. #ifdef GGML_USE_MPI
  8502. const int64_t n_layer = lctx.model.hparams.n_layer;
  8503. ggml_mpi_graph_compute_pre(lctx.ctx_mpi, gf, n_layer);
  8504. #endif
  8505. #ifdef GGML_USE_METAL
  8506. if (ggml_backend_is_metal(lctx.backend_metal)) {
  8507. ggml_backend_metal_set_n_cb(lctx.backend_metal, n_threads);
  8508. }
  8509. #endif
  8510. if (lctx.backend_cpu != nullptr) {
  8511. ggml_backend_cpu_set_n_threads(lctx.backend_cpu, n_threads);
  8512. ggml_backend_cpu_set_abort_callback(lctx.backend_cpu, lctx.abort_callback, lctx.abort_callback_data);
  8513. }
  8514. ggml_backend_sched_graph_compute_async(lctx.sched, gf);
  8515. // fprintf(stderr, "splits: %d\n", ggml_backend_sched_get_n_splits(lctx.sched));
  8516. #ifdef GGML_USE_MPI
  8517. ggml_mpi_graph_compute_post(lctx.ctx_mpi, gf, n_layer);
  8518. #endif
  8519. }
  8520. // decode a batch of tokens by evaluating the transformer
  8521. //
  8522. // - lctx: llama context
  8523. // - batch: batch to evaluate
  8524. //
  8525. // return 0 on success
  8526. // return positive int on warning
  8527. // return negative int on error
  8528. //
  8529. static int llama_decode_internal(
  8530. llama_context & lctx,
  8531. llama_batch batch_all) { // TODO: rename back to batch
  8532. const uint32_t n_tokens_all = batch_all.n_tokens;
  8533. if (n_tokens_all == 0) {
  8534. LLAMA_LOG_ERROR("%s: n_tokens == 0", __func__);
  8535. return -1;
  8536. }
  8537. const auto & model = lctx.model;
  8538. const auto & hparams = model.hparams;
  8539. const auto & cparams = lctx.cparams;
  8540. GGML_ASSERT((!batch_all.token && batch_all.embd) || (batch_all.token && !batch_all.embd)); // NOLINT
  8541. GGML_ASSERT(n_tokens_all <= cparams.n_batch);
  8542. GGML_ASSERT((cparams.causal_attn || cparams.n_ubatch >= n_tokens_all) && "non-causal attention requires n_ubatch >= n_tokens");
  8543. if (lctx.t_compute_start_us == 0) {
  8544. lctx.t_compute_start_us = ggml_time_us();
  8545. }
  8546. lctx.n_queued_tokens += n_tokens_all;
  8547. #ifdef GGML_USE_MPI
  8548. // TODO: needs fix after #3228
  8549. GGML_ASSERT(false && "not implemented");
  8550. //ggml_mpi_eval_init(lctx.ctx_mpi, &n_tokens, &n_past, &n_threads);
  8551. #endif
  8552. auto & kv_self = lctx.kv_self;
  8553. const int64_t n_embd = hparams.n_embd;
  8554. const int64_t n_vocab = hparams.n_vocab;
  8555. uint32_t n_outputs = 0;
  8556. uint32_t n_outputs_prev = 0;
  8557. const auto n_ubatch = cparams.n_ubatch;
  8558. std::vector<llama_pos> pos;
  8559. std::vector<int32_t> n_seq_id;
  8560. std::vector<llama_seq_id *> seq_id_arr;
  8561. std::vector<std::vector<llama_seq_id>> seq_id;
  8562. // count outputs
  8563. if (batch_all.logits) {
  8564. for (uint32_t i = 0; i < n_tokens_all; ++i) {
  8565. n_outputs += batch_all.logits[i] != 0;
  8566. }
  8567. } else if (lctx.logits_all || (cparams.embeddings && cparams.pooling_type != LLAMA_POOLING_TYPE_NONE)) {
  8568. n_outputs = n_tokens_all;
  8569. } else {
  8570. // keep last output only
  8571. n_outputs = 1;
  8572. }
  8573. // reserve output buffer
  8574. if (llama_output_reserve(lctx, n_outputs) < n_outputs) {
  8575. LLAMA_LOG_ERROR("%s: could not reserve space for batch with %u outputs\n", __func__, n_outputs);
  8576. return -2;
  8577. };
  8578. // set output mappings
  8579. if (batch_all.logits) {
  8580. int32_t i_logits = 0;
  8581. for (uint32_t i = 0; i < n_tokens_all; ++i) {
  8582. if (batch_all.logits[i]) {
  8583. lctx.output_ids[i] = i_logits++;
  8584. }
  8585. }
  8586. } else {
  8587. for (uint32_t i = 0; i < n_outputs; ++i) {
  8588. lctx.output_ids[i] = i;
  8589. }
  8590. }
  8591. for (uint32_t cur_token = 0; cur_token < n_tokens_all; cur_token += n_ubatch) {
  8592. const uint32_t n_tokens = std::min(n_ubatch, n_tokens_all - cur_token);
  8593. llama_batch u_batch = {
  8594. /* .n_tokens = */ (int32_t) n_tokens,
  8595. /* .token = */ batch_all.token ? batch_all.token + cur_token : nullptr,
  8596. /* .embd = */ batch_all.embd ? batch_all.embd + cur_token*n_embd : nullptr,
  8597. /* .pos = */ batch_all.pos ? batch_all.pos + cur_token : nullptr,
  8598. /* .n_seq_id = */ batch_all.n_seq_id ? batch_all.n_seq_id + cur_token : nullptr,
  8599. /* .seq_id = */ batch_all.seq_id ? batch_all.seq_id + cur_token : nullptr,
  8600. /* .logits = */ batch_all.logits ? batch_all.logits + cur_token : nullptr,
  8601. /* .all_pos_0 = */ batch_all.all_pos_0 + (llama_pos) cur_token*batch_all.all_pos_1,
  8602. /* .all_pos_1 = */ batch_all.all_pos_1,
  8603. /* .all_seq_id = */ batch_all.all_seq_id,
  8604. };
  8605. // count the outputs in this u_batch
  8606. {
  8607. int32_t n_outputs_new = 0;
  8608. if (u_batch.logits) {
  8609. for (uint32_t i = 0; i < n_tokens; i++) {
  8610. n_outputs_new += u_batch.logits[i] != 0;
  8611. }
  8612. } else if (n_outputs == n_tokens_all) {
  8613. n_outputs_new = n_tokens;
  8614. } else {
  8615. // keep last output only
  8616. if (cur_token + n_tokens >= n_tokens_all) {
  8617. n_outputs_new = 1;
  8618. }
  8619. }
  8620. // needs to happen before the graph is built
  8621. lctx.n_outputs = n_outputs_new;
  8622. }
  8623. int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  8624. GGML_ASSERT(n_threads > 0);
  8625. // helpers for smoother batch API transition
  8626. // after deprecating the llama_eval calls, these will be removed
  8627. if (u_batch.pos == nullptr) {
  8628. pos.resize(n_tokens);
  8629. for (uint32_t i = 0; i < n_tokens; i++) {
  8630. pos[i] = u_batch.all_pos_0 + i*u_batch.all_pos_1;
  8631. }
  8632. u_batch.pos = pos.data();
  8633. }
  8634. if (u_batch.seq_id == nullptr) {
  8635. n_seq_id.resize(n_tokens);
  8636. seq_id.resize(n_tokens);
  8637. seq_id_arr.resize(n_tokens);
  8638. for (uint32_t i = 0; i < n_tokens; i++) {
  8639. n_seq_id[i] = 1;
  8640. seq_id[i].resize(1);
  8641. seq_id[i][0] = u_batch.all_seq_id;
  8642. seq_id_arr[i] = seq_id[i].data();
  8643. }
  8644. u_batch.n_seq_id = n_seq_id.data();
  8645. u_batch.seq_id = seq_id_arr.data();
  8646. }
  8647. // non-causal masks do not use the KV cache
  8648. if (hparams.causal_attn) {
  8649. llama_kv_cache_update(&lctx);
  8650. // if we have enough unused cells before the current head ->
  8651. // better to start searching from the beginning of the cache, hoping to fill it
  8652. if (kv_self.head > kv_self.used + 2*n_tokens) {
  8653. kv_self.head = 0;
  8654. }
  8655. if (!llama_kv_cache_find_slot(kv_self, u_batch)) {
  8656. return 1;
  8657. }
  8658. if (!kv_self.recurrent) {
  8659. // a heuristic, to avoid attending the full cache if it is not yet utilized
  8660. // after enough generations, the benefit from this heuristic disappears
  8661. // if we start defragmenting the cache, the benefit from this will be more important
  8662. kv_self.n = std::min(kv_self.size, std::max(32u, GGML_PAD(llama_kv_cache_cell_max(kv_self), 32)));
  8663. //kv_self.n = llama_kv_cache_cell_max(kv_self);
  8664. }
  8665. }
  8666. //printf("kv_self.n = %5d, kv_self.used = %5d, kv_self.head = %5d\n", kv_self.n, kv_self.used, kv_self.head);
  8667. ggml_backend_sched_reset(lctx.sched);
  8668. ggml_backend_sched_set_eval_callback(lctx.sched, lctx.cparams.cb_eval, lctx.cparams.cb_eval_user_data);
  8669. ggml_cgraph * gf = llama_build_graph(lctx, u_batch, false);
  8670. // the output is always the last tensor in the graph
  8671. struct ggml_tensor * res = gf->nodes[gf->n_nodes - 1];
  8672. struct ggml_tensor * embd = gf->nodes[gf->n_nodes - 2];
  8673. if (lctx.n_outputs == 0) {
  8674. // no output
  8675. res = nullptr;
  8676. embd = nullptr;
  8677. } else if (!hparams.causal_attn) {
  8678. res = nullptr; // do not extract logits for embedding models such as BERT
  8679. // token or sequence embeddings
  8680. embd = gf->nodes[gf->n_nodes - 1];
  8681. GGML_ASSERT(strcmp(embd->name, "result_embd") == 0 || strcmp(embd->name, "result_embd_pooled") == 0);
  8682. } else if (cparams.embeddings) {
  8683. // the embeddings could be in the second to last tensor, or any of the previous tensors
  8684. int i_embd = gf->n_nodes - 2;
  8685. for (int i = 3; strcmp(embd->name, "result_norm") != 0; ++i) {
  8686. i_embd = gf->n_nodes - i;
  8687. if (i_embd < 0) { break; }
  8688. embd = gf->nodes[i_embd];
  8689. }
  8690. GGML_ASSERT(i_embd >= 0 && "missing result_norm tensor");
  8691. // TODO: use a per-batch flag to know when to skip logits while keeping embeddings
  8692. if (!cparams.causal_attn) {
  8693. res = nullptr; // do not extract logits when not needed
  8694. // skip computing logits
  8695. // TODO: is this safe?
  8696. gf->n_nodes = i_embd + 1;
  8697. }
  8698. } else {
  8699. embd = nullptr; // do not extract embeddings when not needed
  8700. GGML_ASSERT(strcmp(res->name, "result_output") == 0 && "missing result_output tensor");
  8701. }
  8702. // 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);
  8703. // for big prompts, if BLAS is enabled, it is better to use only one thread
  8704. // otherwise, the threads are spin-lock waiting for the BLAS calls and are degrading the performance
  8705. // TODO: this is mostly important for Apple Silicon where CBLAS is still performing very well
  8706. // we still need some threads to process all non-mul_mat ops, but not too much to avoid interfering
  8707. // with the BLAS calls. need a better solution
  8708. // MoE Special Case: This logic applies when hparams.n_expert == 0, i.e. the model is NOT an MoE model. When an MoE is
  8709. // being processed then Accelerate/BLAS will not be involved, so capping would limit performance.
  8710. if (n_tokens >= 32 && hparams.n_expert == 0 && ggml_cpu_has_blas() && !ggml_cpu_has_gpublas()) {
  8711. n_threads = std::min(4, n_threads);
  8712. }
  8713. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  8714. llama_set_inputs(lctx, u_batch);
  8715. llama_graph_compute(lctx, gf, n_threads);
  8716. // update the kv ring buffer
  8717. {
  8718. kv_self.head += n_tokens;
  8719. // Ensure kv cache head points to a valid index.
  8720. if (kv_self.head >= kv_self.size) {
  8721. kv_self.head = 0;
  8722. }
  8723. }
  8724. #ifdef GGML_PERF
  8725. // print timing information per ggml operation (for debugging purposes)
  8726. // requires GGML_PERF to be defined
  8727. ggml_graph_print(gf);
  8728. #endif
  8729. // plot the computation graph in dot format (for debugging purposes)
  8730. //if (n_past%100 == 0) {
  8731. // ggml_graph_dump_dot(gf, NULL, "llama.dot");
  8732. //}
  8733. // extract logits
  8734. if (res) {
  8735. ggml_backend_t backend_res = ggml_backend_sched_get_tensor_backend(lctx.sched, res);
  8736. GGML_ASSERT(backend_res != nullptr);
  8737. GGML_ASSERT(lctx.logits != nullptr);
  8738. float * logits_out = lctx.logits + n_outputs_prev*n_vocab;
  8739. const int32_t n_outputs_new = lctx.n_outputs;
  8740. if (n_outputs_new) {
  8741. GGML_ASSERT( n_outputs_prev + n_outputs_new <= n_outputs);
  8742. GGML_ASSERT((n_outputs_prev + n_outputs_new)*n_vocab <= (int64_t) lctx.logits_size);
  8743. ggml_backend_tensor_get_async(backend_res, res, logits_out, 0, n_outputs_new*n_vocab*sizeof(float));
  8744. }
  8745. }
  8746. // extract embeddings
  8747. if (embd) {
  8748. ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend(lctx.sched, embd);
  8749. GGML_ASSERT(backend_embd != nullptr);
  8750. switch (cparams.pooling_type) {
  8751. case LLAMA_POOLING_TYPE_NONE:
  8752. {
  8753. // extract token embeddings
  8754. GGML_ASSERT(lctx.embd != nullptr);
  8755. float * embd_out = lctx.embd + n_outputs_prev*n_embd;
  8756. const int32_t n_outputs_new = lctx.n_outputs;
  8757. if (n_outputs_new) {
  8758. GGML_ASSERT( n_outputs_prev + n_outputs_new <= n_outputs);
  8759. GGML_ASSERT((n_outputs_prev + n_outputs_new)*n_embd <= (int64_t) lctx.embd_size);
  8760. ggml_backend_tensor_get_async(backend_embd, embd, embd_out, 0, n_outputs_new*n_embd*sizeof(float));
  8761. }
  8762. } break;
  8763. case LLAMA_POOLING_TYPE_CLS:
  8764. case LLAMA_POOLING_TYPE_MEAN:
  8765. {
  8766. GGML_ASSERT(strcmp(embd->name, "result_embd_pooled") == 0);
  8767. // extract sequence embeddings
  8768. auto & embd_seq_out = lctx.embd_seq;
  8769. embd_seq_out.clear();
  8770. for (uint32_t i = 0; i < n_tokens; i++) {
  8771. const llama_seq_id seq_id = u_batch.seq_id[i][0];
  8772. if (embd_seq_out.find(seq_id) != embd_seq_out.end()) {
  8773. continue;
  8774. }
  8775. embd_seq_out[seq_id].resize(n_embd);
  8776. ggml_backend_tensor_get_async(backend_embd, embd, embd_seq_out[seq_id].data(), (n_embd*seq_id)*sizeof(float), n_embd*sizeof(float));
  8777. }
  8778. } break;
  8779. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  8780. {
  8781. GGML_ASSERT(false && "unknown pooling type");
  8782. } break;
  8783. }
  8784. }
  8785. n_outputs_prev += lctx.n_outputs;
  8786. }
  8787. // set to total number of outputs in the batch, for use in llama_get_logits_ith
  8788. lctx.n_outputs = n_outputs;
  8789. // wait for the computation to finish (automatically done when obtaining the model output)
  8790. //llama_synchronize(&lctx);
  8791. // decide if we need to defrag the kv cache
  8792. if (cparams.causal_attn && cparams.defrag_thold >= 0.0f) {
  8793. const float fragmentation = kv_self.n >= 128 ? 1.0f - float(kv_self.used)/float(kv_self.n) : 0.0f;
  8794. // queue defragmentation for next llama_kv_cache_update
  8795. if (fragmentation > cparams.defrag_thold) {
  8796. //LLAMA_LOG_INFO("fragmentation: %.2f\n", fragmentation);
  8797. llama_kv_cache_defrag(kv_self);
  8798. }
  8799. }
  8800. return 0;
  8801. }
  8802. // find holes from the beginning of the KV cache and fill them by moving data from the end of the cache
  8803. static void llama_kv_cache_defrag_internal(struct llama_context & lctx) {
  8804. auto & kv_self = lctx.kv_self;
  8805. const auto & hparams = lctx.model.hparams;
  8806. const uint32_t n_layer = hparams.n_layer;
  8807. const uint32_t n_kv = llama_kv_cache_cell_max(kv_self);
  8808. const uint32_t n_used = kv_self.used;
  8809. assert(n_used <= n_kv);
  8810. //const int64_t t_start = ggml_time_us();
  8811. // number of cells moved
  8812. uint32_t n_moves = 0;
  8813. // each move requires 6*n_layer tensors (see build_defrag)
  8814. // - source view, destination view, copy operation
  8815. // - x2 for keys and values
  8816. const uint32_t max_moves = LLAMA_MAX_NODES/(6*n_layer);
  8817. // determine which KV cells to move where
  8818. //
  8819. // cell i moves to ids[i]
  8820. //
  8821. // if ids[i] == i || ids[i] == n_kv, then cell i is not moved
  8822. //
  8823. std::vector<uint32_t> ids(n_kv, n_kv);
  8824. for (uint32_t i0 = 0; i0 < n_used; ++i0) {
  8825. const auto & cell0 = kv_self.cells[i0];
  8826. if (!cell0.is_empty()) {
  8827. ids[i0] = i0;
  8828. continue;
  8829. }
  8830. // found a hole - fill it with data from the end of the cache
  8831. uint32_t nh = 1;
  8832. // determine the size of the hole
  8833. while (i0 + nh < n_used && kv_self.cells[i0 + nh].is_empty()) {
  8834. nh++;
  8835. }
  8836. uint32_t nf = 0;
  8837. uint32_t is = n_kv - 1;
  8838. // starting from the end, find nh non-empty cells
  8839. for (; is > i0; --is) {
  8840. const auto & cell1 = kv_self.cells[is];
  8841. if (cell1.is_empty() || ids[is] != n_kv) {
  8842. continue;
  8843. }
  8844. // non-empty cell which is not yet moved
  8845. nf++;
  8846. if (nf == nh) {
  8847. break;
  8848. }
  8849. }
  8850. // this can only happen if `n_used` is not accurate, which would be a bug
  8851. GGML_ASSERT(nf == nh && "KV defrag bug: nf != nh");
  8852. nf = 0;
  8853. uint32_t i1 = is;
  8854. // are we moving a continuous block of memory?
  8855. bool cont = false;
  8856. // should we stop searching for the next move?
  8857. bool stop = false;
  8858. // go back and move the nf cells to the hole
  8859. for (; i1 < n_kv; ++i1) {
  8860. auto & cell1 = kv_self.cells[i1];
  8861. if (cell1.is_empty() || ids[i1] != n_kv) {
  8862. if (n_moves == max_moves) {
  8863. stop = true;
  8864. break;
  8865. }
  8866. cont = false;
  8867. continue;
  8868. }
  8869. // this cell goes to (i0 + nf)
  8870. ids[i1] = i0 + nf;
  8871. // move the cell meta data
  8872. kv_self.cells[i0 + nf] = cell1;
  8873. // clear the old cell and move the head there
  8874. cell1 = llama_kv_cell();
  8875. kv_self.head = n_used;
  8876. if (!cont) {
  8877. n_moves++;
  8878. cont = true;
  8879. }
  8880. nf++;
  8881. if (nf == nh) {
  8882. break;
  8883. }
  8884. }
  8885. if (stop || n_moves == max_moves) {
  8886. break;
  8887. }
  8888. //LLAMA_LOG_INFO("(tmp log) KV defrag: move [%u, %u) to [%u, %u)\n", is, i1 + 1, i0, i0 + nh);
  8889. i0 += nh - 1;
  8890. }
  8891. if (n_moves == 0) {
  8892. return;
  8893. }
  8894. //LLAMA_LOG_INFO("(tmp log) KV defrag cell moves: %u\n", n_moves);
  8895. //LLAMA_LOG_INFO("expected gf nodes: %u\n", 6*n_moves*n_layer);
  8896. #if 0
  8897. // CPU defrag
  8898. //
  8899. // TODO: optimizations are possible:
  8900. // - multiple threads
  8901. // - avoid copying to the host memory when already there
  8902. //
  8903. // likely not worth the effort, as we have ggml_graph based defrag
  8904. //
  8905. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  8906. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  8907. const uint32_t kv_size = kv_self.size;
  8908. std::vector<uint8_t> buf_k;
  8909. std::vector<uint8_t> buf_v;
  8910. for (uint32_t il = 0; il < n_layer; ++il) {
  8911. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  8912. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_size);
  8913. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  8914. const size_t v_size = ggml_row_size (kv_self.v_l[il]->type, n_embd_v_gqa*kv_size);
  8915. buf_k.resize(k_size);
  8916. buf_v.resize(v_size);
  8917. ggml_backend_tensor_get(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  8918. ggml_backend_tensor_get(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  8919. // batch move [i, i+nm) to [id, id+nm)
  8920. // note: cells can move only to a lower index
  8921. for (uint32_t i = 0; i < n_kv; ++i) {
  8922. const uint32_t id = ids[i];
  8923. if (i == id || id == n_kv) {
  8924. continue;
  8925. }
  8926. uint32_t nm = 1;
  8927. while (i + nm < n_kv && ids[i + nm] == id + nm) {
  8928. nm++;
  8929. }
  8930. // move keys
  8931. {
  8932. const int64_t os = i*k_size_row;
  8933. const int64_t od = id*k_size_row;
  8934. memcpy(buf_k.data() + od, buf_k.data() + os, nm*k_size_row);
  8935. }
  8936. // move values (note: they are transposed)
  8937. {
  8938. const int64_t os = i;
  8939. const int64_t od = id;
  8940. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  8941. 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);
  8942. }
  8943. }
  8944. i += nm - 1;
  8945. }
  8946. ggml_backend_tensor_set(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  8947. ggml_backend_tensor_set(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  8948. }
  8949. #else
  8950. // ggml_graph defrag
  8951. ggml_backend_sched_reset(lctx.sched);
  8952. ggml_cgraph * gf = llama_build_graph_defrag(lctx, ids);
  8953. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  8954. #endif
  8955. //const int64_t t_end = ggml_time_us();
  8956. //LLAMA_LOG_INFO("(tmp log) KV defrag time: %.3f ms\n", (t_end - t_start)/1000.0);
  8957. }
  8958. static void llama_kv_cache_update_internal(struct llama_context & lctx) {
  8959. bool need_reserve = false;
  8960. // apply K-shift if needed
  8961. if (lctx.model.hparams.rope_type != LLAMA_ROPE_TYPE_NONE && lctx.kv_self.has_shift) {
  8962. {
  8963. ggml_backend_sched_reset(lctx.sched);
  8964. ggml_cgraph * gf = llama_build_graph_k_shift(lctx);
  8965. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  8966. llama_set_k_shift(lctx);
  8967. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  8968. need_reserve = true;
  8969. }
  8970. {
  8971. auto & kv_self = lctx.kv_self;
  8972. kv_self.has_shift = false;
  8973. for (uint32_t i = 0; i < kv_self.size; ++i) {
  8974. kv_self.cells[i].delta = 0;
  8975. }
  8976. }
  8977. }
  8978. if (lctx.kv_self.recurrent && lctx.kv_self.do_copy) {
  8979. {
  8980. ggml_backend_sched_reset(lctx.sched);
  8981. ggml_cgraph * gf = llama_build_graph_s_copy(lctx);
  8982. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  8983. llama_set_s_copy(lctx);
  8984. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  8985. need_reserve = true;
  8986. }
  8987. {
  8988. auto & kv_self = lctx.kv_self;
  8989. kv_self.do_copy = false;
  8990. for (uint32_t i = 0; i < kv_self.size; ++i) {
  8991. kv_self.cells[i].src = i;
  8992. }
  8993. }
  8994. }
  8995. // defragment the KV cache if needed
  8996. if (lctx.kv_self.do_defrag) {
  8997. llama_kv_cache_defrag_internal(lctx);
  8998. need_reserve = true;
  8999. lctx.kv_self.do_defrag = false;
  9000. }
  9001. // reserve a worst case graph again
  9002. if (need_reserve) {
  9003. // TODO: extract to a function
  9004. // build worst-case graph
  9005. int n_tokens = (int)std::min(lctx.cparams.n_ctx, lctx.cparams.n_ubatch);
  9006. int n_past = lctx.cparams.n_ctx - n_tokens;
  9007. 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
  9008. ggml_cgraph * gf = llama_build_graph(lctx, llama_batch_get_one(&token, n_tokens, n_past, 0), true);
  9009. // initialize scheduler with the worst-case graph
  9010. ggml_backend_sched_reset(lctx.sched);
  9011. if (!ggml_backend_sched_reserve(lctx.sched, gf)) {
  9012. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  9013. }
  9014. }
  9015. }
  9016. //
  9017. // tokenizer
  9018. //
  9019. static enum llama_vocab_type llama_vocab_get_type(const llama_vocab & vocab) {
  9020. return vocab.type;
  9021. }
  9022. static bool llama_is_normal_token(const llama_vocab & vocab, llama_token id) {
  9023. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  9024. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL;
  9025. }
  9026. static bool llama_is_unknown_token(const llama_vocab & vocab, llama_token id) {
  9027. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  9028. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_UNKNOWN;
  9029. }
  9030. static bool llama_is_control_token(const llama_vocab & vocab, llama_token id) {
  9031. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  9032. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_CONTROL;
  9033. }
  9034. static bool llama_is_byte_token(const llama_vocab & vocab, llama_token id) {
  9035. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  9036. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_BYTE;
  9037. }
  9038. static bool llama_is_user_defined_token(const llama_vocab& vocab, llama_token id) {
  9039. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  9040. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_USER_DEFINED;
  9041. }
  9042. static uint8_t llama_token_to_byte(const llama_vocab& vocab, llama_token id) {
  9043. GGML_ASSERT(llama_vocab_get_type(vocab) != LLAMA_VOCAB_TYPE_NONE);
  9044. GGML_ASSERT(llama_is_byte_token(vocab, id));
  9045. const auto& token_data = vocab.id_to_token.at(id);
  9046. switch (llama_vocab_get_type(vocab)) {
  9047. case LLAMA_VOCAB_TYPE_SPM: {
  9048. auto buf = token_data.text.substr(3, 2);
  9049. return strtol(buf.c_str(), NULL, 16);
  9050. }
  9051. case LLAMA_VOCAB_TYPE_BPE: {
  9052. GGML_ASSERT(false);
  9053. return unicode_utf8_to_byte(token_data.text);
  9054. }
  9055. case LLAMA_VOCAB_TYPE_WPM: {
  9056. GGML_ASSERT(false);
  9057. }
  9058. default:
  9059. GGML_ASSERT(false);
  9060. }
  9061. }
  9062. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch) {
  9063. GGML_ASSERT(llama_vocab_get_type(vocab) != LLAMA_VOCAB_TYPE_NONE);
  9064. static const char * hex = "0123456789ABCDEF";
  9065. switch (llama_vocab_get_type(vocab)) {
  9066. case LLAMA_VOCAB_TYPE_SPM: {
  9067. const char buf[7] = { '<', '0', 'x', hex[ch >> 4], hex[ch & 15], '>', 0 };
  9068. auto token = vocab.token_to_id.find(buf);
  9069. if (token != vocab.token_to_id.end()) {
  9070. return (*token).second;
  9071. }
  9072. // Try to fall back to just the byte as a string
  9073. const char buf2[2] = { (char)ch, 0 };
  9074. return vocab.token_to_id.at(buf2);
  9075. }
  9076. case LLAMA_VOCAB_TYPE_WPM:
  9077. case LLAMA_VOCAB_TYPE_BPE: {
  9078. return vocab.token_to_id.at(unicode_byte_to_utf8(ch));
  9079. }
  9080. default:
  9081. GGML_ASSERT(false);
  9082. }
  9083. }
  9084. static void llama_escape_whitespace(std::string & text) {
  9085. replace_all(text, " ", "\xe2\x96\x81");
  9086. }
  9087. static void llama_unescape_whitespace(std::string & word) {
  9088. replace_all(word, "\xe2\x96\x81", " ");
  9089. }
  9090. struct llm_symbol {
  9091. using index = int;
  9092. index prev;
  9093. index next;
  9094. const char * text;
  9095. size_t n;
  9096. };
  9097. static_assert(std::is_trivially_copyable<llm_symbol>::value, "llm_symbol is not trivially copyable");
  9098. // SPM tokenizer
  9099. // original implementation:
  9100. // https://github.com/ggerganov/llama.cpp/commit/074bea2eb1f1349a0118239c4152914aecaa1be4
  9101. struct llm_bigram_spm {
  9102. struct comparator {
  9103. bool operator()(llm_bigram_spm & l, llm_bigram_spm & r) {
  9104. return (l.score < r.score) || (l.score == r.score && l.left > r.left);
  9105. }
  9106. };
  9107. using queue_storage = std::vector<llm_bigram_spm>;
  9108. using queue = std::priority_queue<llm_bigram_spm, queue_storage, comparator>;
  9109. llm_symbol::index left;
  9110. llm_symbol::index right;
  9111. float score;
  9112. size_t size;
  9113. };
  9114. struct llm_tokenizer_spm {
  9115. llm_tokenizer_spm(const llama_vocab & vocab) : vocab(vocab) {}
  9116. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  9117. // split string into utf8 chars
  9118. int index = 0;
  9119. size_t offs = 0;
  9120. while (offs < text.size()) {
  9121. llm_symbol sym;
  9122. size_t len = utf8_len(text[offs]);
  9123. sym.text = text.c_str() + offs;
  9124. sym.n = std::min(len, text.size() - offs);
  9125. offs += sym.n;
  9126. sym.prev = index - 1;
  9127. sym.next = offs == text.size() ? -1 : index + 1;
  9128. index++;
  9129. symbols.emplace_back(sym);
  9130. }
  9131. // seed the work queue with all possible 2-character tokens.
  9132. for (size_t i = 1; i < symbols.size(); ++i) {
  9133. try_add_bigram(i - 1, i);
  9134. }
  9135. // keep substituting the highest frequency pairs for as long as we can.
  9136. while (!work_queue.empty()) {
  9137. auto bigram = work_queue.top();
  9138. work_queue.pop();
  9139. auto & left_sym = symbols[bigram.left];
  9140. auto & right_sym = symbols[bigram.right];
  9141. // if one of the symbols already got merged, skip it.
  9142. if (left_sym.n == 0 || right_sym.n == 0 ||
  9143. left_sym.n + right_sym.n != bigram.size) {
  9144. continue;
  9145. }
  9146. // merge the right sym into the left one
  9147. left_sym.n += right_sym.n;
  9148. right_sym.n = 0;
  9149. //LLAMA_LOG_INFO("left = '%*s' size = %zu\n", (int) left_sym.n, left_sym.text, bigram.size);
  9150. // remove the right sym from the chain
  9151. left_sym.next = right_sym.next;
  9152. if (right_sym.next >= 0) {
  9153. symbols[right_sym.next].prev = bigram.left;
  9154. }
  9155. // find more substitutions
  9156. try_add_bigram(left_sym.prev, bigram.left);
  9157. try_add_bigram(bigram.left, left_sym.next);
  9158. }
  9159. for (int i = 0; i != -1; i = symbols[i].next) {
  9160. auto & symbol = symbols[i];
  9161. resegment(symbol, output);
  9162. }
  9163. }
  9164. private:
  9165. void resegment(llm_symbol & symbol, std::vector<llama_vocab::id> & output) {
  9166. auto text = std::string(symbol.text, symbol.n);
  9167. auto token = vocab.token_to_id.find(text);
  9168. // Do we need to support is_unused?
  9169. if (token != vocab.token_to_id.end()) {
  9170. output.push_back((*token).second);
  9171. return;
  9172. }
  9173. const auto p = rev_merge.find(text);
  9174. if (p == rev_merge.end()) {
  9175. // output any symbols that did not form tokens as bytes.
  9176. output.reserve(output.size() + symbol.n);
  9177. for (int j = 0; j < (int)symbol.n; ++j) {
  9178. llama_vocab::id token_id = llama_byte_to_token(vocab, symbol.text[j]);
  9179. output.push_back(token_id);
  9180. }
  9181. return;
  9182. }
  9183. resegment(symbols[p->second.first], output);
  9184. resegment(symbols[p->second.second], output);
  9185. }
  9186. void try_add_bigram(int left, int right) {
  9187. if (left == -1 || right == -1) {
  9188. return;
  9189. }
  9190. const std::string text = std::string(symbols[left].text, symbols[left].n + symbols[right].n);
  9191. auto token = vocab.token_to_id.find(text);
  9192. if (token == vocab.token_to_id.end()) {
  9193. return;
  9194. }
  9195. if (static_cast<size_t>((*token).second) >= vocab.id_to_token.size()) {
  9196. return;
  9197. }
  9198. const auto & tok_data = vocab.id_to_token[(*token).second];
  9199. llm_bigram_spm bigram;
  9200. bigram.left = left;
  9201. bigram.right = right;
  9202. bigram.score = tok_data.score;
  9203. bigram.size = text.size();
  9204. work_queue.push(bigram);
  9205. // Do we need to support is_unused?
  9206. rev_merge[text] = std::make_pair(left, right);
  9207. }
  9208. const llama_vocab & vocab;
  9209. std::vector<llm_symbol> symbols;
  9210. llm_bigram_spm::queue work_queue;
  9211. std::map<std::string, std::pair<int, int>> rev_merge;
  9212. };
  9213. // BPE tokenizer
  9214. // adapted from https://github.com/cmp-nct/ggllm.cpp [MIT License]
  9215. // tried to simplify unicode stuff, so most likely does not work 100% correctly!
  9216. // TODO: there are a lot of common parts between spm and bpe tokenizers, should be refactored and reused
  9217. struct llm_bigram_bpe {
  9218. struct comparator {
  9219. bool operator()(const llm_bigram_bpe & l, const llm_bigram_bpe & r) const {
  9220. return l.rank > r.rank || (l.rank == r.rank && l.left > r.left);
  9221. }
  9222. };
  9223. using queue_storage = std::vector<llm_bigram_bpe>;
  9224. using queue = std::priority_queue<llm_bigram_bpe, queue_storage, comparator>;
  9225. llm_symbol::index left;
  9226. llm_symbol::index right;
  9227. std::string text;
  9228. int rank;
  9229. size_t size;
  9230. };
  9231. struct llm_tokenizer_bpe {
  9232. llm_tokenizer_bpe(const llama_vocab & vocab): vocab(vocab) {}
  9233. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  9234. int final_prev_index = -1;
  9235. auto word_collection = bpe_gpt2_preprocess(text);
  9236. symbols_final.clear();
  9237. for (auto & word : word_collection) {
  9238. work_queue = llm_bigram_bpe::queue();
  9239. symbols.clear();
  9240. int index = 0;
  9241. size_t offset = 0;
  9242. while (offset < word.size()) {
  9243. llm_symbol sym;
  9244. size_t char_len = std::min(word.size() - offset, (size_t) ::utf8_len(word[offset]));
  9245. sym.text = word.c_str() + offset;
  9246. sym.n = char_len;
  9247. offset += sym.n;
  9248. sym.prev = index - 1;
  9249. sym.next = offset == word.size() ? -1 : index + 1;
  9250. index++;
  9251. symbols.emplace_back(sym);
  9252. }
  9253. for (size_t i = 1; i < symbols.size(); ++i) {
  9254. add_new_bigram(i - 1, i);
  9255. }
  9256. // build token(s)
  9257. while (!work_queue.empty()) {
  9258. auto bigram = work_queue.top();
  9259. work_queue.pop();
  9260. auto & left_symbol = symbols[bigram.left];
  9261. auto & right_symbol = symbols[bigram.right];
  9262. if (left_symbol.n == 0 || right_symbol.n == 0) {
  9263. continue;
  9264. }
  9265. std::string left_token = std::string(left_symbol.text, left_symbol.n);
  9266. std::string right_token = std::string(right_symbol.text, right_symbol.n);
  9267. if (left_token + right_token != bigram.text) {
  9268. continue; // Skip this bigram if it's outdated
  9269. }
  9270. // merge the right sym into the left one
  9271. left_symbol.n += right_symbol.n;
  9272. right_symbol.n = 0;
  9273. // remove the right sym from the chain
  9274. left_symbol.next = right_symbol.next;
  9275. if (right_symbol.next >= 0) {
  9276. symbols[right_symbol.next].prev = bigram.left;
  9277. }
  9278. add_new_bigram(left_symbol.prev, bigram.left); // left side of current symbol
  9279. add_new_bigram(bigram.left, left_symbol.next); // right side of current symbol
  9280. }
  9281. // add the finished tokens to the final list keeping correct order for next and prev
  9282. for (auto & sym : symbols) {
  9283. if (sym.n > 0) {
  9284. sym.prev = final_prev_index;
  9285. sym.next = -1;
  9286. if (final_prev_index != -1) {
  9287. symbols_final[final_prev_index].next = symbols_final.size();
  9288. }
  9289. symbols_final.emplace_back(sym);
  9290. final_prev_index = symbols_final.size() - 1;
  9291. }
  9292. }
  9293. }
  9294. symbols = symbols_final;
  9295. if (!symbols.empty()) {
  9296. for (int i = 0; i != -1; i = symbols[i].next) {
  9297. auto & symbol = symbols[i];
  9298. if (symbol.n == 0) {
  9299. continue;
  9300. }
  9301. const std::string str = std::string(symbol.text, symbol.n);
  9302. const auto token = vocab.token_to_id.find(str);
  9303. if (token == vocab.token_to_id.end()) {
  9304. for (auto j = str.begin(); j != str.end(); ++j) {
  9305. std::string byte_str(1, *j);
  9306. auto token_multibyte = vocab.token_to_id.find(byte_str);
  9307. if (token_multibyte == vocab.token_to_id.end()) {
  9308. throw std::runtime_error("ERROR: byte not found in vocab");
  9309. }
  9310. output.push_back((*token_multibyte).second);
  9311. }
  9312. } else {
  9313. output.push_back((*token).second);
  9314. }
  9315. }
  9316. }
  9317. }
  9318. private:
  9319. void add_new_bigram(int left, int right) {
  9320. if (left == -1 || right == -1) {
  9321. return;
  9322. }
  9323. std::string left_token = std::string(symbols[left].text, symbols[left].n);
  9324. std::string right_token = std::string(symbols[right].text, symbols[right].n);
  9325. int rank_found = -1;
  9326. rank_found = vocab.find_bpe_rank(left_token, right_token);
  9327. if (rank_found < 0) {
  9328. return;
  9329. }
  9330. llm_bigram_bpe bigram;
  9331. bigram.left = left;
  9332. bigram.right = right;
  9333. bigram.text = left_token + right_token;
  9334. bigram.size = left_token.size() + right_token.size();
  9335. bigram.rank = rank_found;
  9336. work_queue.push(bigram);
  9337. }
  9338. std::vector<std::string> bpe_gpt2_preprocess(const std::string & text) {
  9339. std::vector<std::string> bpe_words;
  9340. std::vector<std::string> bpe_encoded_words;
  9341. std::string token = "";
  9342. // GPT2 system regex: 's|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+
  9343. bool collecting_numeric = false;
  9344. bool collecting_letter = false;
  9345. bool collecting_special = false;
  9346. bool collecting_whitespace_lookahead = false;
  9347. bool collecting = false;
  9348. std::vector<std::string> text_utf;
  9349. text_utf.reserve(text.size());
  9350. bpe_words.reserve(text.size());
  9351. bpe_encoded_words.reserve(text.size());
  9352. const auto cpts = unicode_cpts_from_utf8(text);
  9353. for (size_t i = 0; i < cpts.size(); ++i)
  9354. text_utf.emplace_back(unicode_cpt_to_utf8(cpts[i]));
  9355. for (int i = 0; i < (int)text_utf.size(); i++) {
  9356. const std::string & utf_char = text_utf[i];
  9357. bool split_condition = false;
  9358. int bytes_remain = text_utf.size() - i;
  9359. // forward backward lookups
  9360. const std::string & utf_char_next = (i + 1 < (int)text_utf.size()) ? text_utf[i + 1] : "";
  9361. const std::string & utf_char_next_next = (i + 2 < (int)text_utf.size()) ? text_utf[i + 2] : "";
  9362. // handling contractions
  9363. if (!split_condition && bytes_remain >= 2) {
  9364. // 's|'t|'m|'d
  9365. if (utf_char == "\'" && (utf_char_next == "s" || utf_char_next == "t" || utf_char_next == "m" || utf_char_next == "d")) {
  9366. split_condition = true;
  9367. }
  9368. if (split_condition) {
  9369. if (token.size()) {
  9370. bpe_words.emplace_back(token); // push previous content as token
  9371. }
  9372. token = utf_char + utf_char_next;
  9373. bpe_words.emplace_back(token);
  9374. token = "";
  9375. i++;
  9376. continue;
  9377. }
  9378. }
  9379. if (!split_condition && bytes_remain >= 3) {
  9380. // 're|'ve|'ll
  9381. if (utf_char == "\'" && (
  9382. (utf_char_next == "r" && utf_char_next_next == "e") ||
  9383. (utf_char_next == "v" && utf_char_next_next == "e") ||
  9384. (utf_char_next == "l" && utf_char_next_next == "l"))
  9385. ) {
  9386. split_condition = true;
  9387. }
  9388. if (split_condition) {
  9389. // current token + next token can be defined
  9390. if (token.size()) {
  9391. bpe_words.emplace_back(token); // push previous content as token
  9392. }
  9393. token = utf_char + utf_char_next + utf_char_next_next;
  9394. bpe_words.emplace_back(token); // the contraction
  9395. token = "";
  9396. i += 2;
  9397. continue;
  9398. }
  9399. }
  9400. if (!split_condition && !collecting) {
  9401. if (unicode_cpt_type(utf_char) == CODEPOINT_TYPE_LETTER || (!token.size() && utf_char == " " && unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_LETTER)) {
  9402. collecting_letter = true;
  9403. collecting = true;
  9404. }
  9405. else if (unicode_cpt_type(utf_char) == CODEPOINT_TYPE_DIGIT || (!token.size() && utf_char == " " && unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  9406. collecting_numeric = true;
  9407. collecting = true;
  9408. }
  9409. else if (
  9410. ((unicode_cpt_type(utf_char) != CODEPOINT_TYPE_LETTER && unicode_cpt_type(utf_char) != CODEPOINT_TYPE_DIGIT) && (unicode_cpt_type(utf_char) != CODEPOINT_TYPE_WHITESPACE)) ||
  9411. (!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)
  9412. ) {
  9413. collecting_special = true;
  9414. collecting = true;
  9415. }
  9416. else if (unicode_cpt_type(utf_char) == CODEPOINT_TYPE_WHITESPACE && unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_WHITESPACE) {
  9417. collecting_whitespace_lookahead = true;
  9418. collecting = true;
  9419. }
  9420. else if (unicode_cpt_type(utf_char) == CODEPOINT_TYPE_WHITESPACE) {
  9421. split_condition = true;
  9422. }
  9423. }
  9424. else if (!split_condition && collecting) {
  9425. if (collecting_letter && unicode_cpt_type(utf_char) != CODEPOINT_TYPE_LETTER) {
  9426. split_condition = true;
  9427. }
  9428. else if (collecting_numeric && unicode_cpt_type(utf_char) != CODEPOINT_TYPE_DIGIT) {
  9429. split_condition = true;
  9430. }
  9431. 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)) {
  9432. split_condition = true;
  9433. }
  9434. else if (collecting_whitespace_lookahead && (unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_LETTER || unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  9435. split_condition = true;
  9436. }
  9437. }
  9438. if (utf_char_next == "") {
  9439. split_condition = true; // final
  9440. token += utf_char;
  9441. }
  9442. if (split_condition) {
  9443. if (token.size()) {
  9444. bpe_words.emplace_back(token);
  9445. }
  9446. token = utf_char;
  9447. collecting = false;
  9448. collecting_letter = false;
  9449. collecting_numeric = false;
  9450. collecting_special = false;
  9451. collecting_whitespace_lookahead = false;
  9452. }
  9453. else {
  9454. token += utf_char;
  9455. }
  9456. }
  9457. for (std::string & word : bpe_words) {
  9458. std::string encoded_token = "";
  9459. for (char & c : word) {
  9460. encoded_token += unicode_byte_to_utf8(c);
  9461. }
  9462. bpe_encoded_words.emplace_back(encoded_token);
  9463. }
  9464. return bpe_encoded_words;
  9465. }
  9466. const llama_vocab & vocab;
  9467. std::vector<llm_symbol> symbols;
  9468. std::vector<llm_symbol> symbols_final;
  9469. llm_bigram_bpe::queue work_queue;
  9470. };
  9471. struct llm_tokenizer_wpm {
  9472. llm_tokenizer_wpm(const llama_vocab & vocab): vocab(vocab) {}
  9473. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  9474. auto * token_map = &vocab.token_to_id;
  9475. // normalize and split by whitespace
  9476. std::vector<std::string> words = preprocess(text);
  9477. // bos token prepended already
  9478. // find the longest tokens that form the words
  9479. for (const std::string &word : words) {
  9480. // skip empty words
  9481. if (word.size() == 0) {
  9482. continue;
  9483. }
  9484. // prepend phantom space
  9485. std::string word1 = "\xe2\x96\x81" + word;
  9486. int n = word1.size();
  9487. // we're at the start of a new word
  9488. int i = 0;
  9489. bool match_any = false;
  9490. // move through character position in word
  9491. while (i < n) {
  9492. // loop through possible match length
  9493. bool match = false;
  9494. for (int j = n; j > i; j--) {
  9495. auto it = token_map->find(word1.substr(i, j - i));
  9496. if (it != token_map->end()) {
  9497. output.push_back(it->second);
  9498. match = true;
  9499. match_any = true;
  9500. i = j;
  9501. break;
  9502. }
  9503. }
  9504. // must be an unknown character
  9505. if (!match) {
  9506. i++;
  9507. }
  9508. }
  9509. // we didn't find any matches for this word
  9510. if (!match_any) {
  9511. output.push_back(vocab.special_unk_id);
  9512. }
  9513. }
  9514. }
  9515. std::vector<std::string> preprocess(const std::string & text) {
  9516. std::vector<uint32_t> cpts_nfd = unicode_cpts_normalize_nfd(unicode_cpts_from_utf8(text));
  9517. // strip accents, strip control, uniformize whitespace,
  9518. // to lowercase, pad chinese characters, pad punctuation
  9519. std::string new_str = "";
  9520. for (uint32_t code : cpts_nfd) {
  9521. int type = unicode_cpt_type(code);
  9522. if (type == CODEPOINT_TYPE_ACCENT_MARK || type == CODEPOINT_TYPE_CONTROL) {
  9523. continue;
  9524. }
  9525. code = unicode_tolower(code);
  9526. if (type == CODEPOINT_TYPE_WHITESPACE) {
  9527. code = ' ';
  9528. }
  9529. std::string s = unicode_cpt_to_utf8(code);
  9530. if (type == CODEPOINT_TYPE_PUNCTUATION || is_ascii_punct(code) || is_chinese_char(code)) {
  9531. new_str += " ";
  9532. new_str += s;
  9533. new_str += " ";
  9534. } else {
  9535. new_str += s;
  9536. }
  9537. }
  9538. // split by whitespace
  9539. uint64_t l = 0;
  9540. uint64_t r = 0;
  9541. std::vector<std::string> words;
  9542. while (r < new_str.size()) {
  9543. // if is whitespace
  9544. if (isspace(new_str[r], std::locale::classic())) {
  9545. if (r > l) words.push_back(new_str.substr(l, (r - l)));
  9546. l = r + 1;
  9547. r = l;
  9548. } else {
  9549. r += 1;
  9550. }
  9551. }
  9552. if (r > l) {
  9553. words.push_back(new_str.substr(l, (r - l)));
  9554. }
  9555. return words;
  9556. }
  9557. bool is_ascii_punct(uint32_t code) {
  9558. if (code > 0xFF) {
  9559. return false;
  9560. }
  9561. auto c = char(static_cast<unsigned char>(code));
  9562. return ispunct(c, std::locale::classic());
  9563. }
  9564. bool is_chinese_char(uint32_t cpt) {
  9565. if ((cpt >= 0x4E00 && cpt <= 0x9FFF) ||
  9566. (cpt >= 0x3400 && cpt <= 0x4DBF) ||
  9567. (cpt >= 0x20000 && cpt <= 0x2A6DF) ||
  9568. (cpt >= 0x2A700 && cpt <= 0x2B73F) ||
  9569. (cpt >= 0x2B740 && cpt <= 0x2B81F) ||
  9570. (cpt >= 0x2B920 && cpt <= 0x2CEAF) || // this should be 0x2B820 but in hf rust code it is 0x2B920
  9571. (cpt >= 0xF900 && cpt <= 0xFAFF) ||
  9572. (cpt >= 0x2F800 && cpt <= 0x2FA1F) ||
  9573. (cpt >= 0x3000 && cpt <= 0x303F) ||
  9574. (cpt >= 0xFF00 && cpt <= 0xFFEF)) {
  9575. return true; // NOLINT
  9576. }
  9577. return false;
  9578. }
  9579. const llama_vocab & vocab;
  9580. };
  9581. typedef enum FRAGMENT_BUFFER_VARIANT_TYPE {
  9582. FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN,
  9583. FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT
  9584. } FRAGMENT_BUFFER_VARIANT_TYPE;
  9585. struct fragment_buffer_variant {
  9586. fragment_buffer_variant(llama_vocab::id _token)
  9587. :
  9588. type(FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN),
  9589. token(_token),
  9590. raw_text(_dummy),
  9591. offset(0),
  9592. length(0) {}
  9593. fragment_buffer_variant(const std::string & _raw_text, int64_t _offset, int64_t _length)
  9594. :
  9595. type(FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT),
  9596. token((llama_vocab::id) - 1),
  9597. raw_text(_raw_text),
  9598. offset(_offset),
  9599. length(_length){
  9600. GGML_ASSERT(_offset >= 0);
  9601. GGML_ASSERT(_length >= 1);
  9602. GGML_ASSERT(offset + length <= raw_text.length());
  9603. }
  9604. const FRAGMENT_BUFFER_VARIANT_TYPE type;
  9605. const llama_vocab::id token;
  9606. const std::string _dummy;
  9607. const std::string & raw_text;
  9608. const uint64_t offset;
  9609. const uint64_t length;
  9610. };
  9611. // #define PRETOKENIZERDEBUG
  9612. static void tokenizer_st_partition(const llama_vocab & vocab, std::forward_list<fragment_buffer_variant> & buffer) {
  9613. // for each special token
  9614. for (const auto & st: vocab.special_tokens_cache) {
  9615. const auto & special_token = st.first;
  9616. const auto & special_id = st.second;
  9617. // for each text fragment
  9618. std::forward_list<fragment_buffer_variant>::iterator it = buffer.begin();
  9619. while (it != buffer.end()) {
  9620. auto & fragment = (*it);
  9621. // if a fragment is text ( not yet processed )
  9622. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  9623. auto * raw_text = &(fragment.raw_text);
  9624. auto raw_text_base_offset = fragment.offset;
  9625. auto raw_text_base_length = fragment.length;
  9626. // loop over the text
  9627. while (true) {
  9628. // find the first occurrence of a given special token in this fragment
  9629. // passing offset argument only limit the "search area" but match coordinates
  9630. // are still relative to the source full raw_text
  9631. auto match = raw_text->find(special_token, raw_text_base_offset);
  9632. // no occurrences found, stop processing this fragment for a given special token
  9633. if (match == std::string::npos) break;
  9634. // check if match is within bounds of offset <-> length
  9635. if (match + special_token.length() > raw_text_base_offset + raw_text_base_length) break;
  9636. #ifdef PRETOKENIZERDEBUG
  9637. 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());
  9638. #endif
  9639. auto source = std::distance(buffer.begin(), it);
  9640. // if match is further than base offset
  9641. // then we have some text to the left of it
  9642. if (match > raw_text_base_offset) {
  9643. // left
  9644. const int64_t left_reminder_offset = raw_text_base_offset + 0;
  9645. const int64_t left_reminder_length = match - raw_text_base_offset;
  9646. buffer.emplace_after(it, (*raw_text), left_reminder_offset, left_reminder_length);
  9647. #ifdef PRETOKENIZERDEBUG
  9648. 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());
  9649. #endif
  9650. it++;
  9651. }
  9652. // special token
  9653. buffer.emplace_after(it, special_id);
  9654. it++;
  9655. // right
  9656. if (match + special_token.length() < raw_text_base_offset + raw_text_base_length) {
  9657. const int64_t right_reminder_offset = match + special_token.length();
  9658. const int64_t right_reminder_length = raw_text_base_length - ((match - raw_text_base_offset) + special_token.length());
  9659. buffer.emplace_after(it, (*raw_text), right_reminder_offset, right_reminder_length);
  9660. #ifdef PRETOKENIZERDEBUG
  9661. 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());
  9662. #endif
  9663. it++;
  9664. if (source == 0) {
  9665. buffer.erase_after(buffer.before_begin());
  9666. } else {
  9667. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  9668. }
  9669. // repeat for the right side
  9670. raw_text_base_offset = right_reminder_offset;
  9671. raw_text_base_length = right_reminder_length;
  9672. #ifdef PRETOKENIZERDEBUG
  9673. 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());
  9674. #endif
  9675. } else {
  9676. if (source == 0) {
  9677. buffer.erase_after(buffer.before_begin());
  9678. } else {
  9679. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  9680. }
  9681. break;
  9682. }
  9683. }
  9684. }
  9685. it++;
  9686. }
  9687. }
  9688. }
  9689. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool add_special, bool parse_special) {
  9690. std::vector<llama_vocab::id> output;
  9691. std::forward_list<fragment_buffer_variant> fragment_buffer;
  9692. if (!raw_text.empty()) {
  9693. fragment_buffer.emplace_front(raw_text, 0, raw_text.length());
  9694. if (parse_special) tokenizer_st_partition(vocab, fragment_buffer);
  9695. }
  9696. switch (vocab.type) {
  9697. case LLAMA_VOCAB_TYPE_SPM:
  9698. {
  9699. // OG tokenizer behavior:
  9700. //
  9701. // tokenizer.encode('', add_special_tokens=True) returns [1]
  9702. // tokenizer.encode('', add_special_tokens=False) returns []
  9703. if (add_special && vocab.special_add_bos != 0) {
  9704. GGML_ASSERT(vocab.special_bos_id != -1);
  9705. output.push_back(vocab.special_bos_id);
  9706. }
  9707. for (const auto & fragment : fragment_buffer) {
  9708. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  9709. // without adding this leading whitespace, we do not get the same results as the original tokenizer
  9710. // TODO: It's likely possible to get rid of this string copy entirely
  9711. // by modifying llm_tokenizer_x to operate with string offsets like pre-tokenizer
  9712. // and passing 'add space prefix' as bool argument
  9713. //
  9714. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  9715. if (&fragment == &fragment_buffer.front()) {
  9716. if (vocab.add_space_prefix) {
  9717. raw_text = " " + raw_text; // prefix with space if the first token is not special
  9718. }
  9719. }
  9720. #ifdef PRETOKENIZERDEBUG
  9721. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  9722. #endif
  9723. llm_tokenizer_spm tokenizer(vocab);
  9724. llama_escape_whitespace(raw_text);
  9725. tokenizer.tokenize(raw_text, output);
  9726. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  9727. output.push_back(fragment.token);
  9728. }
  9729. }
  9730. if (add_special && vocab.special_add_eos == 1) {
  9731. GGML_ASSERT(vocab.special_eos_id != -1);
  9732. output.push_back(vocab.special_eos_id);
  9733. }
  9734. } break;
  9735. case LLAMA_VOCAB_TYPE_BPE:
  9736. {
  9737. if (add_special && vocab.special_add_bos == 1) {
  9738. GGML_ASSERT(vocab.special_bos_id != -1);
  9739. output.push_back(vocab.special_bos_id);
  9740. }
  9741. for (const auto & fragment : fragment_buffer) {
  9742. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  9743. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  9744. #ifdef PRETOKENIZERDEBUG
  9745. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  9746. #endif
  9747. llm_tokenizer_bpe tokenizer(vocab);
  9748. tokenizer.tokenize(raw_text, output);
  9749. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  9750. output.push_back(fragment.token);
  9751. }
  9752. }
  9753. GGML_ASSERT(vocab.special_add_eos != 1);
  9754. } break;
  9755. case LLAMA_VOCAB_TYPE_WPM:
  9756. {
  9757. if (add_special) {
  9758. GGML_ASSERT(vocab.special_cls_id != -1);
  9759. output.push_back(vocab.special_cls_id);
  9760. }
  9761. for (const auto & fragment : fragment_buffer) {
  9762. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  9763. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  9764. #ifdef PRETOKENIZERDEBUG
  9765. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  9766. #endif
  9767. llm_tokenizer_wpm tokenizer(vocab);
  9768. tokenizer.tokenize(raw_text, output);
  9769. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  9770. output.push_back(fragment.token);
  9771. }
  9772. }
  9773. if (add_special) {
  9774. GGML_ASSERT(vocab.special_sep_id != -1);
  9775. output.push_back(vocab.special_sep_id);
  9776. }
  9777. } break;
  9778. case LLAMA_VOCAB_TYPE_NONE:
  9779. GGML_ASSERT(false);
  9780. }
  9781. return output;
  9782. }
  9783. //
  9784. // grammar - internal
  9785. //
  9786. // Decodes a UTF-8 string which may end in an incomplete sequence. Adds a terminating 0 for use as
  9787. // pointer. If an invalid sequence is encountered, returns `llama_partial_utf8.n_remain == -1`.
  9788. std::pair<std::vector<uint32_t>, llama_partial_utf8> decode_utf8(
  9789. const std::string & src,
  9790. llama_partial_utf8 partial_start) {
  9791. static const int lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 3, 4 };
  9792. const char * pos = src.c_str();
  9793. std::vector<uint32_t> code_points;
  9794. // common english strings have the same number of codepoints and bytes. `+ 1` for the terminating 0.
  9795. code_points.reserve(src.size() + 1);
  9796. uint32_t value = partial_start.value;
  9797. int n_remain = partial_start.n_remain;
  9798. // continue previous decode, if applicable
  9799. while (*pos != 0 && n_remain > 0) {
  9800. uint8_t next_byte = static_cast<uint8_t>(*pos);
  9801. if ((next_byte >> 6) != 2) {
  9802. // invalid sequence, abort
  9803. code_points.push_back(0);
  9804. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, -1 });
  9805. }
  9806. value = (value << 6) + (next_byte & 0x3F);
  9807. ++pos;
  9808. --n_remain;
  9809. }
  9810. if (partial_start.n_remain > 0 && n_remain == 0) {
  9811. code_points.push_back(value);
  9812. }
  9813. // decode any subsequent utf-8 sequences, which may end in an incomplete one
  9814. while (*pos != 0) {
  9815. uint8_t first_byte = static_cast<uint8_t>(*pos);
  9816. uint8_t highbits = first_byte >> 4;
  9817. n_remain = lookup[highbits] - 1;
  9818. if (n_remain < 0) {
  9819. // invalid sequence, abort
  9820. code_points.clear();
  9821. code_points.push_back(0);
  9822. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, n_remain });
  9823. }
  9824. uint8_t mask = (1 << (7 - n_remain)) - 1;
  9825. value = first_byte & mask;
  9826. ++pos;
  9827. while (*pos != 0 && n_remain > 0) {
  9828. value = (value << 6) + (static_cast<uint8_t>(*pos) & 0x3F);
  9829. ++pos;
  9830. --n_remain;
  9831. }
  9832. if (n_remain == 0) {
  9833. code_points.push_back(value);
  9834. }
  9835. }
  9836. code_points.push_back(0);
  9837. return std::make_pair(std::move(code_points), llama_partial_utf8{ value, n_remain });
  9838. }
  9839. // returns true iff pos points to the end of one of the definitions of a rule
  9840. static bool llama_grammar_is_end_of_sequence(const llama_grammar_element * pos) {
  9841. switch (pos->type) {
  9842. case LLAMA_GRETYPE_END: return true; // NOLINT
  9843. case LLAMA_GRETYPE_ALT: return true; // NOLINT
  9844. default: return false;
  9845. }
  9846. }
  9847. // returns true iff chr satisfies the char range at pos (regular or inverse range)
  9848. // asserts that pos is pointing to a char range element
  9849. static std::pair<bool, const llama_grammar_element *> llama_grammar_match_char(
  9850. const llama_grammar_element * pos,
  9851. const uint32_t chr) {
  9852. bool found = false;
  9853. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  9854. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT); // NOLINT
  9855. do {
  9856. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  9857. // inclusive range, e.g. [a-z]
  9858. found = found || (pos->value <= chr && chr <= pos[1].value);
  9859. pos += 2;
  9860. } else {
  9861. // exact char match, e.g. [a] or "a"
  9862. found = found || pos->value == chr;
  9863. pos += 1;
  9864. }
  9865. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  9866. return std::make_pair(found == is_positive_char, pos);
  9867. }
  9868. // returns true iff some continuation of the given partial UTF-8 sequence could satisfy the char
  9869. // range at pos (regular or inverse range)
  9870. // asserts that pos is pointing to a char range element
  9871. static bool llama_grammar_match_partial_char(
  9872. const llama_grammar_element * pos,
  9873. const llama_partial_utf8 partial_utf8) {
  9874. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  9875. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT);
  9876. uint32_t partial_value = partial_utf8.value;
  9877. int n_remain = partial_utf8.n_remain;
  9878. // invalid sequence or 7-bit char split across 2 bytes (overlong)
  9879. if (n_remain < 0 || (n_remain == 1 && partial_value < 2)) {
  9880. return false;
  9881. }
  9882. // range of possible code points this partial UTF-8 sequence could complete to
  9883. uint32_t low = partial_value << (n_remain * 6);
  9884. uint32_t high = low | ((1 << (n_remain * 6)) - 1);
  9885. if (low == 0) {
  9886. if (n_remain == 2) {
  9887. low = 1 << 11;
  9888. } else if (n_remain == 3) {
  9889. low = 1 << 16;
  9890. }
  9891. }
  9892. do {
  9893. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  9894. // inclusive range, e.g. [a-z]
  9895. if (pos->value <= high && low <= pos[1].value) {
  9896. return is_positive_char;
  9897. }
  9898. pos += 2;
  9899. } else {
  9900. // exact char match, e.g. [a] or "a"
  9901. if (low <= pos->value && pos->value <= high) {
  9902. return is_positive_char;
  9903. }
  9904. pos += 1;
  9905. }
  9906. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  9907. return !is_positive_char;
  9908. }
  9909. // transforms a grammar pushdown stack into N possible stacks, all ending
  9910. // at a character range (terminal element)
  9911. static void llama_grammar_advance_stack(
  9912. const std::vector<std::vector<llama_grammar_element>> & rules,
  9913. const std::vector<const llama_grammar_element *> & stack,
  9914. std::vector<std::vector<const llama_grammar_element *>> & new_stacks) {
  9915. if (stack.empty()) {
  9916. if (std::find(new_stacks.begin(), new_stacks.end(), stack) == new_stacks.end()) {
  9917. new_stacks.emplace_back(stack);
  9918. }
  9919. return;
  9920. }
  9921. const llama_grammar_element * pos = stack.back();
  9922. switch (pos->type) {
  9923. case LLAMA_GRETYPE_RULE_REF: {
  9924. const size_t rule_id = static_cast<size_t>(pos->value);
  9925. const llama_grammar_element * subpos = rules[rule_id].data();
  9926. do {
  9927. // init new stack without the top (pos)
  9928. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  9929. if (!llama_grammar_is_end_of_sequence(pos + 1)) {
  9930. // if this rule ref is followed by another element, add that to stack
  9931. new_stack.push_back(pos + 1);
  9932. }
  9933. if (!llama_grammar_is_end_of_sequence(subpos)) {
  9934. // if alternate is nonempty, add to stack
  9935. new_stack.push_back(subpos);
  9936. }
  9937. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  9938. while (!llama_grammar_is_end_of_sequence(subpos)) {
  9939. // scan to end of alternate def
  9940. subpos++;
  9941. }
  9942. if (subpos->type == LLAMA_GRETYPE_ALT) {
  9943. // there's another alternate def of this rule to process
  9944. subpos++;
  9945. } else {
  9946. break;
  9947. }
  9948. } while (true);
  9949. break;
  9950. }
  9951. case LLAMA_GRETYPE_CHAR:
  9952. case LLAMA_GRETYPE_CHAR_NOT:
  9953. if (std::find(new_stacks.begin(), new_stacks.end(), stack) == new_stacks.end()) {
  9954. // only add the stack if it's not a duplicate of one we already have
  9955. new_stacks.emplace_back(stack);
  9956. }
  9957. break;
  9958. default:
  9959. // end of alternate (LLAMA_GRETYPE_END, LLAMA_GRETYPE_ALT) or middle of char range
  9960. // (LLAMA_GRETYPE_CHAR_ALT, LLAMA_GRETYPE_CHAR_RNG_UPPER); stack should never be left on
  9961. // those
  9962. GGML_ASSERT(false);
  9963. }
  9964. }
  9965. // takes a set of possible pushdown stacks on a grammar, which are required to
  9966. // be positioned at a character range (see `llama_grammar_advance_stack`), and
  9967. // produces the N possible stacks if the given char is accepted at those
  9968. // positions
  9969. void llama_grammar_accept(
  9970. const std::vector<std::vector<llama_grammar_element>> & rules,
  9971. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  9972. const uint32_t chr,
  9973. std::vector<std::vector<const llama_grammar_element *>> & new_stacks) {
  9974. new_stacks.clear();
  9975. for (const auto & stack : stacks) {
  9976. if (stack.empty()) {
  9977. continue;
  9978. }
  9979. auto match = llama_grammar_match_char(stack.back(), chr);
  9980. if (match.first) {
  9981. const llama_grammar_element * pos = match.second;
  9982. // update top of stack to next element, if any
  9983. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  9984. if (!llama_grammar_is_end_of_sequence(pos)) {
  9985. new_stack.push_back(pos);
  9986. }
  9987. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  9988. }
  9989. }
  9990. }
  9991. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  9992. const std::vector<std::vector<llama_grammar_element>> & rules,
  9993. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  9994. const std::vector<llama_grammar_candidate> & candidates);
  9995. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates_for_stack(
  9996. const std::vector<std::vector<llama_grammar_element>> & rules,
  9997. const std::vector<const llama_grammar_element *> & stack,
  9998. const std::vector<llama_grammar_candidate> & candidates) {
  9999. std::vector<llama_grammar_candidate> rejects;
  10000. rejects.reserve(candidates.size());
  10001. if (stack.empty()) {
  10002. for (const auto & tok : candidates) {
  10003. if (*tok.code_points != 0 || tok.partial_utf8.n_remain != 0) {
  10004. rejects.push_back(tok);
  10005. }
  10006. }
  10007. return rejects;
  10008. }
  10009. const llama_grammar_element * stack_pos = stack.back();
  10010. std::vector<llama_grammar_candidate> next_candidates;
  10011. next_candidates.reserve(candidates.size());
  10012. for (const auto & tok : candidates) {
  10013. if (*tok.code_points == 0) {
  10014. // reached end of full codepoints in token, reject iff it ended in a partial sequence
  10015. // that cannot satisfy this position in grammar
  10016. if (tok.partial_utf8.n_remain != 0 &&
  10017. !llama_grammar_match_partial_char(stack_pos, tok.partial_utf8)) {
  10018. rejects.push_back(tok);
  10019. }
  10020. } else if (llama_grammar_match_char(stack_pos, *tok.code_points).first) {
  10021. next_candidates.push_back({ tok.index, tok.code_points + 1, tok.partial_utf8 });
  10022. } else {
  10023. rejects.push_back(tok);
  10024. }
  10025. }
  10026. const auto * stack_pos_after = llama_grammar_match_char(stack_pos, 0).second;
  10027. // update top of stack to next element, if any
  10028. std::vector<const llama_grammar_element *> stack_after(stack.begin(), stack.end() - 1);
  10029. if (!llama_grammar_is_end_of_sequence(stack_pos_after)) {
  10030. stack_after.push_back(stack_pos_after);
  10031. }
  10032. std::vector<std::vector<const llama_grammar_element *>> next_stacks;
  10033. llama_grammar_advance_stack(rules, stack_after, next_stacks);
  10034. auto next_rejects = llama_grammar_reject_candidates(rules, next_stacks, next_candidates);
  10035. for (const auto & tok : next_rejects) {
  10036. rejects.push_back({ tok.index, tok.code_points - 1, tok.partial_utf8 });
  10037. }
  10038. return rejects;
  10039. }
  10040. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  10041. const std::vector<std::vector<llama_grammar_element>> & rules,
  10042. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  10043. const std::vector<llama_grammar_candidate> & candidates) {
  10044. GGML_ASSERT(!stacks.empty()); // REVIEW
  10045. if (candidates.empty()) {
  10046. return std::vector<llama_grammar_candidate>();
  10047. }
  10048. auto rejects = llama_grammar_reject_candidates_for_stack(rules, stacks.front(), candidates);
  10049. for (size_t i = 1, size = stacks.size(); i < size; ++i) {
  10050. rejects = llama_grammar_reject_candidates_for_stack(rules, stacks[i], rejects);
  10051. }
  10052. return rejects;
  10053. }
  10054. //
  10055. // grammar - external
  10056. //
  10057. struct llama_grammar * llama_grammar_init(
  10058. const llama_grammar_element ** rules,
  10059. size_t n_rules,
  10060. size_t start_rule_index) {
  10061. const llama_grammar_element * pos;
  10062. // copy rule definitions into vectors
  10063. std::vector<std::vector<llama_grammar_element>> vec_rules(n_rules);
  10064. for (size_t i = 0; i < n_rules; i++) {
  10065. for (pos = rules[i]; pos->type != LLAMA_GRETYPE_END; pos++) {
  10066. vec_rules[i].push_back(*pos);
  10067. }
  10068. vec_rules[i].push_back({LLAMA_GRETYPE_END, 0});
  10069. }
  10070. // loop over alternates of start rule to build initial stacks
  10071. std::vector<std::vector<const llama_grammar_element *>> stacks;
  10072. pos = vec_rules[start_rule_index].data();
  10073. do {
  10074. std::vector<const llama_grammar_element *> stack;
  10075. if (!llama_grammar_is_end_of_sequence(pos)) {
  10076. // if alternate is nonempty, add to stack
  10077. stack.push_back(pos);
  10078. }
  10079. llama_grammar_advance_stack(vec_rules, stack, stacks);
  10080. while (!llama_grammar_is_end_of_sequence(pos)) {
  10081. // scan to end of alternate def
  10082. pos++;
  10083. }
  10084. if (pos->type == LLAMA_GRETYPE_ALT) {
  10085. // there's another alternate def of this rule to process
  10086. pos++;
  10087. } else {
  10088. break;
  10089. }
  10090. } while (true);
  10091. return new llama_grammar{ std::move(vec_rules), std::move(stacks), {} };
  10092. }
  10093. void llama_grammar_free(struct llama_grammar * grammar) {
  10094. delete grammar;
  10095. }
  10096. struct llama_grammar * llama_grammar_copy(const struct llama_grammar * grammar) {
  10097. llama_grammar * result = new llama_grammar{ grammar->rules, grammar->stacks, grammar->partial_utf8 };
  10098. // redirect elements in stacks to point to new rules
  10099. for (size_t is = 0; is < result->stacks.size(); is++) {
  10100. for (size_t ie = 0; ie < result->stacks[is].size(); ie++) {
  10101. for (size_t ir0 = 0; ir0 < grammar->rules.size(); ir0++) {
  10102. for (size_t ir1 = 0; ir1 < grammar->rules[ir0].size(); ir1++) {
  10103. if (grammar->stacks[is][ie] == &grammar->rules[ir0][ir1]) {
  10104. result->stacks[is][ie] = &result->rules[ir0][ir1];
  10105. }
  10106. }
  10107. }
  10108. }
  10109. }
  10110. return result;
  10111. }
  10112. //
  10113. // sampling
  10114. //
  10115. void llama_set_rng_seed(struct llama_context * ctx, uint32_t seed) {
  10116. if (seed == LLAMA_DEFAULT_SEED) {
  10117. seed = time(NULL);
  10118. }
  10119. ctx->rng.seed(seed);
  10120. }
  10121. void llama_sample_softmax(struct llama_context * ctx, llama_token_data_array * candidates) {
  10122. GGML_ASSERT(candidates->size > 0);
  10123. const int64_t t_start_sample_us = ggml_time_us();
  10124. // Sort the logits in descending order
  10125. if (!candidates->sorted) {
  10126. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  10127. return a.logit > b.logit;
  10128. });
  10129. candidates->sorted = true;
  10130. }
  10131. float max_l = candidates->data[0].logit;
  10132. float cum_sum = 0.0f;
  10133. for (size_t i = 0; i < candidates->size; ++i) {
  10134. float p = expf(candidates->data[i].logit - max_l);
  10135. candidates->data[i].p = p;
  10136. cum_sum += p;
  10137. }
  10138. for (size_t i = 0; i < candidates->size; ++i) {
  10139. candidates->data[i].p /= cum_sum;
  10140. }
  10141. if (ctx) {
  10142. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10143. }
  10144. }
  10145. void llama_sample_top_k(struct llama_context * ctx, llama_token_data_array * candidates, int32_t k, size_t min_keep) {
  10146. // TODO: move bucket sort to separate function so that top_p/tail_free/typical/softmax first is equally fast
  10147. // if (k >= (int32_t)candidates->size) {
  10148. // return;
  10149. // }
  10150. const int64_t t_start_sample_us = ggml_time_us();
  10151. if (k <= 0) {
  10152. k = candidates->size;
  10153. }
  10154. k = std::max(k, (int) min_keep);
  10155. k = std::min(k, (int) candidates->size);
  10156. // Sort scores in descending order
  10157. if (!candidates->sorted) {
  10158. auto comp = [](const llama_token_data & a, const llama_token_data & b) {
  10159. return a.logit > b.logit;
  10160. };
  10161. if (k <= 128) {
  10162. std::partial_sort(candidates->data, candidates->data + k, candidates->data + candidates->size, comp);
  10163. } else {
  10164. constexpr int nbuckets = 128;
  10165. constexpr float bucket_low = -10.0f;
  10166. constexpr float bucket_high = 10.0f;
  10167. constexpr float bucket_scale = nbuckets/(bucket_high - bucket_low);
  10168. constexpr float bucker_inter = -bucket_low * bucket_scale;
  10169. std::vector<int> bucket_idx(candidates->size);
  10170. std::vector<int> histo(nbuckets, 0);
  10171. for (int i = 0; i < (int)candidates->size; ++i) {
  10172. const float val = candidates->data[i].logit;
  10173. int ib = int(bucket_scale * val + bucker_inter); //nbuckets * (val - bucket_low) / (bucket_high - bucket_low);
  10174. ib = std::max(0, std::min(nbuckets-1, ib));
  10175. bucket_idx[i] = ib;
  10176. ++histo[ib];
  10177. }
  10178. int nhave = 0;
  10179. int ib = nbuckets - 1;
  10180. for ( ; ib >= 0; --ib) {
  10181. nhave += histo[ib];
  10182. if (nhave >= k) break;
  10183. }
  10184. std::vector<llama_token_data> tmp_tokens(nhave);
  10185. auto ptr = tmp_tokens.data();
  10186. std::vector<llama_token_data*> bucket_ptrs;
  10187. bucket_ptrs.reserve(nbuckets - ib);
  10188. for (int j = nbuckets - 1; j >= ib; --j) {
  10189. bucket_ptrs.push_back(ptr);
  10190. ptr += histo[j];
  10191. }
  10192. for (int i = 0; i < (int)candidates->size; ++i) {
  10193. int j = bucket_idx[i];
  10194. if (j >= ib) {
  10195. *bucket_ptrs[nbuckets-1-j]++ = candidates->data[i];
  10196. }
  10197. }
  10198. ptr = tmp_tokens.data();
  10199. int ndone = 0;
  10200. for (int j = nbuckets-1; j > ib; --j) {
  10201. std::sort(ptr, ptr + histo[j], comp);
  10202. ptr += histo[j];
  10203. ndone += histo[j];
  10204. }
  10205. std::partial_sort(ptr, ptr + k - ndone, ptr + histo[ib], comp);
  10206. std::memcpy(candidates->data, tmp_tokens.data(), k*sizeof(llama_token_data));
  10207. }
  10208. candidates->sorted = true;
  10209. }
  10210. candidates->size = k;
  10211. if (ctx) {
  10212. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10213. }
  10214. }
  10215. void llama_sample_top_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  10216. if (p >= 1.0f) {
  10217. return;
  10218. }
  10219. llama_sample_softmax(ctx, candidates);
  10220. const int64_t t_start_sample_us = ggml_time_us();
  10221. // Compute the cumulative probabilities
  10222. float cum_sum = 0.0f;
  10223. size_t last_idx = candidates->size;
  10224. for (size_t i = 0; i < candidates->size; ++i) {
  10225. cum_sum += candidates->data[i].p;
  10226. // Check if the running sum is at least p or if we have kept at least min_keep tokens
  10227. // we set the last index to i+1 to indicate that the current iterate should be included in the set
  10228. if (cum_sum >= p && i + 1 >= min_keep) {
  10229. last_idx = i + 1;
  10230. break;
  10231. }
  10232. }
  10233. // Resize the output vector to keep only the top-p tokens
  10234. candidates->size = last_idx;
  10235. if (ctx) {
  10236. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10237. }
  10238. }
  10239. void llama_sample_min_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  10240. if (p <= 0.0f || !candidates->size) {
  10241. return;
  10242. }
  10243. const int64_t t_start_sample_us = ggml_time_us();
  10244. bool min_p_applied = false;
  10245. // if the candidates aren't sorted, try the unsorted implementation first
  10246. if (!candidates->sorted) {
  10247. std::vector<llama_token_data> filtered_tokens;
  10248. float max_logit = -FLT_MAX;
  10249. for (size_t i = 0; i < candidates->size; ++i) {
  10250. max_logit = std::max(max_logit, candidates->data[i].logit);
  10251. }
  10252. const float min_logit = max_logit + logf(p); // min logit for p_i >= p * p_max
  10253. for (size_t i = 0; i < candidates->size; ++i) {
  10254. if (candidates->data[i].logit >= min_logit) {
  10255. filtered_tokens.push_back(candidates->data[i]);
  10256. }
  10257. }
  10258. // if we have enough values the operation was a success
  10259. if (filtered_tokens.size() >= min_keep) {
  10260. memcpy(candidates->data, filtered_tokens.data(), filtered_tokens.size()*sizeof(llama_token_data));
  10261. candidates->size = filtered_tokens.size();
  10262. min_p_applied = true;
  10263. }
  10264. }
  10265. // if the candidates are sorted or the unsorted implementation failed, use this implementation
  10266. if (!min_p_applied) {
  10267. // Sort the logits in descending order
  10268. if (!candidates->sorted) {
  10269. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  10270. return a.logit > b.logit;
  10271. });
  10272. candidates->sorted = true;
  10273. }
  10274. const float min_logit = candidates->data[0].logit + logf(p); // min logit for p_i >= p * p_max
  10275. size_t i = 1; // first token always matches
  10276. for (; i < candidates->size; ++i) {
  10277. if (candidates->data[i].logit < min_logit && i >= min_keep) {
  10278. break; // prob too small
  10279. }
  10280. }
  10281. // Resize the output vector to keep only the matching tokens
  10282. candidates->size = i;
  10283. }
  10284. if (ctx) {
  10285. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10286. }
  10287. }
  10288. void llama_sample_tail_free(struct llama_context * ctx, llama_token_data_array * candidates, float z, size_t min_keep) {
  10289. if (z >= 1.0f || candidates->size <= 2) {
  10290. return;
  10291. }
  10292. llama_sample_softmax(nullptr, candidates);
  10293. const int64_t t_start_sample_us = ggml_time_us();
  10294. // Compute the first and second derivatives
  10295. std::vector<float> first_derivatives(candidates->size - 1);
  10296. std::vector<float> second_derivatives(candidates->size - 2);
  10297. for (size_t i = 0; i < first_derivatives.size(); ++i) {
  10298. first_derivatives[i] = candidates->data[i].p - candidates->data[i + 1].p;
  10299. }
  10300. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  10301. second_derivatives[i] = first_derivatives[i] - first_derivatives[i + 1];
  10302. }
  10303. // Calculate absolute value of second derivatives
  10304. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  10305. second_derivatives[i] = std::abs(second_derivatives[i]);
  10306. }
  10307. // Normalize the second derivatives
  10308. {
  10309. const float second_derivatives_sum = std::accumulate(second_derivatives.begin(), second_derivatives.end(), 0.0f);
  10310. if (second_derivatives_sum > 1e-6f) {
  10311. for (float & value : second_derivatives) {
  10312. value /= second_derivatives_sum;
  10313. }
  10314. } else {
  10315. for (float & value : second_derivatives) {
  10316. value = 1.0f / second_derivatives.size();
  10317. }
  10318. }
  10319. }
  10320. float cum_sum = 0.0f;
  10321. size_t last_idx = candidates->size;
  10322. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  10323. cum_sum += second_derivatives[i];
  10324. // Check if the running sum is greater than z or if we have kept at least min_keep tokens
  10325. if (cum_sum > z && i >= min_keep) {
  10326. last_idx = i;
  10327. break;
  10328. }
  10329. }
  10330. // Resize the output vector to keep only the tokens above the tail location
  10331. candidates->size = last_idx;
  10332. if (ctx) {
  10333. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10334. }
  10335. }
  10336. void llama_sample_typical(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  10337. // Reference implementation:
  10338. // https://github.com/huggingface/transformers/compare/main...cimeister:typical-sampling:typical-pr
  10339. if (p >= 1.0f) {
  10340. return;
  10341. }
  10342. // Compute the softmax of logits and calculate entropy
  10343. llama_sample_softmax(nullptr, candidates);
  10344. const int64_t t_start_sample_us = ggml_time_us();
  10345. float entropy = 0.0f;
  10346. for (size_t i = 0; i < candidates->size; ++i) {
  10347. entropy += -candidates->data[i].p * logf(candidates->data[i].p);
  10348. }
  10349. // Compute the absolute difference between negative log probability and entropy for each candidate
  10350. std::vector<float> shifted_scores;
  10351. for (size_t i = 0; i < candidates->size; ++i) {
  10352. float shifted_score = fabsf(-logf(candidates->data[i].p) - entropy);
  10353. shifted_scores.push_back(shifted_score);
  10354. }
  10355. // Sort tokens based on the shifted_scores and their corresponding indices
  10356. std::vector<size_t> indices(candidates->size);
  10357. std::iota(indices.begin(), indices.end(), 0);
  10358. std::sort(indices.begin(), indices.end(), [&](size_t a, size_t b) {
  10359. return shifted_scores[a] < shifted_scores[b];
  10360. });
  10361. // Compute the cumulative probabilities
  10362. float cum_sum = 0.0f;
  10363. size_t last_idx = indices.size();
  10364. for (size_t i = 0; i < indices.size(); ++i) {
  10365. size_t idx = indices[i];
  10366. cum_sum += candidates->data[idx].p;
  10367. // Check if the running sum is greater than typical or if we have kept at least min_keep tokens
  10368. if (cum_sum > p && i >= min_keep - 1) {
  10369. last_idx = i + 1;
  10370. break;
  10371. }
  10372. }
  10373. // Resize the output vector to keep only the locally typical tokens
  10374. std::vector<llama_token_data> new_candidates;
  10375. for (size_t i = 0; i < last_idx; ++i) {
  10376. size_t idx = indices[i];
  10377. new_candidates.push_back(candidates->data[idx]);
  10378. }
  10379. // Replace the data in candidates with the new_candidates data
  10380. std::copy(new_candidates.begin(), new_candidates.end(), candidates->data);
  10381. candidates->size = new_candidates.size();
  10382. candidates->sorted = false;
  10383. if (ctx) {
  10384. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10385. }
  10386. }
  10387. void llama_sample_entropy(struct llama_context * ctx, llama_token_data_array * candidates_p, float min_temp, float max_temp, float exponent_val) {
  10388. const int64_t t_start_sample_us = ggml_time_us();
  10389. // no need to do anything if there is only one (or zero) candidates
  10390. if(candidates_p->size <= 1) {
  10391. return;
  10392. }
  10393. // Calculate maximum possible entropy
  10394. float max_entropy = -logf(1.0f / candidates_p->size);
  10395. llama_sample_softmax(nullptr, candidates_p);
  10396. // Calculate entropy of the softmax probabilities
  10397. float entropy = 0.0f;
  10398. for (size_t i = 0; i < candidates_p->size; ++i) {
  10399. float prob = candidates_p->data[i].p;
  10400. if (prob > 0.0f) { // Ensure no log(0)
  10401. entropy -= prob * logf(prob);
  10402. }
  10403. }
  10404. // Normalize the entropy (max_entropy cannot be 0 here because we checked candidates_p->size != 1 above)
  10405. float normalized_entropy = entropy / max_entropy;
  10406. // Map the normalized entropy to the desired temperature range using the power function
  10407. float dyn_temp = min_temp + (max_temp - min_temp) * powf(normalized_entropy, exponent_val);
  10408. #ifdef DEBUG
  10409. LLAMA_LOG_INFO("Your text maxtemp value is: %f\n", max_temp);
  10410. LLAMA_LOG_INFO("Entropy: %f\n", entropy);
  10411. LLAMA_LOG_INFO("Max Possible Entropy: %f\n", max_entropy);
  10412. LLAMA_LOG_INFO("Normalized Entropy: %f\n", normalized_entropy);
  10413. LLAMA_LOG_INFO("Exponent: %f\n", exponent_val);
  10414. LLAMA_LOG_INFO("Dynamic Temperature (dyn_temp): %f\n", dyn_temp);
  10415. #endif
  10416. // Apply the dynamically calculated temperature scaling
  10417. for (size_t i = 0; i < candidates_p->size; ++i) {
  10418. candidates_p->data[i].logit /= dyn_temp;
  10419. }
  10420. // Re-compute softmax probabilities after scaling logits with dynamic temperature
  10421. double max_l_double = candidates_p->data[0].logit;
  10422. double cum_sum_double = 0.0;
  10423. for (size_t i = 0; i < candidates_p->size; ++i) {
  10424. double p = exp(candidates_p->data[i].logit - max_l_double);
  10425. candidates_p->data[i].p = p; // Store the scaled probability
  10426. cum_sum_double += p;
  10427. }
  10428. for (size_t i = 0; i < candidates_p->size; ++i) {
  10429. candidates_p->data[i].p /= cum_sum_double; // Re-normalize the probabilities
  10430. }
  10431. #ifdef DEBUG
  10432. // Print the updated top 25 probabilities after temperature scaling
  10433. LLAMA_LOG_INFO("\nUpdated Top 25 Probabilities After Dynamic Temperature Scaling (in percentages):\n");
  10434. for (size_t i = 0; i < 25 && i < candidates_p->size; ++i) {
  10435. LLAMA_LOG_INFO("Token %zu: %f%%\n", i + 1, candidates_p->data[i].p * 100.0f);
  10436. }
  10437. #endif
  10438. if (ctx) {
  10439. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10440. }
  10441. }
  10442. void llama_sample_temp(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  10443. const int64_t t_start_sample_us = ggml_time_us();
  10444. for (size_t i = 0; i < candidates_p->size; ++i) {
  10445. candidates_p->data[i].logit /= temp;
  10446. }
  10447. if (ctx) {
  10448. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10449. }
  10450. }
  10451. void llama_sample_repetition_penalties(
  10452. struct llama_context * ctx,
  10453. llama_token_data_array * candidates,
  10454. const llama_token * last_tokens,
  10455. size_t penalty_last_n,
  10456. float penalty_repeat,
  10457. float penalty_freq,
  10458. float penalty_present) {
  10459. if (penalty_last_n == 0 || (penalty_repeat == 1.0f && penalty_freq == 0.0f && penalty_present == 0.0f)) {
  10460. return;
  10461. }
  10462. const int64_t t_start_sample_us = ggml_time_us();
  10463. // Create a frequency map to count occurrences of each token in last_tokens
  10464. std::unordered_map<llama_token, int> token_count;
  10465. for (size_t i = 0; i < penalty_last_n; ++i) {
  10466. token_count[last_tokens[i]]++;
  10467. }
  10468. // Apply frequency and presence penalties to the candidates
  10469. for (size_t i = 0; i < candidates->size; ++i) {
  10470. const auto token_iter = token_count.find(candidates->data[i].id);
  10471. if (token_iter == token_count.end()) {
  10472. continue;
  10473. }
  10474. const int count = token_iter->second;
  10475. // 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.
  10476. // This is common fix for this problem, which is to multiply by the penalty instead of dividing.
  10477. if (candidates->data[i].logit <= 0) {
  10478. candidates->data[i].logit *= penalty_repeat;
  10479. } else {
  10480. candidates->data[i].logit /= penalty_repeat;
  10481. }
  10482. candidates->data[i].logit -= float(count) * penalty_freq + float(count > 0) * penalty_present;
  10483. }
  10484. candidates->sorted = false;
  10485. if (ctx) {
  10486. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10487. }
  10488. }
  10489. void llama_sample_grammar(struct llama_context * ctx, llama_token_data_array * candidates, const struct llama_grammar * grammar) {
  10490. GGML_ASSERT(ctx);
  10491. const int64_t t_start_sample_us = ggml_time_us();
  10492. bool allow_eos = false;
  10493. for (const auto & stack : grammar->stacks) {
  10494. if (stack.empty()) {
  10495. allow_eos = true;
  10496. break;
  10497. }
  10498. }
  10499. const llama_token eos = llama_token_eos(&ctx->model);
  10500. std::vector<std::pair<std::vector<uint32_t>, llama_partial_utf8>> candidates_decoded;
  10501. candidates_decoded.reserve(candidates->size);
  10502. std::vector<llama_grammar_candidate> candidates_grammar;
  10503. candidates_grammar.reserve(candidates->size);
  10504. for (size_t i = 0; i < candidates->size; ++i) {
  10505. const llama_token id = candidates->data[i].id;
  10506. const std::string piece = llama_token_to_piece(ctx, id);
  10507. if (id == eos) {
  10508. if (!allow_eos) {
  10509. candidates->data[i].logit = -INFINITY;
  10510. }
  10511. } else if (piece.empty() || piece[0] == 0) {
  10512. candidates->data[i].logit = -INFINITY;
  10513. } else {
  10514. candidates_decoded.push_back(decode_utf8(piece, grammar->partial_utf8));
  10515. candidates_grammar.push_back({ i, candidates_decoded.back().first.data(), candidates_decoded.back().second });
  10516. }
  10517. }
  10518. const auto rejects = llama_grammar_reject_candidates(grammar->rules, grammar->stacks, candidates_grammar);
  10519. for (const auto & reject : rejects) {
  10520. candidates->data[reject.index].logit = -INFINITY;
  10521. }
  10522. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10523. }
  10524. static void llama_log_softmax(float * array, size_t size) {
  10525. float max_l = *std::max_element(array, array + size);
  10526. float sum = 0.f;
  10527. for (size_t i = 0; i < size; ++i) {
  10528. float p = expf(array[i] - max_l);
  10529. sum += p;
  10530. array[i] = p;
  10531. }
  10532. for (size_t i = 0; i < size; ++i) {
  10533. array[i] = logf(array[i] / sum);
  10534. }
  10535. }
  10536. void llama_sample_apply_guidance(
  10537. struct llama_context * ctx,
  10538. float * logits,
  10539. float * logits_guidance,
  10540. float scale) {
  10541. GGML_ASSERT(ctx);
  10542. const auto t_start_sample_us = ggml_time_us();
  10543. const auto n_vocab = llama_n_vocab(llama_get_model(ctx));
  10544. llama_log_softmax(logits, n_vocab);
  10545. llama_log_softmax(logits_guidance, n_vocab);
  10546. for (int i = 0; i < n_vocab; ++i) {
  10547. auto & l = logits[i];
  10548. const auto & g = logits_guidance[i];
  10549. l = scale * (l - g) + g;
  10550. }
  10551. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10552. }
  10553. llama_token llama_sample_token_mirostat(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, int32_t m, float * mu) {
  10554. GGML_ASSERT(ctx);
  10555. auto N = float(llama_n_vocab(llama_get_model(ctx)));
  10556. int64_t t_start_sample_us;
  10557. t_start_sample_us = ggml_time_us();
  10558. llama_sample_softmax(nullptr, candidates);
  10559. // Estimate s_hat using the most probable m tokens
  10560. float s_hat = 0.0;
  10561. float sum_ti_bi = 0.0;
  10562. float sum_ti_sq = 0.0;
  10563. for (size_t i = 0; i < size_t(m - 1) && i < candidates->size - 1; ++i) {
  10564. float t_i = logf(float(i + 2) / float(i + 1));
  10565. float b_i = logf(candidates->data[i].p / candidates->data[i + 1].p);
  10566. sum_ti_bi += t_i * b_i;
  10567. sum_ti_sq += t_i * t_i;
  10568. }
  10569. s_hat = sum_ti_bi / sum_ti_sq;
  10570. // Compute k from the estimated s_hat and target surprise value
  10571. float epsilon_hat = s_hat - 1;
  10572. float k = powf((epsilon_hat * powf(2, *mu)) / (1 - powf(N, -epsilon_hat)), 1 / s_hat);
  10573. // Sample the next word X using top-k sampling
  10574. llama_sample_top_k(nullptr, candidates, int(k), 1);
  10575. if (ctx) {
  10576. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10577. }
  10578. llama_token X = llama_sample_token(ctx, candidates);
  10579. t_start_sample_us = ggml_time_us();
  10580. // Compute error as the difference between observed surprise and target surprise value
  10581. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  10582. return candidate.id == X;
  10583. }));
  10584. float observed_surprise = -log2f(candidates->data[X_idx].p);
  10585. float e = observed_surprise - tau;
  10586. // Update mu using the learning rate and error
  10587. *mu = *mu - eta * e;
  10588. if (ctx) {
  10589. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10590. }
  10591. return X;
  10592. }
  10593. llama_token llama_sample_token_mirostat_v2(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, float * mu) {
  10594. int64_t t_start_sample_us;
  10595. t_start_sample_us = ggml_time_us();
  10596. llama_sample_softmax(ctx, candidates);
  10597. // Truncate the words with surprise values greater than mu
  10598. candidates->size = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  10599. return -log2f(candidate.p) > *mu;
  10600. }));
  10601. if (candidates->size == 0) {
  10602. candidates->size = 1;
  10603. }
  10604. if (ctx) {
  10605. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10606. }
  10607. // Normalize the probabilities of the remaining words
  10608. llama_sample_softmax(ctx, candidates);
  10609. // Sample the next word X from the remaining words
  10610. llama_token X = llama_sample_token(ctx, candidates);
  10611. t_start_sample_us = ggml_time_us();
  10612. // Compute error as the difference between observed surprise and target surprise value
  10613. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  10614. return candidate.id == X;
  10615. }));
  10616. float observed_surprise = -log2f(candidates->data[X_idx].p);
  10617. float e = observed_surprise - tau;
  10618. // Update mu using the learning rate and error
  10619. *mu = *mu - eta * e;
  10620. if (ctx) {
  10621. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10622. }
  10623. return X;
  10624. }
  10625. llama_token llama_sample_token_greedy(struct llama_context * ctx, llama_token_data_array * candidates) {
  10626. const int64_t t_start_sample_us = ggml_time_us();
  10627. // Find max element
  10628. auto * max_iter = std::max_element(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  10629. return a.logit < b.logit;
  10630. });
  10631. llama_token result = max_iter->id;
  10632. if (ctx) {
  10633. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10634. ctx->n_sample++;
  10635. }
  10636. return result;
  10637. }
  10638. llama_token llama_sample_token(struct llama_context * ctx, llama_token_data_array * candidates) {
  10639. GGML_ASSERT(ctx);
  10640. const int64_t t_start_sample_us = ggml_time_us();
  10641. llama_sample_softmax(nullptr, candidates);
  10642. std::vector<float> probs;
  10643. probs.reserve(candidates->size);
  10644. for (size_t i = 0; i < candidates->size; ++i) {
  10645. probs.push_back(candidates->data[i].p);
  10646. }
  10647. std::discrete_distribution<> dist(probs.begin(), probs.end());
  10648. auto & rng = ctx->rng;
  10649. int idx = dist(rng);
  10650. llama_token result = candidates->data[idx].id;
  10651. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10652. ctx->n_sample++;
  10653. return result;
  10654. }
  10655. void llama_grammar_accept_token(struct llama_context * ctx, struct llama_grammar * grammar, llama_token token) {
  10656. const int64_t t_start_sample_us = ggml_time_us();
  10657. if (token == llama_token_eos(&ctx->model)) {
  10658. for (const auto & stack : grammar->stacks) {
  10659. if (stack.empty()) {
  10660. return;
  10661. }
  10662. }
  10663. GGML_ASSERT(false);
  10664. }
  10665. const std::string piece = llama_token_to_piece(ctx, token);
  10666. // Note terminating 0 in decoded string
  10667. const auto decoded = decode_utf8(piece, grammar->partial_utf8);
  10668. const auto & code_points = decoded.first;
  10669. std::vector<std::vector<const llama_grammar_element *>> tmp_new_stacks;
  10670. for (auto it = code_points.begin(), end = code_points.end() - 1; it != end; ++it) {
  10671. llama_grammar_accept(grammar->rules, grammar->stacks, *it, tmp_new_stacks);
  10672. grammar->stacks = tmp_new_stacks;
  10673. }
  10674. grammar->partial_utf8 = decoded.second;
  10675. GGML_ASSERT(!grammar->stacks.empty());
  10676. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10677. }
  10678. //
  10679. // Beam search
  10680. //
  10681. struct llama_beam {
  10682. std::vector<llama_token> tokens;
  10683. float p; // Cumulative beam probability (renormalized relative to all beams)
  10684. bool eob; // Initialize end-of-beam to false. Callback sets this to true.
  10685. // Sort beams by probability. In case of ties, prefer beams at eob.
  10686. bool operator<(const llama_beam & rhs) const {
  10687. return std::make_pair(p, eob) < std::make_pair(rhs.p, rhs.eob);
  10688. }
  10689. // Shift off first n tokens and discard them.
  10690. void shift_tokens(const size_t n) {
  10691. if (n) {
  10692. std::copy(tokens.begin() + n, tokens.end(), tokens.begin());
  10693. tokens.resize(tokens.size() - n);
  10694. }
  10695. }
  10696. llama_beam_view view() const { return {tokens.data(), tokens.size(), p, eob}; }
  10697. };
  10698. // A struct for calculating logit-related info.
  10699. struct llama_logit_info {
  10700. const float * const logits;
  10701. const int n_vocab;
  10702. const float max_l;
  10703. const float normalizer;
  10704. struct sum_exp {
  10705. float max_l;
  10706. float operator()(float sum, float l) const { return sum + std::exp(l - max_l); }
  10707. };
  10708. llama_logit_info(llama_context * ctx)
  10709. : logits(llama_get_logits(ctx))
  10710. , n_vocab(llama_n_vocab(llama_get_model(ctx)))
  10711. , max_l(*std::max_element(logits, logits + n_vocab))
  10712. , normalizer(1.0f / std::accumulate(logits, logits + n_vocab, 0.0f, sum_exp{max_l}))
  10713. { }
  10714. llama_token_data get_token_data(const llama_token token_id) const {
  10715. constexpr auto p = std::numeric_limits<float>::quiet_NaN(); // never used
  10716. return {token_id, logits[token_id], p};
  10717. }
  10718. // Return top k token_data by logit.
  10719. std::vector<llama_token_data> top_k(size_t k) {
  10720. std::vector<llama_token_data> min_heap; // min-heap by logit
  10721. const llama_token k_min = std::min(static_cast<llama_token>(k), n_vocab);
  10722. min_heap.reserve(k_min);
  10723. for (llama_token token_id = 0 ; token_id < k_min ; ++token_id) {
  10724. min_heap.push_back(get_token_data(token_id));
  10725. }
  10726. auto comp = [](const llama_token_data & a, const llama_token_data & b) { return a.logit > b.logit; };
  10727. std::make_heap(min_heap.begin(), min_heap.end(), comp);
  10728. for (llama_token token_id = k_min ; token_id < n_vocab ; ++token_id) {
  10729. if (min_heap.front().logit < logits[token_id]) {
  10730. std::pop_heap(min_heap.begin(), min_heap.end(), comp);
  10731. min_heap.back().id = token_id;
  10732. min_heap.back().logit = logits[token_id];
  10733. std::push_heap(min_heap.begin(), min_heap.end(), comp);
  10734. }
  10735. }
  10736. return min_heap;
  10737. }
  10738. float probability_from_logit(float logit) const {
  10739. return normalizer * std::exp(logit - max_l);
  10740. }
  10741. };
  10742. struct llama_beam_search_data {
  10743. llama_context * ctx;
  10744. size_t n_beams;
  10745. int n_past;
  10746. int n_predict;
  10747. std::vector<llama_beam> beams;
  10748. std::vector<llama_beam> next_beams;
  10749. // Re-calculated on each loop iteration
  10750. size_t common_prefix_length;
  10751. // Used to communicate to/from callback on beams state.
  10752. std::vector<llama_beam_view> beam_views;
  10753. llama_beam_search_data(llama_context * ctx, size_t n_beams, int n_past, int n_predict)
  10754. : ctx(ctx)
  10755. , n_beams(n_beams)
  10756. , n_past(n_past)
  10757. , n_predict(n_predict)
  10758. , beam_views(n_beams) {
  10759. beams.reserve(n_beams);
  10760. next_beams.reserve(n_beams);
  10761. }
  10762. // Collapse beams to a single beam given by index.
  10763. void collapse_beams(const size_t beam_idx) {
  10764. if (0u < beam_idx) {
  10765. std::swap(beams[0], beams[beam_idx]);
  10766. }
  10767. beams.resize(1);
  10768. }
  10769. // Min-heaps are used to efficiently collect the top-k elements (k=n_beams).
  10770. // The repetitive patterns below reflect the 2 stages of heaps:
  10771. // * Gather elements until the vector is full, then call std::make_heap() on it.
  10772. // * If the heap is full and a new element is found that should be included, pop the
  10773. // least element to the back(), replace it with the new, then push it into the heap.
  10774. void fill_next_beams_by_top_probabilities(llama_beam & beam) {
  10775. // Min-heaps use a greater-than comparator.
  10776. const auto comp = [](const llama_beam & a, const llama_beam & b) { return a.p > b.p; };
  10777. if (beam.eob) {
  10778. // beam is at end-of-sentence, so just copy it to next_beams if its probability is high enough.
  10779. if (next_beams.size() < n_beams) {
  10780. next_beams.push_back(std::move(beam));
  10781. if (next_beams.size() == n_beams) {
  10782. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  10783. }
  10784. } else if (next_beams.front().p < beam.p) {
  10785. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  10786. next_beams.back() = std::move(beam);
  10787. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  10788. }
  10789. } else {
  10790. // beam is not at end-of-sentence, so branch with next top_k tokens.
  10791. if (!beam.tokens.empty()) {
  10792. llama_decode(ctx, llama_batch_get_one(beam.tokens.data(), beam.tokens.size(), n_past, 0));
  10793. }
  10794. llama_logit_info logit_info(ctx);
  10795. std::vector<llama_token_data> next_tokens = logit_info.top_k(n_beams);
  10796. size_t i=0;
  10797. if (next_beams.size() < n_beams) {
  10798. for (; next_beams.size() < n_beams ; ++i) {
  10799. llama_beam next_beam = beam;
  10800. next_beam.tokens.push_back(next_tokens[i].id);
  10801. next_beam.p *= logit_info.probability_from_logit(next_tokens[i].logit);
  10802. next_beams.push_back(std::move(next_beam));
  10803. }
  10804. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  10805. } else {
  10806. for (; next_beams.front().p == 0.0f ; ++i) {
  10807. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  10808. next_beams.back() = beam;
  10809. next_beams.back().tokens.push_back(next_tokens[i].id);
  10810. next_beams.back().p *= logit_info.probability_from_logit(next_tokens[i].logit);
  10811. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  10812. }
  10813. }
  10814. for (; i < n_beams ; ++i) {
  10815. const float next_p = beam.p * logit_info.probability_from_logit(next_tokens[i].logit);
  10816. if (next_beams.front().p < next_p) {
  10817. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  10818. next_beams.back() = beam;
  10819. next_beams.back().tokens.push_back(next_tokens[i].id);
  10820. next_beams.back().p = next_p;
  10821. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  10822. }
  10823. }
  10824. }
  10825. }
  10826. // Find common_prefix_length based on beams.
  10827. // Requires beams is not empty.
  10828. size_t find_common_prefix_length() {
  10829. size_t common_prefix_length = beams[0].tokens.size();
  10830. for (size_t i = 1 ; i < beams.size() ; ++i) {
  10831. common_prefix_length = std::min(common_prefix_length, beams[i].tokens.size());
  10832. for (size_t j = 0 ; j < common_prefix_length ; ++j) {
  10833. if (beams[0].tokens[j] != beams[i].tokens[j]) {
  10834. common_prefix_length = j;
  10835. break;
  10836. }
  10837. }
  10838. }
  10839. return common_prefix_length;
  10840. }
  10841. // Construct beams_state to send back to caller via the callback function.
  10842. // Side effect: set common_prefix_length = find_common_prefix_length();
  10843. llama_beams_state get_beams_state(const bool last_call) {
  10844. for (size_t i = 0 ; i < beams.size() ; ++i) {
  10845. beam_views[i] = beams[i].view();
  10846. }
  10847. common_prefix_length = find_common_prefix_length();
  10848. return {beam_views.data(), beams.size(), common_prefix_length, last_call};
  10849. }
  10850. // Loop:
  10851. // * while i < n_predict, AND
  10852. // * any of the beams have not yet reached end-of-beam (eob), AND
  10853. // * the highest probability beam(s) (plural in case of ties) are not at end-of-sentence
  10854. // (since all other beam probabilities can only decrease)
  10855. void loop(const llama_beam_search_callback_fn_t callback, void * const callback_data) {
  10856. beams.push_back({{}, 1.0f, false}); // Start with one empty beam w/ probability = 1.0 and !eob.
  10857. const auto not_eob = [](const llama_beam & beam) { return !beam.eob; };
  10858. for (int i = 0 ; i < n_predict && std::any_of(beams.begin(),beams.end(),not_eob) &&
  10859. !beams[top_beam_index()].eob ; ++i) {
  10860. callback(callback_data, get_beams_state(false)); // Sets common_prefix_length
  10861. update_beams_from_beam_views(); // Update values (p,eob) that callback may have changed.
  10862. if (common_prefix_length) {
  10863. llama_decode(ctx, llama_batch_get_one(beams[0].tokens.data(), common_prefix_length, n_past, 0));
  10864. n_past += common_prefix_length;
  10865. }
  10866. // Zero-out next_beam probabilities to place them last in following min-heap.
  10867. std::for_each(next_beams.begin(), next_beams.end(), [](llama_beam & beam) { beam.p = 0.0f; });
  10868. for (llama_beam & beam : beams) {
  10869. beam.shift_tokens(common_prefix_length);
  10870. fill_next_beams_by_top_probabilities(beam);
  10871. }
  10872. // next_beams become the beams of next/final iteration. Swap them to re-use memory.
  10873. beams.swap(next_beams);
  10874. renormalize_beam_probabilities(beams);
  10875. }
  10876. collapse_beams(top_beam_index());
  10877. callback(callback_data, get_beams_state(true));
  10878. }
  10879. // As beams grow, the cumulative probabilities decrease.
  10880. // Renormalize them to avoid floating point underflow.
  10881. static void renormalize_beam_probabilities(std::vector<llama_beam> & beams) {
  10882. const auto sum_p = [](float sum, llama_beam & beam) { return sum + beam.p; };
  10883. const float inv_sum = 1.0f / std::accumulate(beams.begin(), beams.end(), 0.0f, sum_p);
  10884. std::for_each(beams.begin(), beams.end(), [=](llama_beam & beam) { beam.p *= inv_sum; });
  10885. }
  10886. // Assumes beams is non-empty. Uses llama_beam::operator<() for ordering.
  10887. size_t top_beam_index() {
  10888. return std::max_element(beams.begin(), beams.end()) - beams.begin();
  10889. }
  10890. // Copy (p,eob) for each beam which may have been changed by the callback.
  10891. void update_beams_from_beam_views() {
  10892. for (size_t i = 0 ; i < beams.size() ; ++i) {
  10893. beams[i].p = beam_views[i].p;
  10894. beams[i].eob = beam_views[i].eob;
  10895. }
  10896. }
  10897. };
  10898. void llama_beam_search(llama_context * ctx,
  10899. llama_beam_search_callback_fn_t callback, void * callback_data,
  10900. size_t n_beams, int n_past, int n_predict) {
  10901. assert(ctx);
  10902. const int64_t t_start_sample_us = ggml_time_us();
  10903. llama_beam_search_data beam_search_data(ctx, n_beams, n_past, n_predict);
  10904. beam_search_data.loop(callback, callback_data);
  10905. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10906. ctx->n_sample++;
  10907. }
  10908. //
  10909. // quantization
  10910. //
  10911. struct quantize_state_internal {
  10912. const llama_model & model;
  10913. const llama_model_quantize_params * params;
  10914. int n_attention_wv = 0;
  10915. int n_ffn_down = 0;
  10916. int n_ffn_gate = 0;
  10917. int n_ffn_up = 0;
  10918. int i_attention_wv = 0;
  10919. int i_ffn_down = 0;
  10920. int i_ffn_gate = 0;
  10921. int i_ffn_up = 0;
  10922. int n_k_quantized = 0;
  10923. int n_fallback = 0;
  10924. bool has_imatrix = false;
  10925. // used to figure out if a model shares tok_embd with the output weight
  10926. bool has_output = false;
  10927. quantize_state_internal(const llama_model & model, const llama_model_quantize_params * params)
  10928. : model(model)
  10929. , params(params)
  10930. {}
  10931. };
  10932. static void llama_tensor_dequantize_internal(
  10933. struct ggml_tensor * tensor, std::vector<no_init<float>> & output, std::vector<std::thread> & workers,
  10934. const size_t nelements, const int nthread
  10935. ) {
  10936. if (output.size() < nelements) {
  10937. output.resize(nelements);
  10938. }
  10939. float * f32_output = (float *) output.data();
  10940. ggml_type_traits_t qtype;
  10941. if (ggml_is_quantized(tensor->type)) {
  10942. qtype = ggml_internal_get_type_traits(tensor->type);
  10943. if (qtype.to_float == NULL) {
  10944. throw std::runtime_error(format("type %s unsupported for integer quantization: no dequantization available", ggml_type_name(tensor->type)));
  10945. }
  10946. } else if (tensor->type != GGML_TYPE_F16) {
  10947. throw std::runtime_error(format("cannot dequantize/convert tensor type %s", ggml_type_name(tensor->type)));
  10948. }
  10949. if (nthread < 2) {
  10950. if (tensor->type == GGML_TYPE_F16) {
  10951. ggml_fp16_to_fp32_row((ggml_fp16_t *)tensor->data, f32_output, nelements);
  10952. } else if (ggml_is_quantized(tensor->type)) {
  10953. qtype.to_float(tensor->data, f32_output, nelements);
  10954. } else {
  10955. GGML_ASSERT(false); // unreachable
  10956. }
  10957. return;
  10958. }
  10959. size_t block_size = tensor->type == GGML_TYPE_F16 ? 1 : (size_t)ggml_blck_size(tensor->type);
  10960. size_t block_size_bytes = ggml_type_size(tensor->type);
  10961. GGML_ASSERT(nelements % block_size == 0);
  10962. size_t nblocks = nelements / block_size;
  10963. size_t blocks_per_thread = nblocks / nthread;
  10964. size_t spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count
  10965. size_t in_buff_offs = 0;
  10966. size_t out_buff_offs = 0;
  10967. for (int tnum = 0; tnum < nthread; tnum++) {
  10968. size_t thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread
  10969. size_t thr_elems = thr_blocks * block_size; // number of elements for this thread
  10970. size_t thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread
  10971. auto compute = [qtype] (ggml_type typ, uint8_t * inbuf, float * outbuf, int nels) {
  10972. if (typ == GGML_TYPE_F16) {
  10973. ggml_fp16_to_fp32_row((ggml_fp16_t *)inbuf, outbuf, nels);
  10974. } else {
  10975. qtype.to_float(inbuf, outbuf, nels);
  10976. }
  10977. };
  10978. workers.emplace_back(compute, tensor->type, (uint8_t *) tensor->data + in_buff_offs, f32_output + out_buff_offs, thr_elems);
  10979. in_buff_offs += thr_block_bytes;
  10980. out_buff_offs += thr_elems;
  10981. }
  10982. for (auto & w : workers) { w.join(); }
  10983. workers.clear();
  10984. }
  10985. static ggml_type llama_tensor_get_type(quantize_state_internal & qs, ggml_type new_type, const ggml_tensor * tensor, llama_ftype ftype) {
  10986. const std::string name = ggml_get_name(tensor);
  10987. // TODO: avoid hardcoded tensor names - use the TN_* constants
  10988. const llm_arch arch = qs.model.arch;
  10989. const auto tn = LLM_TN(arch);
  10990. auto use_more_bits = [](int i_layer, int num_layers) -> bool {
  10991. return i_layer < num_layers/8 || i_layer >= 7*num_layers/8 || (i_layer - num_layers/8)%3 == 2;
  10992. };
  10993. const int n_expert = std::max(1, (int)qs.model.hparams.n_expert);
  10994. auto layer_info = [n_expert] (int i_layer, int n_layer, const char * name) {
  10995. if (n_expert > 1) {
  10996. // Believe it or not, "experts" in the FFN of Mixtral-8x7B are not consecutive, but iccasionally randomly
  10997. // sprinkled in the model. Hence, simply dividing i_ffn_down by n_expert does not work
  10998. // for getting the current layer as I initially thought, and we need to resort to parsing the
  10999. // tensor name.
  11000. if (sscanf(name, "blk.%d.", &i_layer) != 1) {
  11001. throw std::runtime_error(format("Failed to determine layer for tensor %s", name));
  11002. }
  11003. if (i_layer < 0 || i_layer >= n_layer) {
  11004. throw std::runtime_error(format("Bad layer %d for tensor %s. Must be in [0, %d)", i_layer, name, n_layer));
  11005. }
  11006. }
  11007. return std::make_pair(i_layer, n_layer);
  11008. };
  11009. // for arches that share the same tensor between the token embeddings and the output, we quantize the token embeddings
  11010. // with the quantization of the output tensor
  11011. if (name == tn(LLM_TENSOR_OUTPUT, "weight") || (!qs.has_output && name == tn(LLM_TENSOR_TOKEN_EMBD, "weight"))) {
  11012. if (qs.params->output_tensor_type < GGML_TYPE_COUNT) {
  11013. new_type = qs.params->output_tensor_type;
  11014. } else {
  11015. int nx = tensor->ne[0];
  11016. if (arch == LLM_ARCH_FALCON || nx % QK_K != 0) {
  11017. new_type = GGML_TYPE_Q8_0;
  11018. }
  11019. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  11020. ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ||
  11021. ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  11022. new_type = GGML_TYPE_Q5_K;
  11023. }
  11024. else if (new_type != GGML_TYPE_Q8_0) {
  11025. new_type = GGML_TYPE_Q6_K;
  11026. }
  11027. }
  11028. } else if (name == "token_embd.weight") {
  11029. if (qs.params->token_embedding_type < GGML_TYPE_COUNT) {
  11030. new_type = qs.params->token_embedding_type;
  11031. } else {
  11032. if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS ||
  11033. ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  11034. new_type = GGML_TYPE_Q2_K;
  11035. }
  11036. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) {
  11037. new_type = GGML_TYPE_IQ3_S;
  11038. }
  11039. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  11040. new_type = GGML_TYPE_IQ3_S;
  11041. }
  11042. }
  11043. } else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S ||
  11044. ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  11045. if (name.find("attn_v.weight") != std::string::npos) {
  11046. if (qs.model.hparams.n_gqa() >= 4 || qs.model.hparams.n_expert >= 4) new_type = GGML_TYPE_Q4_K;
  11047. else new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  11048. ++qs.i_attention_wv;
  11049. }
  11050. else if (qs.model.hparams.n_expert == 8 && name.find("attn_k.weight") != std::string::npos) {
  11051. new_type = GGML_TYPE_Q4_K;
  11052. }
  11053. else if (name.find("ffn_down") != std::string::npos) {
  11054. if (qs.i_ffn_down < qs.n_ffn_down/8) {
  11055. new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  11056. }
  11057. ++qs.i_ffn_down;
  11058. }
  11059. else if (name.find("attn_output.weight") != std::string::npos) {
  11060. if (qs.model.hparams.n_expert == 8) {
  11061. new_type = GGML_TYPE_Q5_K;
  11062. } else {
  11063. if (ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) new_type = GGML_TYPE_IQ2_XXS;
  11064. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) new_type = GGML_TYPE_IQ3_S;
  11065. }
  11066. }
  11067. } else if (name.find("attn_v.weight") != std::string::npos) {
  11068. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) {
  11069. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  11070. }
  11071. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && qs.model.hparams.n_gqa() >= 4) {
  11072. new_type = GGML_TYPE_Q4_K;
  11073. }
  11074. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  11075. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : !qs.has_imatrix ? GGML_TYPE_IQ3_S : GGML_TYPE_IQ3_XXS;
  11076. }
  11077. else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S) && qs.model.hparams.n_gqa() >= 4) {
  11078. new_type = GGML_TYPE_Q4_K;
  11079. }
  11080. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  11081. new_type = GGML_TYPE_Q4_K;
  11082. }
  11083. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  11084. new_type = qs.i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  11085. }
  11086. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  11087. else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && qs.model.hparams.n_gqa() >= 4) {
  11088. new_type = GGML_TYPE_Q5_K;
  11089. }
  11090. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
  11091. use_more_bits(qs.i_attention_wv, qs.n_attention_wv)) new_type = GGML_TYPE_Q6_K;
  11092. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && qs.i_attention_wv < 4) new_type = GGML_TYPE_Q5_K;
  11093. else if (QK_K == 64 && (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S) &&
  11094. (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;
  11095. if (qs.model.type == MODEL_70B) {
  11096. // In the 70B model we have 8 heads sharing the same attn_v weights. As a result, the attn_v.weight tensor is
  11097. // 8x smaller compared to attn_q.weight. Hence, we can get a nice boost in quantization accuracy with
  11098. // nearly negligible increase in model size by quantizing this tensor with more bits:
  11099. if (new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K) new_type = GGML_TYPE_Q5_K;
  11100. }
  11101. if (qs.model.hparams.n_expert == 8) {
  11102. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  11103. // TODO: explore better strategies
  11104. new_type = GGML_TYPE_Q8_0;
  11105. }
  11106. ++qs.i_attention_wv;
  11107. } else if (name.find("attn_k.weight") != std::string::npos) {
  11108. if (qs.model.hparams.n_expert == 8) {
  11109. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  11110. // TODO: explore better strategies
  11111. new_type = GGML_TYPE_Q8_0;
  11112. }
  11113. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  11114. new_type = GGML_TYPE_IQ3_XXS;
  11115. }
  11116. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  11117. new_type = GGML_TYPE_IQ2_S;
  11118. }
  11119. } else if (name.find("attn_q.weight") != std::string::npos) {
  11120. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  11121. new_type = GGML_TYPE_IQ3_XXS;
  11122. }
  11123. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  11124. new_type = GGML_TYPE_IQ2_S;
  11125. }
  11126. } else if (name.find("ffn_down") != std::string::npos) {
  11127. auto info = layer_info(qs.i_ffn_down, qs.n_ffn_down, name.c_str());
  11128. int i_layer = info.first, n_layer = info.second;
  11129. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  11130. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S) {
  11131. if (i_layer < n_layer/8) new_type = GGML_TYPE_Q4_K;
  11132. }
  11133. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS && !qs.has_imatrix) {
  11134. new_type = i_layer < n_layer/8 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  11135. }
  11136. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  11137. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q5_K
  11138. : arch != LLM_ARCH_FALCON || use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q4_K
  11139. : GGML_TYPE_Q3_K;
  11140. }
  11141. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M && (i_layer < n_layer/8 ||
  11142. (qs.model.hparams.n_expert == 8 && use_more_bits(i_layer, n_layer)))) {
  11143. new_type = GGML_TYPE_Q4_K;
  11144. }
  11145. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) {
  11146. new_type = arch == LLM_ARCH_FALCON ? GGML_TYPE_Q4_K : GGML_TYPE_Q5_K;
  11147. }
  11148. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  11149. if (arch == LLM_ARCH_FALCON) {
  11150. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q6_K :
  11151. use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  11152. } else {
  11153. if (use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  11154. }
  11155. }
  11156. else if (i_layer < n_layer/8 && (ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && !qs.has_imatrix) {
  11157. new_type = GGML_TYPE_Q5_K;
  11158. }
  11159. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M && use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  11160. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && arch != LLM_ARCH_FALCON && i_layer < n_layer/8) {
  11161. new_type = GGML_TYPE_Q5_K;
  11162. }
  11163. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_0 || ftype == LLAMA_FTYPE_MOSTLY_Q5_0)
  11164. && qs.has_imatrix && i_layer < n_layer/8) {
  11165. // Guard against craziness in the first few ffn_down layers that can happen even with imatrix for Q4_0/Q5_0.
  11166. // We only do it when an imatrix is provided because a) we want to make sure that one can always get the
  11167. // same quantization as before imatrix stuff, and b) Q4_1/Q5_1 do go crazy on ffn_down without an imatrix.
  11168. new_type = ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ? GGML_TYPE_Q4_1 : GGML_TYPE_Q5_1;
  11169. }
  11170. ++qs.i_ffn_down;
  11171. } else if (name.find("attn_output.weight") != std::string::npos) {
  11172. if (arch != LLM_ARCH_FALCON) {
  11173. if (qs.model.hparams.n_expert == 8) {
  11174. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  11175. ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL ||
  11176. ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S ||
  11177. ftype == LLAMA_FTYPE_MOSTLY_IQ3_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) {
  11178. new_type = GGML_TYPE_Q5_K;
  11179. }
  11180. } else {
  11181. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K ) new_type = GGML_TYPE_Q3_K;
  11182. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) new_type = GGML_TYPE_IQ3_S;
  11183. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M ) new_type = GGML_TYPE_Q4_K;
  11184. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L ) new_type = GGML_TYPE_Q5_K;
  11185. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M ) new_type = GGML_TYPE_Q4_K;
  11186. }
  11187. } else {
  11188. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  11189. }
  11190. }
  11191. else if (name.find("attn_qkv.weight") != std::string::npos) {
  11192. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L || ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  11193. new_type = GGML_TYPE_Q4_K;
  11194. }
  11195. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) new_type = GGML_TYPE_Q5_K;
  11196. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) new_type = GGML_TYPE_Q6_K;
  11197. }
  11198. else if (name.find("ffn_gate") != std::string::npos) {
  11199. auto info = layer_info(qs.i_ffn_gate, qs.n_ffn_gate, name.c_str());
  11200. int i_layer = info.first, n_layer = info.second;
  11201. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  11202. new_type = GGML_TYPE_IQ3_XXS;
  11203. }
  11204. ++qs.i_ffn_gate;
  11205. }
  11206. else if (name.find("ffn_up") != std::string::npos) {
  11207. auto info = layer_info(qs.i_ffn_up, qs.n_ffn_up, name.c_str());
  11208. int i_layer = info.first, n_layer = info.second;
  11209. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  11210. new_type = GGML_TYPE_IQ3_XXS;
  11211. }
  11212. ++qs.i_ffn_up;
  11213. }
  11214. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  11215. //}
  11216. // IK: let's remove this, else Q2_K is almost the same as Q3_K_S
  11217. //else if (name.find("ffn_gate") != std::string::npos || name.find("ffn_up") != std::string::npos) {
  11218. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  11219. //}
  11220. // This can be used to reduce the size of the Q5_K_S model.
  11221. // The associated PPL increase is fully in line with the size reduction
  11222. //else {
  11223. // if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_S) new_type = GGML_TYPE_Q4_K;
  11224. //}
  11225. bool convert_incompatible_tensor = false;
  11226. if (new_type == GGML_TYPE_Q2_K || new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K ||
  11227. new_type == GGML_TYPE_Q5_K || new_type == GGML_TYPE_Q6_K || new_type == GGML_TYPE_IQ4_XS ||
  11228. new_type == GGML_TYPE_IQ2_XS || new_type == GGML_TYPE_IQ2_XXS || new_type == GGML_TYPE_IQ2_S ||
  11229. new_type == GGML_TYPE_IQ3_XXS || new_type == GGML_TYPE_IQ1_S || new_type == GGML_TYPE_IQ3_S ||
  11230. new_type == GGML_TYPE_IQ1_M) {
  11231. int nx = tensor->ne[0];
  11232. int ny = tensor->ne[1];
  11233. if (nx % QK_K != 0) {
  11234. 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));
  11235. convert_incompatible_tensor = true;
  11236. } else {
  11237. ++qs.n_k_quantized;
  11238. }
  11239. }
  11240. if (convert_incompatible_tensor) {
  11241. switch (new_type) {
  11242. case GGML_TYPE_IQ2_XXS:
  11243. case GGML_TYPE_IQ2_XS:
  11244. case GGML_TYPE_IQ2_S:
  11245. case GGML_TYPE_IQ3_XXS:
  11246. case GGML_TYPE_IQ3_S:
  11247. case GGML_TYPE_IQ1_S:
  11248. case GGML_TYPE_IQ1_M:
  11249. case GGML_TYPE_Q2_K:
  11250. case GGML_TYPE_Q3_K:
  11251. case GGML_TYPE_IQ4_XS: new_type = GGML_TYPE_IQ4_NL; break;
  11252. case GGML_TYPE_Q4_K: new_type = GGML_TYPE_Q5_0; break;
  11253. case GGML_TYPE_Q5_K: new_type = GGML_TYPE_Q5_1; break;
  11254. case GGML_TYPE_Q6_K: new_type = GGML_TYPE_Q8_0; break;
  11255. default: throw std::runtime_error("\nUnsupported tensor size encountered\n");
  11256. }
  11257. LLAMA_LOG_WARN(" - using fallback quantization %s\n", ggml_type_name(new_type));
  11258. ++qs.n_fallback;
  11259. }
  11260. return new_type;
  11261. }
  11262. 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) {
  11263. std::mutex mutex;
  11264. int64_t counter = 0;
  11265. size_t new_size = 0;
  11266. if (nthread < 2) {
  11267. // single-thread
  11268. return ggml_quantize_chunk(new_type, f32_data, new_data, 0, nrows, n_per_row, imatrix);
  11269. }
  11270. auto compute = [&mutex, &counter, &new_size, new_type, f32_data, new_data, chunk_size,
  11271. nrows, n_per_row, imatrix]() {
  11272. const int64_t nrows_per_chunk = chunk_size / n_per_row;
  11273. size_t local_size = 0;
  11274. while (true) {
  11275. std::unique_lock<std::mutex> lock(mutex);
  11276. int64_t first_row = counter; counter += nrows_per_chunk;
  11277. if (first_row >= nrows) {
  11278. if (local_size > 0) {
  11279. new_size += local_size;
  11280. }
  11281. break;
  11282. }
  11283. lock.unlock();
  11284. const int64_t this_nrow = std::min(nrows - first_row, nrows_per_chunk);
  11285. local_size += ggml_quantize_chunk(new_type, f32_data, new_data, first_row * n_per_row, this_nrow, n_per_row, imatrix);
  11286. }
  11287. };
  11288. for (int it = 0; it < nthread - 1; ++it) {
  11289. workers.emplace_back(compute);
  11290. }
  11291. compute();
  11292. for (auto & w : workers) { w.join(); }
  11293. workers.clear();
  11294. return new_size;
  11295. }
  11296. static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) {
  11297. ggml_type default_type;
  11298. llama_ftype ftype = params->ftype;
  11299. switch (params->ftype) {
  11300. case LLAMA_FTYPE_MOSTLY_Q4_0: default_type = GGML_TYPE_Q4_0; break;
  11301. case LLAMA_FTYPE_MOSTLY_Q4_1: default_type = GGML_TYPE_Q4_1; break;
  11302. case LLAMA_FTYPE_MOSTLY_Q5_0: default_type = GGML_TYPE_Q5_0; break;
  11303. case LLAMA_FTYPE_MOSTLY_Q5_1: default_type = GGML_TYPE_Q5_1; break;
  11304. case LLAMA_FTYPE_MOSTLY_Q8_0: default_type = GGML_TYPE_Q8_0; break;
  11305. case LLAMA_FTYPE_MOSTLY_F16: default_type = GGML_TYPE_F16; break;
  11306. case LLAMA_FTYPE_ALL_F32: default_type = GGML_TYPE_F32; break;
  11307. // K-quants
  11308. case LLAMA_FTYPE_MOSTLY_Q2_K_S:
  11309. case LLAMA_FTYPE_MOSTLY_Q2_K: default_type = GGML_TYPE_Q2_K; break;
  11310. case LLAMA_FTYPE_MOSTLY_IQ3_XS: default_type = GGML_TYPE_IQ3_S; break;
  11311. case LLAMA_FTYPE_MOSTLY_Q3_K_S:
  11312. case LLAMA_FTYPE_MOSTLY_Q3_K_M:
  11313. case LLAMA_FTYPE_MOSTLY_Q3_K_L: default_type = GGML_TYPE_Q3_K; break;
  11314. case LLAMA_FTYPE_MOSTLY_Q4_K_S:
  11315. case LLAMA_FTYPE_MOSTLY_Q4_K_M: default_type = GGML_TYPE_Q4_K; break;
  11316. case LLAMA_FTYPE_MOSTLY_Q5_K_S:
  11317. case LLAMA_FTYPE_MOSTLY_Q5_K_M: default_type = GGML_TYPE_Q5_K; break;
  11318. case LLAMA_FTYPE_MOSTLY_Q6_K: default_type = GGML_TYPE_Q6_K; break;
  11319. case LLAMA_FTYPE_MOSTLY_IQ2_XXS: default_type = GGML_TYPE_IQ2_XXS; break;
  11320. case LLAMA_FTYPE_MOSTLY_IQ2_XS: default_type = GGML_TYPE_IQ2_XS; break;
  11321. case LLAMA_FTYPE_MOSTLY_IQ2_S: default_type = GGML_TYPE_IQ2_XS; break;
  11322. case LLAMA_FTYPE_MOSTLY_IQ2_M: default_type = GGML_TYPE_IQ2_S; break;
  11323. case LLAMA_FTYPE_MOSTLY_IQ3_XXS: default_type = GGML_TYPE_IQ3_XXS; break;
  11324. case LLAMA_FTYPE_MOSTLY_IQ1_S: default_type = GGML_TYPE_IQ1_S; break;
  11325. case LLAMA_FTYPE_MOSTLY_IQ1_M: default_type = GGML_TYPE_IQ1_M; break;
  11326. case LLAMA_FTYPE_MOSTLY_IQ4_NL: default_type = GGML_TYPE_IQ4_NL; break;
  11327. case LLAMA_FTYPE_MOSTLY_IQ4_XS: default_type = GGML_TYPE_IQ4_XS; break;
  11328. case LLAMA_FTYPE_MOSTLY_IQ3_S: default_type = GGML_TYPE_IQ3_S; break;
  11329. case LLAMA_FTYPE_MOSTLY_IQ3_M: default_type = GGML_TYPE_IQ3_S; break;
  11330. default: throw std::runtime_error(format("invalid output file type %d\n", ftype));
  11331. }
  11332. int nthread = params->nthread;
  11333. if (nthread <= 0) {
  11334. nthread = std::thread::hardware_concurrency();
  11335. }
  11336. // mmap consistently increases speed Linux, and also increases speed on Windows with
  11337. // hot cache. It may cause a slowdown on macOS, possibly related to free memory.
  11338. #if defined(__linux__) || defined(_WIN32)
  11339. constexpr bool use_mmap = true;
  11340. #else
  11341. constexpr bool use_mmap = false;
  11342. #endif
  11343. llama_model_kv_override * kv_overrides = nullptr;
  11344. if (params->kv_overrides) {
  11345. auto v = (std::vector<llama_model_kv_override>*)params->kv_overrides;
  11346. kv_overrides = v->data();
  11347. }
  11348. llama_model_loader ml(fname_inp, use_mmap, kv_overrides);
  11349. ml.init_mappings(false); // no prefetching
  11350. llama_model model;
  11351. llm_load_arch(ml, model);
  11352. llm_load_hparams(ml, model);
  11353. struct quantize_state_internal qs(model, params);
  11354. if (params->only_copy) {
  11355. ftype = model.ftype;
  11356. }
  11357. const std::unordered_map<std::string, std::vector<float>> * imatrix_data = nullptr;
  11358. if (params->imatrix) {
  11359. imatrix_data = static_cast<const std::unordered_map<std::string, std::vector<float>>*>(params->imatrix);
  11360. if (imatrix_data) {
  11361. LLAMA_LOG_INFO("================================ Have weights data with %d entries\n",int(imatrix_data->size()));
  11362. qs.has_imatrix = true;
  11363. }
  11364. }
  11365. const size_t align = GGUF_DEFAULT_ALIGNMENT;
  11366. struct gguf_context * ctx_out = gguf_init_empty();
  11367. // copy the KV pairs from the input file
  11368. gguf_set_kv (ctx_out, ml.meta);
  11369. gguf_set_val_u32(ctx_out, "general.quantization_version", GGML_QNT_VERSION);
  11370. gguf_set_val_u32(ctx_out, "general.file_type", ftype);
  11371. // Remove split metadata
  11372. gguf_remove_key(ctx_out, ml.llm_kv(LLM_KV_SPLIT_NO).c_str());
  11373. gguf_remove_key(ctx_out, ml.llm_kv(LLM_KV_SPLIT_COUNT).c_str());
  11374. gguf_remove_key(ctx_out, ml.llm_kv(LLM_KV_SPLIT_TENSORS_COUNT).c_str());
  11375. if (params->kv_overrides) {
  11376. const std::vector<llama_model_kv_override> & overrides = *(const std::vector<llama_model_kv_override> *)params->kv_overrides;
  11377. for (auto & o : overrides) {
  11378. if (o.key[0] == 0) break;
  11379. if (o.tag == LLAMA_KV_OVERRIDE_TYPE_FLOAT) {
  11380. gguf_set_val_f32(ctx_out, o.key, o.float_value);
  11381. } else if (o.tag == LLAMA_KV_OVERRIDE_TYPE_INT) {
  11382. gguf_set_val_i32(ctx_out, o.key, o.int_value);
  11383. } else if (o.tag == LLAMA_KV_OVERRIDE_TYPE_BOOL) {
  11384. gguf_set_val_bool(ctx_out, o.key, o.bool_value);
  11385. } else {
  11386. LLAMA_LOG_WARN("%s: unknown KV override type for key %s\n", __func__, o.key);
  11387. }
  11388. }
  11389. }
  11390. for (int i = 0; i < ml.n_tensors; ++i) {
  11391. const struct ggml_tensor * meta = ml.get_tensor_meta(i);
  11392. const std::string name = ggml_get_name(meta);
  11393. // TODO: avoid hardcoded tensor names - use the TN_* constants
  11394. if (name.find("attn_v.weight") != std::string::npos ||
  11395. name.find("attn_qkv.weight") != std::string::npos) {
  11396. ++qs.n_attention_wv;
  11397. } else if (name == LLM_TN(model.arch)(LLM_TENSOR_OUTPUT, "weight")) {
  11398. qs.has_output = true;
  11399. }
  11400. }
  11401. qs.n_ffn_down = qs.n_ffn_gate = qs.n_ffn_up = (int)model.hparams.n_layer;
  11402. // sanity checks
  11403. //
  11404. // - qs.n_attention_wv == 0 for Mamba models
  11405. // - qs.n_attention_wv == model.hparams.n_layer for Transformer models
  11406. //
  11407. GGML_ASSERT((qs.n_attention_wv == 0 || qs.n_attention_wv == (int)model.hparams.n_layer) && "n_attention_wv is unexpected");
  11408. size_t total_size_org = 0;
  11409. size_t total_size_new = 0;
  11410. std::vector<std::thread> workers;
  11411. workers.reserve(nthread);
  11412. int idx = 0;
  11413. std::vector<no_init<uint8_t>> read_data;
  11414. std::vector<no_init<uint8_t>> work;
  11415. std::vector<no_init<float>> f32_conv_buf;
  11416. // populate the original tensors so we get an initial meta data
  11417. for (int i = 0; i < ml.n_tensors; ++i) {
  11418. const struct ggml_tensor * meta = ml.get_tensor_meta(i);
  11419. gguf_add_tensor(ctx_out, meta);
  11420. }
  11421. std::ofstream fout(fname_out, std::ios::binary);
  11422. fout.exceptions(std::ofstream::failbit); // fail fast on write errors
  11423. const size_t meta_size = gguf_get_meta_size(ctx_out);
  11424. LLAMA_LOG_INFO("%s: meta size = %zu bytes\n", __func__, meta_size);
  11425. // placeholder for the meta data
  11426. ::zeros(fout, meta_size);
  11427. const auto tn = LLM_TN(model.arch);
  11428. for (int i = 0; i < ml.n_tensors; ++i) {
  11429. struct ggml_tensor * tensor = ml.get_tensor_meta(i);
  11430. const std::string name = ggml_get_name(tensor);
  11431. if (!ml.use_mmap) {
  11432. if (read_data.size() < ggml_nbytes(tensor)) {
  11433. read_data.resize(ggml_nbytes(tensor));
  11434. }
  11435. tensor->data = read_data.data();
  11436. }
  11437. ml.load_data_for(tensor);
  11438. LLAMA_LOG_INFO("[%4d/%4d] %36s - [%s], type = %6s, ",
  11439. ++idx, ml.n_tensors,
  11440. ggml_get_name(tensor),
  11441. llama_format_tensor_shape(tensor).c_str(),
  11442. ggml_type_name(tensor->type));
  11443. // This used to be a regex, but <regex> has an extreme cost to compile times.
  11444. bool quantize = name.rfind("weight") == name.size() - 6; // ends with 'weight'?
  11445. // quantize only 2D and 3D tensors (experts)
  11446. quantize &= (ggml_n_dims(tensor) >= 2);
  11447. // do not quantize norm tensors
  11448. quantize &= name.find("_norm.weight") == std::string::npos;
  11449. quantize &= params->quantize_output_tensor || name != "output.weight";
  11450. quantize &= !params->only_copy;
  11451. // do not quantize expert gating tensors
  11452. // NOTE: can't use LLM_TN here because the layer number is not known
  11453. quantize &= name.find("ffn_gate_inp.weight") == std::string::npos;
  11454. // do not quantize positional embeddings and token types (BERT)
  11455. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_POS_EMBD, "weight");
  11456. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_TOKEN_TYPES, "weight");
  11457. // do not quantize Mamba's small yet 2D weights
  11458. // NOTE: can't use LLM_TN here because the layer number is not known
  11459. quantize &= name.find("ssm_conv1d.weight") == std::string::npos;
  11460. quantize &= name.find("ssm_x.weight") == std::string::npos;
  11461. quantize &= name.find("ssm_dt.weight") == std::string::npos;
  11462. enum ggml_type new_type;
  11463. void * new_data;
  11464. size_t new_size;
  11465. if (quantize) {
  11466. new_type = default_type;
  11467. // get more optimal quantization type based on the tensor shape, layer, etc.
  11468. if (!params->pure && ggml_is_quantized(default_type)) {
  11469. new_type = llama_tensor_get_type(qs, new_type, tensor, ftype);
  11470. }
  11471. if (params->token_embedding_type < GGML_TYPE_COUNT && strcmp(tensor->name, "token_embd.weight") == 0) {
  11472. new_type = params->token_embedding_type;
  11473. }
  11474. if (params->output_tensor_type < GGML_TYPE_COUNT && strcmp(tensor->name, "output.weight") == 0) {
  11475. new_type = params->output_tensor_type;
  11476. }
  11477. // If we've decided to quantize to the same type the tensor is already
  11478. // in then there's nothing to do.
  11479. quantize = tensor->type != new_type;
  11480. }
  11481. if (!quantize) {
  11482. new_type = tensor->type;
  11483. new_data = tensor->data;
  11484. new_size = ggml_nbytes(tensor);
  11485. LLAMA_LOG_INFO("size = %8.3f MB\n", ggml_nbytes(tensor)/1024.0/1024.0);
  11486. } else {
  11487. const int64_t nelements = ggml_nelements(tensor);
  11488. const float * imatrix = nullptr;
  11489. if (imatrix_data) {
  11490. auto it = imatrix_data->find(tensor->name);
  11491. if (it == imatrix_data->end()) {
  11492. LLAMA_LOG_INFO("\n====== %s: did not find weights for %s\n", __func__, tensor->name);
  11493. } else {
  11494. if (it->second.size() == (size_t)tensor->ne[0]*tensor->ne[2]) {
  11495. imatrix = it->second.data();
  11496. } else {
  11497. LLAMA_LOG_INFO("\n====== %s: imatrix size %d is different from tensor size %d for %s\n", __func__,
  11498. int(it->second.size()), int(tensor->ne[0]*tensor->ne[2]), tensor->name);
  11499. // this can happen when quantizing an old mixtral model with split tensors with a new incompatible imatrix
  11500. // this is a significant error and it may be good idea to abort the process if this happens,
  11501. // since many people will miss the error and not realize that most of the model is being quantized without an imatrix
  11502. // tok_embd should be ignored in this case, since it always causes this warning
  11503. if (name != tn(LLM_TENSOR_TOKEN_EMBD, "weight")) {
  11504. throw std::runtime_error(format("imatrix size %d is different from tensor size %d for %s",
  11505. int(it->second.size()), int(tensor->ne[0]*tensor->ne[2]), tensor->name));
  11506. }
  11507. }
  11508. }
  11509. }
  11510. if ((new_type == GGML_TYPE_IQ2_XXS ||
  11511. new_type == GGML_TYPE_IQ2_XS ||
  11512. new_type == GGML_TYPE_IQ2_S ||
  11513. new_type == GGML_TYPE_IQ1_S ||
  11514. (new_type == GGML_TYPE_IQ1_M && strcmp(tensor->name, "token_embd.weight") && strcmp(tensor->name, "output.weight")) ||
  11515. (new_type == GGML_TYPE_Q2_K && params->ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && strcmp(tensor->name, "token_embd.weight") != 0)) && !imatrix) {
  11516. LLAMA_LOG_ERROR("\n\n============================================================\n");
  11517. LLAMA_LOG_ERROR("Missing importance matrix for tensor %s in a very low-bit quantization\n", tensor->name);
  11518. LLAMA_LOG_ERROR("The result will be garbage, so bailing out\n");
  11519. LLAMA_LOG_ERROR("============================================================\n\n");
  11520. throw std::runtime_error(format("Missing importance matrix for tensor %s in a very low-bit quantization", tensor->name));
  11521. }
  11522. float * f32_data;
  11523. if (tensor->type == GGML_TYPE_F32) {
  11524. f32_data = (float *) tensor->data;
  11525. } else if (ggml_is_quantized(tensor->type) && !params->allow_requantize) {
  11526. throw std::runtime_error(format("requantizing from type %s is disabled", ggml_type_name(tensor->type)));
  11527. } else {
  11528. llama_tensor_dequantize_internal(tensor, f32_conv_buf, workers, nelements, nthread);
  11529. f32_data = (float *) f32_conv_buf.data();
  11530. }
  11531. LLAMA_LOG_INFO("converting to %s .. ", ggml_type_name(new_type));
  11532. fflush(stdout);
  11533. if (work.size() < (size_t)nelements * 4) {
  11534. work.resize(nelements * 4); // upper bound on size
  11535. }
  11536. new_data = work.data();
  11537. const int64_t n_per_row = tensor->ne[0];
  11538. const int64_t nrows = tensor->ne[1];
  11539. static const int64_t min_chunk_size = 32 * 512;
  11540. 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);
  11541. const int64_t nelements_matrix = tensor->ne[0] * tensor->ne[1];
  11542. const int64_t nchunk = (nelements_matrix + chunk_size - 1)/chunk_size;
  11543. const int64_t nthread_use = nthread > 1 ? std::max((int64_t)1, std::min((int64_t)nthread, nchunk)) : 1;
  11544. // quantize each expert separately since they have different importance matrices
  11545. new_size = 0;
  11546. for (int64_t i03 = 0; i03 < tensor->ne[2]; ++i03) {
  11547. const float * f32_data_03 = f32_data + i03 * nelements_matrix;
  11548. void * new_data_03 = (char *)new_data + ggml_row_size(new_type, n_per_row) * i03 * nrows;
  11549. const float * imatrix_03 = imatrix ? imatrix + i03 * n_per_row : nullptr;
  11550. 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);
  11551. }
  11552. LLAMA_LOG_INFO("size = %8.2f MiB -> %8.2f MiB\n", ggml_nbytes(tensor)/1024.0/1024.0, new_size/1024.0/1024.0);
  11553. }
  11554. total_size_org += ggml_nbytes(tensor);
  11555. total_size_new += new_size;
  11556. // update the gguf meta data as we go
  11557. gguf_set_tensor_type(ctx_out, name.c_str(), new_type);
  11558. gguf_set_tensor_data(ctx_out, name.c_str(), new_data, new_size);
  11559. // write tensor data + padding
  11560. fout.write((const char *) new_data, new_size);
  11561. zeros(fout, GGML_PAD(new_size, align) - new_size);
  11562. }
  11563. // go back to beginning of file and write the updated meta data
  11564. {
  11565. fout.seekp(0);
  11566. std::vector<uint8_t> data(gguf_get_meta_size(ctx_out));
  11567. gguf_get_meta_data(ctx_out, data.data());
  11568. fout.write((const char *) data.data(), data.size());
  11569. }
  11570. fout.close();
  11571. gguf_free(ctx_out);
  11572. LLAMA_LOG_INFO("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  11573. LLAMA_LOG_INFO("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  11574. if (qs.n_fallback > 0) {
  11575. LLAMA_LOG_WARN("%s: WARNING: %d of %d tensor(s) required fallback quantization\n",
  11576. __func__, qs.n_fallback, qs.n_k_quantized + qs.n_fallback);
  11577. }
  11578. }
  11579. static int llama_apply_lora_from_file_internal(
  11580. const struct llama_model & model, const char * path_lora, float scale, const char * path_base_model, int n_threads
  11581. ) {
  11582. LLAMA_LOG_INFO("%s: applying lora adapter from '%s' - please wait ...\n", __func__, path_lora);
  11583. const int64_t t_start_lora_us = ggml_time_us();
  11584. llama_file fin(path_lora, "rb");
  11585. // verify magic and version
  11586. {
  11587. uint32_t magic = fin.read_u32();
  11588. if (magic != LLAMA_FILE_MAGIC_GGLA) {
  11589. LLAMA_LOG_ERROR("%s: bad file magic\n", __func__);
  11590. return 1;
  11591. }
  11592. uint32_t format_version = fin.read_u32();
  11593. if (format_version != 1) {
  11594. LLAMA_LOG_ERROR("%s: unsupported file version\n", __func__ );
  11595. return 1;
  11596. }
  11597. }
  11598. int32_t lora_r = fin.read_u32();
  11599. int32_t lora_alpha = fin.read_u32();
  11600. float scaling = scale * (float)lora_alpha / (float)lora_r;
  11601. LLAMA_LOG_INFO("%s: r = %d, alpha = %d, scaling = %.2f\n", __func__, lora_r, lora_alpha, scaling);
  11602. // load base model
  11603. std::unique_ptr<llama_model_loader> ml;
  11604. if (path_base_model) {
  11605. LLAMA_LOG_INFO("%s: loading base model from '%s'\n", __func__, path_base_model);
  11606. ml.reset(new llama_model_loader(path_base_model, /*use_mmap*/ true, /*kv_overrides*/ nullptr));
  11607. ml->init_mappings(/*prefetch*/ false); // no prefetching
  11608. }
  11609. struct tensor_meta {
  11610. std::string name;
  11611. ggml_type type;
  11612. int32_t ne[2];
  11613. size_t offset;
  11614. };
  11615. std::map<std::string, tensor_meta> tensor_meta_map;
  11616. // load all tensor meta
  11617. while (true) {
  11618. if (fin.tell() == fin.size) {
  11619. // eof
  11620. break;
  11621. }
  11622. int32_t n_dims;
  11623. int32_t name_len;
  11624. int32_t ftype;
  11625. fin.read_raw(&n_dims, sizeof(n_dims));
  11626. fin.read_raw(&name_len, sizeof(name_len));
  11627. fin.read_raw(&ftype, sizeof(ftype));
  11628. if (n_dims != 1 && n_dims != 2) {
  11629. LLAMA_LOG_ERROR("%s: unsupported tensor dimension %d\n", __func__, n_dims);
  11630. return 1;
  11631. }
  11632. int32_t ne[2] = { 1, 1 };
  11633. for (int i = 0; i < n_dims; ++i) {
  11634. fin.read_raw(&ne[i], sizeof(ne[i]));
  11635. }
  11636. std::string name;
  11637. {
  11638. GGML_ASSERT(name_len < GGML_MAX_NAME);
  11639. char buf[GGML_MAX_NAME];
  11640. fin.read_raw(buf, name_len);
  11641. name = std::string(buf, name_len);
  11642. }
  11643. // check for lora suffix
  11644. std::string lora_suffix;
  11645. if (name.length() > 6) {
  11646. lora_suffix = name.substr(name.length() - 6);
  11647. }
  11648. if (lora_suffix != ".loraA" && lora_suffix != ".loraB") {
  11649. LLAMA_LOG_ERROR("%s: error: '%s' is not a lora tensor\n", __func__, name.c_str());
  11650. return 1;
  11651. }
  11652. // tensor type
  11653. ggml_type wtype;
  11654. switch (ftype) {
  11655. case 0: wtype = GGML_TYPE_F32; break;
  11656. case 1: wtype = GGML_TYPE_F16; break;
  11657. default:
  11658. {
  11659. LLAMA_LOG_ERROR("%s: invalid tensor data type '%d'\n",
  11660. __func__, ftype);
  11661. return 1;
  11662. }
  11663. }
  11664. // data offset
  11665. size_t offset = fin.tell();
  11666. offset = (offset + 31) & -32;
  11667. // skip tensor data
  11668. fin.seek(offset + ggml_row_size(wtype, ne[0]) * ne[1], SEEK_SET);
  11669. tensor_meta_map.emplace(name, tensor_meta{ name, wtype, { ne[0], ne[1] }, offset });
  11670. }
  11671. bool warned = false;
  11672. int n_tensors = 0;
  11673. // apply
  11674. ggml_backend_t backend_cpu = ggml_backend_cpu_init();
  11675. if (backend_cpu == nullptr) {
  11676. LLAMA_LOG_ERROR("%s: error: failed to initialize cpu backend\n", __func__);
  11677. return 1;
  11678. }
  11679. ggml_backend_cpu_set_n_threads(backend_cpu, n_threads);
  11680. std::vector<no_init<uint8_t>> read_buf;
  11681. for (const auto & it : model.tensors_by_name) {
  11682. const std::string & base_name = it.first;
  11683. ggml_tensor * model_t = it.second;
  11684. if (tensor_meta_map.find(base_name + ".loraA") == tensor_meta_map.end() ||
  11685. tensor_meta_map.find(base_name + ".loraB") == tensor_meta_map.end()) {
  11686. continue;
  11687. }
  11688. tensor_meta & metaA = tensor_meta_map.at(base_name + ".loraA");
  11689. tensor_meta & metaB = tensor_meta_map.at(base_name + ".loraB");
  11690. ggml_init_params lora_init_params = {
  11691. /* .mem_size */ ggml_tensor_overhead()*128 + ggml_graph_overhead(),
  11692. /* .mem_buffer */ nullptr,
  11693. /* .no_alloc */ true,
  11694. };
  11695. ggml_context * lora_ctx = ggml_init(lora_init_params);
  11696. if (lora_ctx == nullptr) {
  11697. LLAMA_LOG_ERROR("%s: error: failed to initialize lora context\n", __func__);
  11698. ggml_backend_free(backend_cpu);
  11699. return 1;
  11700. }
  11701. // create tensors
  11702. ggml_tensor * loraA = ggml_new_tensor_2d(lora_ctx, metaA.type, metaA.ne[0], metaA.ne[1]);
  11703. ggml_tensor * loraB = ggml_new_tensor_2d(lora_ctx, metaB.type, metaB.ne[0], metaB.ne[1]);
  11704. ggml_set_name(loraA, metaA.name.c_str());
  11705. ggml_set_name(loraB, metaB.name.c_str());
  11706. ggml_tensor * base_t;
  11707. if (ml) {
  11708. if (!ml->get_tensor_meta(base_name.c_str())) {
  11709. LLAMA_LOG_ERROR("%s: error: tensor '%s' not found in base model\n", __func__, base_name.c_str());
  11710. return 1;
  11711. }
  11712. base_t = ggml_dup_tensor(lora_ctx, ml->get_tensor_meta(base_name.c_str()));
  11713. } else {
  11714. base_t = ggml_dup_tensor(lora_ctx, model_t);
  11715. }
  11716. ggml_set_name(base_t, base_name.c_str());
  11717. // allocate in backend buffer
  11718. ggml_backend_buffer_t lora_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  11719. if (lora_buf == nullptr) {
  11720. LLAMA_LOG_ERROR("%s: error: failed to allocate lora tensors\n", __func__);
  11721. return 1;
  11722. }
  11723. // load tensor data
  11724. auto load_tensor = [&read_buf, &fin](const tensor_meta & tensor_meta, ggml_tensor * tensor) {
  11725. read_buf.resize(ggml_nbytes(tensor));
  11726. fin.seek(tensor_meta.offset, SEEK_SET);
  11727. fin.read_raw(read_buf.data(), ggml_nbytes(tensor));
  11728. ggml_backend_tensor_set(tensor, read_buf.data(), 0, read_buf.size());
  11729. };
  11730. load_tensor(metaA, loraA);
  11731. load_tensor(metaB, loraB);
  11732. // load base model tensor data
  11733. if (ml) {
  11734. ml->load_data_for(base_t);
  11735. } else {
  11736. ggml_backend_tensor_copy(model_t, base_t);
  11737. }
  11738. if (ggml_is_quantized(base_t->type) && !warned) {
  11739. LLAMA_LOG_WARN("%s: warning: using a lora adapter with a quantized model may result in poor quality, "
  11740. "use a f16 or f32 base model with --lora-base\n", __func__);
  11741. warned = true;
  11742. }
  11743. if (base_t->ne[0] != loraA->ne[1] || base_t->ne[1] != loraB->ne[1]) {
  11744. LLAMA_LOG_ERROR("%s: incompatible tensor dimensions (%" PRId64 " and %" PRId64 ");"
  11745. " are you sure that this adapter is for this model?\n", __func__, base_t->ne[0], loraA->ne[1]);
  11746. ggml_free(lora_ctx);
  11747. ggml_backend_buffer_free(lora_buf);
  11748. ggml_backend_free(backend_cpu);
  11749. return 1;
  11750. }
  11751. auto build_lora_graph = [&]() {
  11752. // w = w + BA*s
  11753. ggml_tensor * BA = ggml_mul_mat(lora_ctx, loraA, loraB);
  11754. ggml_set_name(BA, "BA");
  11755. if (scaling != 1.0f) {
  11756. BA = ggml_scale(lora_ctx, BA, scaling);
  11757. ggml_set_name(BA, "BA_scaled");
  11758. }
  11759. ggml_tensor * r;
  11760. r = ggml_add_inplace(lora_ctx, base_t, BA);
  11761. ggml_set_name(r, "r_add");
  11762. if (base_t->type != model_t->type) {
  11763. // convert the result to the model type
  11764. r = ggml_cast(lora_ctx, r, model_t->type);
  11765. ggml_set_name(r, "r_cast");
  11766. }
  11767. return r;
  11768. };
  11769. ggml_cgraph * gf = ggml_new_graph(lora_ctx);
  11770. ggml_tensor * r = build_lora_graph();
  11771. ggml_build_forward_expand(gf, r);
  11772. ggml_backend_buffer_t graph_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  11773. if (graph_buf == nullptr) {
  11774. LLAMA_LOG_ERROR("%s: error: failed to allocate graph tensors\n", __func__);
  11775. ggml_free(lora_ctx);
  11776. ggml_backend_buffer_free(lora_buf);
  11777. ggml_backend_free(backend_cpu);
  11778. return 1;
  11779. }
  11780. ggml_backend_graph_compute(backend_cpu, gf);
  11781. ggml_backend_tensor_set(model_t, r->data, 0, ggml_nbytes(r));
  11782. #if 0
  11783. // TODO: use scheduler with fallback to CPU for less copies between CPU and GPU
  11784. //ggml_backend_sched_t sched = ggml_backend_sched_new(backends.data(), backends.size(), GGML_DEFAULT_GRAPH_SIZE);
  11785. // sched compute
  11786. ggml_build_forward_expand(gf, build_graph());
  11787. ggml_backend_sched_init_measure(sched, gf);
  11788. // create the graph again, since the previous one was destroyed by the measure
  11789. ggml_graph_clear(gf);
  11790. ggml_build_forward_expand(gf, build_graph());
  11791. ggml_backend_sched_graph_compute(sched, gf);
  11792. ggml_backend_sched_free(sched);
  11793. #endif
  11794. ggml_backend_buffer_free(lora_buf);
  11795. ggml_backend_buffer_free(graph_buf);
  11796. ggml_free(lora_ctx);
  11797. n_tensors++;
  11798. if (n_tensors % 4 == 0) {
  11799. LLAMA_LOG_INFO(".");
  11800. }
  11801. }
  11802. ggml_backend_free(backend_cpu);
  11803. const int64_t t_lora_us = ggml_time_us() - t_start_lora_us;
  11804. LLAMA_LOG_INFO(" done (%.2f ms)\n", t_lora_us / 1000.0);
  11805. return 0;
  11806. }
  11807. //
  11808. // interface implementation
  11809. //
  11810. struct llama_model_params llama_model_default_params() {
  11811. struct llama_model_params result = {
  11812. /*.n_gpu_layers =*/ 0,
  11813. /*.split_mode =*/ LLAMA_SPLIT_MODE_LAYER,
  11814. /*.main_gpu =*/ 0,
  11815. /*.tensor_split =*/ nullptr,
  11816. /*.progress_callback =*/ nullptr,
  11817. /*.progress_callback_user_data =*/ nullptr,
  11818. /*.kv_overrides =*/ nullptr,
  11819. /*.vocab_only =*/ false,
  11820. /*.use_mmap =*/ true,
  11821. /*.use_mlock =*/ false,
  11822. };
  11823. #ifdef GGML_USE_METAL
  11824. // note: we usually have plenty of VRAM, so by default offload all layers to the GPU
  11825. result.n_gpu_layers = 999;
  11826. #endif
  11827. return result;
  11828. }
  11829. struct llama_context_params llama_context_default_params() {
  11830. struct llama_context_params result = {
  11831. /*.seed =*/ LLAMA_DEFAULT_SEED,
  11832. /*.n_ctx =*/ 512,
  11833. /*.n_batch =*/ 2048,
  11834. /*.n_ubatch =*/ 512,
  11835. /*.n_seq_max =*/ 1,
  11836. /*.n_threads =*/ GGML_DEFAULT_N_THREADS, // TODO: better default
  11837. /*.n_threads_batch =*/ GGML_DEFAULT_N_THREADS,
  11838. /*.rope_scaling_type =*/ LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED,
  11839. /*.pooling_type =*/ LLAMA_POOLING_TYPE_UNSPECIFIED,
  11840. /*.rope_freq_base =*/ 0.0f,
  11841. /*.rope_freq_scale =*/ 0.0f,
  11842. /*.yarn_ext_factor =*/ -1.0f,
  11843. /*.yarn_attn_factor =*/ 1.0f,
  11844. /*.yarn_beta_fast =*/ 32.0f,
  11845. /*.yarn_beta_slow =*/ 1.0f,
  11846. /*.yarn_orig_ctx =*/ 0,
  11847. /*.defrag_thold =*/ -1.0f,
  11848. /*.cb_eval =*/ nullptr,
  11849. /*.cb_eval_user_data =*/ nullptr,
  11850. /*.type_k =*/ GGML_TYPE_F16,
  11851. /*.type_v =*/ GGML_TYPE_F16,
  11852. /*.logits_all =*/ false,
  11853. /*.embeddings =*/ false,
  11854. /*.offload_kqv =*/ true,
  11855. /*.abort_callback =*/ nullptr,
  11856. /*.abort_callback_data =*/ nullptr,
  11857. };
  11858. return result;
  11859. }
  11860. struct llama_model_quantize_params llama_model_quantize_default_params() {
  11861. struct llama_model_quantize_params result = {
  11862. /*.nthread =*/ 0,
  11863. /*.ftype =*/ LLAMA_FTYPE_MOSTLY_Q5_1,
  11864. /*.output_tensor_type =*/ GGML_TYPE_COUNT,
  11865. /*.token_embedding_type =*/ GGML_TYPE_COUNT,
  11866. /*.allow_requantize =*/ false,
  11867. /*.quantize_output_tensor =*/ true,
  11868. /*.only_copy =*/ false,
  11869. /*.pure =*/ false,
  11870. /*.imatrix =*/ nullptr,
  11871. /*.kv_overrides =*/ nullptr,
  11872. };
  11873. return result;
  11874. }
  11875. size_t llama_max_devices(void) {
  11876. #if defined(GGML_USE_METAL)
  11877. return 1;
  11878. #elif defined(GGML_USE_CUDA)
  11879. return GGML_CUDA_MAX_DEVICES;
  11880. #elif defined(GGML_USE_SYCL)
  11881. return GGML_SYCL_MAX_DEVICES;
  11882. #elif defined(GGML_USE_VULKAN)
  11883. return GGML_VK_MAX_DEVICES;
  11884. #else
  11885. return 1;
  11886. #endif
  11887. }
  11888. bool llama_supports_mmap(void) {
  11889. return llama_mmap::SUPPORTED;
  11890. }
  11891. bool llama_supports_mlock(void) {
  11892. return llama_mlock::SUPPORTED;
  11893. }
  11894. bool llama_supports_gpu_offload(void) {
  11895. #if defined(GGML_USE_CUDA) || defined(GGML_USE_CLBLAST) || defined(GGML_USE_METAL) || defined(GGML_USE_VULKAN) || \
  11896. defined(GGML_USE_SYCL) || defined(GGML_USE_KOMPUTE)
  11897. // Defined when llama.cpp is compiled with support for offloading model layers to GPU.
  11898. return true;
  11899. #else
  11900. return false;
  11901. #endif
  11902. }
  11903. void llama_backend_init(void) {
  11904. ggml_time_init();
  11905. // needed to initialize f16 tables
  11906. {
  11907. struct ggml_init_params params = { 0, NULL, false };
  11908. struct ggml_context * ctx = ggml_init(params);
  11909. ggml_free(ctx);
  11910. }
  11911. #ifdef GGML_USE_MPI
  11912. ggml_mpi_backend_init();
  11913. #endif
  11914. }
  11915. void llama_numa_init(enum ggml_numa_strategy numa) {
  11916. if (numa != GGML_NUMA_STRATEGY_DISABLED) {
  11917. ggml_numa_init(numa);
  11918. }
  11919. }
  11920. void llama_backend_free(void) {
  11921. #ifdef GGML_USE_MPI
  11922. ggml_mpi_backend_free();
  11923. #endif
  11924. ggml_quantize_free();
  11925. }
  11926. int64_t llama_time_us(void) {
  11927. return ggml_time_us();
  11928. }
  11929. struct llama_model * llama_load_model_from_file(
  11930. const char * path_model,
  11931. struct llama_model_params params) {
  11932. ggml_time_init();
  11933. llama_model * model = new llama_model;
  11934. unsigned cur_percentage = 0;
  11935. if (params.progress_callback == NULL) {
  11936. params.progress_callback_user_data = &cur_percentage;
  11937. params.progress_callback = [](float progress, void * ctx) {
  11938. unsigned * cur_percentage_p = (unsigned *) ctx;
  11939. unsigned percentage = (unsigned) (100 * progress);
  11940. while (percentage > *cur_percentage_p) {
  11941. *cur_percentage_p = percentage;
  11942. LLAMA_LOG_INFO(".");
  11943. if (percentage >= 100) {
  11944. LLAMA_LOG_INFO("\n");
  11945. }
  11946. }
  11947. return true;
  11948. };
  11949. }
  11950. int status = llama_model_load(path_model, *model, params);
  11951. GGML_ASSERT(status <= 0);
  11952. if (status < 0) {
  11953. if (status == -1) {
  11954. LLAMA_LOG_ERROR("%s: failed to load model\n", __func__);
  11955. } else if (status == -2) {
  11956. LLAMA_LOG_INFO("%s: cancelled model load\n", __func__);
  11957. }
  11958. delete model;
  11959. return nullptr;
  11960. }
  11961. return model;
  11962. }
  11963. void llama_free_model(struct llama_model * model) {
  11964. delete model;
  11965. }
  11966. struct llama_context * llama_new_context_with_model(
  11967. struct llama_model * model,
  11968. struct llama_context_params params) {
  11969. if (!model) {
  11970. LLAMA_LOG_ERROR("%s: model cannot be NULL\n", __func__);
  11971. return nullptr;
  11972. }
  11973. if (params.n_batch == 0 && params.n_ubatch == 0) {
  11974. LLAMA_LOG_ERROR("%s: n_batch and n_ubatch cannot both be zero\n", __func__);
  11975. return nullptr;
  11976. }
  11977. if (params.n_ctx == 0 && model->hparams.n_ctx_train == 0) {
  11978. LLAMA_LOG_ERROR("%s: n_ctx and model->hparams.n_ctx_train cannot both be zero\n", __func__);
  11979. return nullptr;
  11980. }
  11981. llama_context * ctx = new llama_context(*model);
  11982. const auto & hparams = model->hparams;
  11983. auto & cparams = ctx->cparams;
  11984. cparams.n_seq_max = std::max(1u, params.n_seq_max);
  11985. cparams.n_threads = params.n_threads;
  11986. cparams.n_threads_batch = params.n_threads_batch;
  11987. cparams.yarn_ext_factor = params.yarn_ext_factor;
  11988. cparams.yarn_attn_factor = params.yarn_attn_factor;
  11989. cparams.yarn_beta_fast = params.yarn_beta_fast;
  11990. cparams.yarn_beta_slow = params.yarn_beta_slow;
  11991. cparams.defrag_thold = params.defrag_thold;
  11992. cparams.embeddings = params.embeddings;
  11993. cparams.offload_kqv = params.offload_kqv;
  11994. cparams.pooling_type = params.pooling_type;
  11995. cparams.n_ctx = params.n_ctx == 0 ? hparams.n_ctx_train : params.n_ctx;
  11996. cparams.rope_freq_base = params.rope_freq_base == 0.0f ? hparams.rope_freq_base_train : params.rope_freq_base;
  11997. cparams.rope_freq_scale = params.rope_freq_scale == 0.0f ? hparams.rope_freq_scale_train : params.rope_freq_scale;
  11998. // this is necessary due to kv_self.n being padded later during inference
  11999. cparams.n_ctx = GGML_PAD(cparams.n_ctx, 32);
  12000. // with causal attention, the batch size is limited by the context size
  12001. cparams.n_batch = hparams.causal_attn ? std::min(cparams.n_ctx, params.n_batch) : params.n_batch;
  12002. cparams.n_ubatch = std::min(cparams.n_batch, params.n_ubatch == 0 ? params.n_batch : params.n_ubatch);
  12003. cparams.n_yarn_orig_ctx = params.yarn_orig_ctx != 0 ? params.yarn_orig_ctx :
  12004. hparams.n_yarn_orig_ctx != 0 ? hparams.n_yarn_orig_ctx :
  12005. hparams.n_ctx_train;
  12006. cparams.cb_eval = params.cb_eval;
  12007. cparams.cb_eval_user_data = params.cb_eval_user_data;
  12008. auto rope_scaling_type = params.rope_scaling_type;
  12009. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED) {
  12010. rope_scaling_type = hparams.rope_scaling_type_train;
  12011. }
  12012. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_NONE) {
  12013. cparams.rope_freq_scale = 1.0f; // never scale if scaling type is none
  12014. }
  12015. if (cparams.yarn_ext_factor < 0.0f) { // negative indicates 'not set'
  12016. cparams.yarn_ext_factor = rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_YARN ? 1.0f : 0.0f;
  12017. }
  12018. cparams.causal_attn = hparams.causal_attn;
  12019. if (cparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  12020. if (hparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  12021. cparams.pooling_type = LLAMA_POOLING_TYPE_NONE;
  12022. } else {
  12023. cparams.pooling_type = hparams.pooling_type;
  12024. }
  12025. }
  12026. if (params.seed == LLAMA_DEFAULT_SEED) {
  12027. params.seed = time(NULL);
  12028. }
  12029. LLAMA_LOG_INFO("%s: n_ctx = %u\n", __func__, cparams.n_ctx);
  12030. LLAMA_LOG_INFO("%s: n_batch = %u\n", __func__, cparams.n_batch);
  12031. LLAMA_LOG_INFO("%s: n_ubatch = %u\n", __func__, cparams.n_ubatch);
  12032. LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, cparams.rope_freq_base);
  12033. LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, cparams.rope_freq_scale);
  12034. ctx->abort_callback = params.abort_callback;
  12035. ctx->abort_callback_data = params.abort_callback_data;
  12036. ctx->rng = std::mt19937(params.seed);
  12037. ctx->logits_all = params.logits_all;
  12038. uint32_t kv_size = cparams.n_ctx;
  12039. ggml_type type_k = params.type_k;
  12040. ggml_type type_v = params.type_v;
  12041. // Mamba only needs a constant number of KV cache cells per sequence
  12042. if (model->arch == LLM_ARCH_MAMBA) {
  12043. // Mamba needs at least as many KV cells as there are sequences kept at any time
  12044. kv_size = std::max((uint32_t) 1, params.n_seq_max);
  12045. // it's probably best to keep as much precision as possible for the states
  12046. type_k = GGML_TYPE_F32; // required by ggml_ssm_conv for Mamba's conv_states
  12047. type_v = GGML_TYPE_F32; // required by ggml_ssm_scan for Mamba's ssm_states
  12048. }
  12049. GGML_ASSERT(hparams.n_embd_head_k % ggml_blck_size(type_k) == 0);
  12050. GGML_ASSERT(hparams.n_embd_head_v % ggml_blck_size(type_v) == 0);
  12051. if (!hparams.vocab_only) {
  12052. // initialize backends
  12053. #ifdef GGML_USE_METAL
  12054. if (model->n_gpu_layers > 0) {
  12055. ctx->backend_metal = ggml_backend_metal_init();
  12056. if (ctx->backend_metal == nullptr) {
  12057. LLAMA_LOG_ERROR("%s: failed to initialize Metal backend\n", __func__);
  12058. llama_free(ctx);
  12059. return nullptr;
  12060. }
  12061. ctx->backends.push_back(ctx->backend_metal);
  12062. }
  12063. #elif defined(GGML_USE_CUDA)
  12064. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  12065. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  12066. ggml_backend_t backend = ggml_backend_cuda_init(model->main_gpu);
  12067. if (backend == nullptr) {
  12068. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, model->main_gpu);
  12069. llama_free(ctx);
  12070. return nullptr;
  12071. }
  12072. ctx->backends.push_back(backend);
  12073. } else {
  12074. // LLAMA_SPLIT_MODE_LAYER requires a backend for each GPU
  12075. for (int device = 0; device < ggml_backend_cuda_get_device_count(); ++device) {
  12076. ggml_backend_t backend = ggml_backend_cuda_init(device);
  12077. if (backend == nullptr) {
  12078. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, device);
  12079. llama_free(ctx);
  12080. return nullptr;
  12081. }
  12082. ctx->backends.push_back(backend);
  12083. }
  12084. }
  12085. #elif defined(GGML_USE_VULKAN)
  12086. if (model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  12087. LLAMA_LOG_ERROR("%s: Row split not supported. Failed to initialize Vulkan backend\n", __func__);
  12088. llama_free(ctx);
  12089. return nullptr;
  12090. }
  12091. if (model->split_mode == LLAMA_SPLIT_MODE_NONE) {
  12092. ggml_backend_t backend = ggml_backend_vk_init(0);
  12093. if (backend == nullptr) {
  12094. LLAMA_LOG_ERROR("%s: failed to initialize Vulkan backend\n", __func__);
  12095. llama_free(ctx);
  12096. return nullptr;
  12097. }
  12098. ctx->backends.push_back(backend);
  12099. } else {
  12100. for (int device = 0; device < ggml_backend_vk_get_device_count(); ++device) {
  12101. ggml_backend_t backend = ggml_backend_vk_init(device);
  12102. if (backend == nullptr) {
  12103. LLAMA_LOG_ERROR("%s: failed to initialize Vulkan%d backend\n", __func__, device);
  12104. llama_free(ctx);
  12105. return nullptr;
  12106. }
  12107. ctx->backends.push_back(backend);
  12108. }
  12109. }
  12110. #elif defined(GGML_USE_SYCL)
  12111. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  12112. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  12113. ggml_backend_t backend = ggml_backend_sycl_init(model->main_gpu);
  12114. if (backend == nullptr) {
  12115. int main_gpu_id = ggml_backend_sycl_get_device_id(model->main_gpu);
  12116. LLAMA_LOG_ERROR("%s: failed to initialize SYCL%d (index %d) backend\n", __func__, main_gpu_id, model->main_gpu);
  12117. llama_free(ctx);
  12118. return nullptr;
  12119. }
  12120. ctx->backends.push_back(backend);
  12121. } else {
  12122. // LLAMA_SPLIT_LAYER requires a backend for each GPU
  12123. for (int i = 0; i < ggml_backend_sycl_get_device_count(); ++i) {
  12124. ggml_backend_t backend = ggml_backend_sycl_init(i);
  12125. if (backend == nullptr) {
  12126. int id_list[GGML_SYCL_MAX_DEVICES];
  12127. ggml_sycl_get_gpu_list(id_list, GGML_SYCL_MAX_DEVICES);
  12128. LLAMA_LOG_ERROR("%s: failed to initialize SYCL%d (index %d) backend\n", __func__, id_list[i], i);
  12129. llama_free(ctx);
  12130. return nullptr;
  12131. }
  12132. ctx->backends.push_back(backend);
  12133. }
  12134. }
  12135. #elif defined(GGML_USE_KOMPUTE)
  12136. if (model->n_gpu_layers > 0) {
  12137. auto * backend = ggml_backend_kompute_init(model->main_gpu);
  12138. if (backend == nullptr) {
  12139. LLAMA_LOG_ERROR("%s: failed to initialize Kompute backend\n", __func__);
  12140. llama_free(ctx);
  12141. return nullptr;
  12142. }
  12143. ctx->backends.push_back(backend);
  12144. }
  12145. #endif
  12146. ctx->backend_cpu = ggml_backend_cpu_init();
  12147. if (ctx->backend_cpu == nullptr) {
  12148. LLAMA_LOG_ERROR("%s: failed to initialize CPU backend\n", __func__);
  12149. llama_free(ctx);
  12150. return nullptr;
  12151. }
  12152. ctx->backends.push_back(ctx->backend_cpu);
  12153. if (!llama_kv_cache_init(ctx->kv_self, ctx->model, type_k, type_v, kv_size, cparams.offload_kqv)) {
  12154. LLAMA_LOG_ERROR("%s: llama_kv_cache_init() failed for self-attention cache\n", __func__);
  12155. llama_free(ctx);
  12156. return nullptr;
  12157. }
  12158. {
  12159. size_t memory_size_k = 0;
  12160. size_t memory_size_v = 0;
  12161. for (auto & k : ctx->kv_self.k_l) {
  12162. memory_size_k += ggml_nbytes(k);
  12163. }
  12164. for (auto & v : ctx->kv_self.v_l) {
  12165. memory_size_v += ggml_nbytes(v);
  12166. }
  12167. LLAMA_LOG_INFO("%s: KV self size = %7.2f MiB, K (%s): %7.2f MiB, V (%s): %7.2f MiB\n", __func__,
  12168. (float)(memory_size_k + memory_size_v) / (1024.0f * 1024.0f),
  12169. ggml_type_name(type_k), (float)memory_size_k / (1024.0f * 1024.0f),
  12170. ggml_type_name(type_v), (float)memory_size_v / (1024.0f * 1024.0f));
  12171. }
  12172. // graph outputs buffer
  12173. {
  12174. // resized during inference when a batch uses more outputs
  12175. if (llama_output_reserve(*ctx, params.n_seq_max) < params.n_seq_max) {
  12176. LLAMA_LOG_ERROR("%s: failed to reserve initial output buffer\n", __func__);
  12177. llama_free(ctx);
  12178. return nullptr;
  12179. }
  12180. LLAMA_LOG_INFO("%s: %10s output buffer size = %8.2f MiB\n", __func__,
  12181. ggml_backend_buffer_name(ctx->buf_output),
  12182. ggml_backend_buffer_get_size(ctx->buf_output) / 1024.0 / 1024.0);
  12183. }
  12184. // scheduler and compute buffers
  12185. {
  12186. // buffer types used for the compute buffer of each backend
  12187. std::vector<ggml_backend_buffer_type_t> backend_buft;
  12188. for (auto * backend : ctx->backends) {
  12189. if (ggml_backend_is_cpu(backend)) {
  12190. // use host buffers for the CPU backend compute buffer
  12191. backend_buft.push_back(llama_default_buffer_type_cpu(true));
  12192. } else {
  12193. backend_buft.push_back(ggml_backend_get_default_buffer_type(backend));
  12194. }
  12195. }
  12196. // buffer used to store the computation graph and the tensor meta data
  12197. ctx->buf_compute_meta.resize(ggml_tensor_overhead()*LLAMA_MAX_NODES + ggml_graph_overhead_custom(LLAMA_MAX_NODES, false));
  12198. // enabling pipeline parallelism in the scheduler increases memory usage, so it is only done when necessary
  12199. bool pipeline_parallel = llama_get_device_count() > 1 && model->n_gpu_layers > (int)model->hparams.n_layer && model->split_mode == LLAMA_SPLIT_MODE_LAYER;
  12200. #ifndef GGML_USE_CUDA
  12201. // pipeline parallelism requires support for async compute and events
  12202. // currently this is only implemented in the CUDA backend
  12203. pipeline_parallel = false;
  12204. #endif
  12205. ctx->sched = ggml_backend_sched_new(ctx->backends.data(), backend_buft.data(), ctx->backends.size(), LLAMA_MAX_NODES, pipeline_parallel);
  12206. if (pipeline_parallel) {
  12207. LLAMA_LOG_INFO("%s: pipeline parallelism enabled (n_copies=%d)\n", __func__, ggml_backend_sched_get_n_copies(ctx->sched));
  12208. }
  12209. // build worst-case graph
  12210. int n_tokens = (int)std::min(cparams.n_ctx, cparams.n_ubatch);
  12211. int n_past = cparams.n_ctx - n_tokens;
  12212. 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
  12213. ggml_cgraph * gf = llama_build_graph(*ctx, llama_batch_get_one(&token, n_tokens, n_past, 0), true);
  12214. // initialize scheduler with the worst-case graph
  12215. if (!ggml_backend_sched_reserve(ctx->sched, gf)) {
  12216. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  12217. llama_free(ctx);
  12218. return nullptr;
  12219. }
  12220. for (size_t i = 0; i < ctx->backends.size(); i++) {
  12221. ggml_backend_t backend = ctx->backends[i];
  12222. ggml_backend_buffer_type_t buft = backend_buft[i];
  12223. size_t size = ggml_backend_sched_get_buffer_size(ctx->sched, backend);
  12224. if (size > 1) {
  12225. LLAMA_LOG_INFO("%s: %10s compute buffer size = %8.2f MiB\n", __func__,
  12226. ggml_backend_buft_name(buft),
  12227. size / 1024.0 / 1024.0);
  12228. }
  12229. }
  12230. // note: the number of splits during measure is higher than during inference due to the kv shift
  12231. int n_splits = ggml_backend_sched_get_n_splits(ctx->sched);
  12232. LLAMA_LOG_INFO("%s: graph nodes = %d\n", __func__, gf->n_nodes);
  12233. LLAMA_LOG_INFO("%s: graph splits = %d\n", __func__, n_splits);
  12234. }
  12235. }
  12236. #ifdef GGML_USE_MPI
  12237. ctx->ctx_mpi = ggml_mpi_init();
  12238. if (ggml_mpi_rank(ctx->ctx_mpi) > 0) {
  12239. // Enter a blocking eval loop with dummy input, letting rank=0 drive the process
  12240. // TODO: needs fix after #3228
  12241. GGML_ASSERT(false && "not implemented");
  12242. //const std::vector<llama_token> tmp(ctx->model.hparams.n_ctx, llama_token_bos(ctx));
  12243. //while (!llama_eval(ctx, tmp.data(), tmp.size(), 0, 0)) {};
  12244. llama_backend_free();
  12245. exit(1);
  12246. }
  12247. #endif
  12248. return ctx;
  12249. }
  12250. void llama_free(struct llama_context * ctx) {
  12251. delete ctx;
  12252. }
  12253. const llama_model * llama_get_model(const struct llama_context * ctx) {
  12254. return &ctx->model;
  12255. }
  12256. uint32_t llama_n_ctx(const struct llama_context * ctx) {
  12257. return ctx->cparams.n_ctx;
  12258. }
  12259. uint32_t llama_n_batch(const struct llama_context * ctx) {
  12260. return ctx->cparams.n_batch;
  12261. }
  12262. uint32_t llama_n_ubatch(const struct llama_context * ctx) {
  12263. return ctx->cparams.n_ubatch;
  12264. }
  12265. uint32_t llama_n_seq_max(const struct llama_context * ctx) {
  12266. return ctx->kv_self.size;
  12267. }
  12268. enum llama_vocab_type llama_vocab_type(const struct llama_model * model) {
  12269. return model->vocab.type;
  12270. }
  12271. enum llama_rope_type llama_rope_type(const struct llama_model * model) {
  12272. switch (model->arch) {
  12273. // these models do not use RoPE
  12274. case LLM_ARCH_GPT2:
  12275. case LLM_ARCH_GPTJ:
  12276. case LLM_ARCH_GPTNEOX:
  12277. case LLM_ARCH_MPT:
  12278. case LLM_ARCH_REFACT:
  12279. case LLM_ARCH_BLOOM:
  12280. case LLM_ARCH_MAMBA:
  12281. return LLAMA_ROPE_TYPE_NONE;
  12282. // use what we call a normal RoPE, operating on pairs of consecutive head values
  12283. case LLM_ARCH_LLAMA:
  12284. case LLM_ARCH_BAICHUAN:
  12285. case LLM_ARCH_STARCODER:
  12286. case LLM_ARCH_PLAMO:
  12287. case LLM_ARCH_CODESHELL:
  12288. case LLM_ARCH_ORION:
  12289. case LLM_ARCH_INTERNLM2:
  12290. case LLM_ARCH_MINICPM:
  12291. case LLM_ARCH_XVERSE:
  12292. case LLM_ARCH_COMMAND_R:
  12293. return LLAMA_ROPE_TYPE_NORM;
  12294. // the pairs of head values are offset by n_rot/2
  12295. case LLM_ARCH_FALCON:
  12296. case LLM_ARCH_GROK:
  12297. case LLM_ARCH_DBRX:
  12298. case LLM_ARCH_PERSIMMON:
  12299. case LLM_ARCH_BERT:
  12300. case LLM_ARCH_NOMIC_BERT:
  12301. case LLM_ARCH_STABLELM:
  12302. case LLM_ARCH_QWEN:
  12303. case LLM_ARCH_QWEN2:
  12304. case LLM_ARCH_PHI2:
  12305. case LLM_ARCH_GEMMA:
  12306. case LLM_ARCH_STARCODER2:
  12307. return LLAMA_ROPE_TYPE_NEOX;
  12308. // all model arches should be listed explicitly here
  12309. case LLM_ARCH_UNKNOWN:
  12310. GGML_ASSERT(false && "unknown architecture");
  12311. break;
  12312. }
  12313. return LLAMA_ROPE_TYPE_NONE;
  12314. }
  12315. int32_t llama_n_vocab(const struct llama_model * model) {
  12316. return model->hparams.n_vocab;
  12317. }
  12318. int32_t llama_n_ctx_train(const struct llama_model * model) {
  12319. return model->hparams.n_ctx_train;
  12320. }
  12321. int32_t llama_n_embd(const struct llama_model * model) {
  12322. return model->hparams.n_embd;
  12323. }
  12324. int32_t llama_n_layer(const struct llama_model * model) {
  12325. return model->hparams.n_layer;
  12326. }
  12327. float llama_rope_freq_scale_train(const struct llama_model * model) {
  12328. return model->hparams.rope_freq_scale_train;
  12329. }
  12330. int32_t llama_model_meta_val_str(const struct llama_model * model, const char * key, char * buf, size_t buf_size) {
  12331. const auto & it = model->gguf_kv.find(key);
  12332. if (it == model->gguf_kv.end()) {
  12333. if (buf_size > 0) {
  12334. buf[0] = '\0';
  12335. }
  12336. return -1;
  12337. }
  12338. return snprintf(buf, buf_size, "%s", it->second.c_str());
  12339. }
  12340. int32_t llama_model_meta_count(const struct llama_model * model) {
  12341. return (int)model->gguf_kv.size();
  12342. }
  12343. int32_t llama_model_meta_key_by_index(const struct llama_model * model, int i, char * buf, size_t buf_size) {
  12344. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  12345. if (buf_size > 0) {
  12346. buf[0] = '\0';
  12347. }
  12348. return -1;
  12349. }
  12350. auto it = model->gguf_kv.begin();
  12351. std::advance(it, i);
  12352. return snprintf(buf, buf_size, "%s", it->first.c_str());
  12353. }
  12354. int32_t llama_model_meta_val_str_by_index(const struct llama_model * model, int32_t i, char * buf, size_t buf_size) {
  12355. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  12356. if (buf_size > 0) {
  12357. buf[0] = '\0';
  12358. }
  12359. return -1;
  12360. }
  12361. auto it = model->gguf_kv.begin();
  12362. std::advance(it, i);
  12363. return snprintf(buf, buf_size, "%s", it->second.c_str());
  12364. }
  12365. int32_t llama_model_desc(const struct llama_model * model, char * buf, size_t buf_size) {
  12366. return snprintf(buf, buf_size, "%s %s %s",
  12367. llama_model_arch_name(model->arch),
  12368. llama_model_type_name(model->type),
  12369. llama_model_ftype_name(model->ftype).c_str());
  12370. }
  12371. uint64_t llama_model_size(const struct llama_model * model) {
  12372. uint64_t size = 0;
  12373. for (const auto & it : model->tensors_by_name) {
  12374. size += ggml_nbytes(it.second);
  12375. }
  12376. return size;
  12377. }
  12378. uint64_t llama_model_n_params(const struct llama_model * model) {
  12379. uint64_t nparams = 0;
  12380. for (const auto & it : model->tensors_by_name) {
  12381. nparams += ggml_nelements(it.second);
  12382. }
  12383. return nparams;
  12384. }
  12385. struct ggml_tensor * llama_get_model_tensor(struct llama_model * model, const char * name) {
  12386. auto it = std::find_if(model->tensors_by_name.begin(), model->tensors_by_name.end(),
  12387. [name](const std::pair<std::string, struct ggml_tensor *> & it) {
  12388. return it.first == name;
  12389. });
  12390. if (it == model->tensors_by_name.end()) {
  12391. return nullptr;
  12392. }
  12393. return it->second;
  12394. }
  12395. uint32_t llama_model_quantize(
  12396. const char * fname_inp,
  12397. const char * fname_out,
  12398. const llama_model_quantize_params * params) {
  12399. try {
  12400. llama_model_quantize_internal(fname_inp, fname_out, params);
  12401. return 0;
  12402. } catch (const std::exception & err) {
  12403. LLAMA_LOG_ERROR("%s: failed to quantize: %s\n", __func__, err.what());
  12404. return 1;
  12405. }
  12406. }
  12407. 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) {
  12408. try {
  12409. return llama_apply_lora_from_file_internal(*model, path_lora, scale, path_base_model, n_threads);
  12410. } catch (const std::exception & err) {
  12411. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  12412. return 1;
  12413. }
  12414. }
  12415. static bool llama_control_vector_init(struct llama_control_vector & cvec, const llama_model & model) {
  12416. GGML_ASSERT(cvec.tensors.empty());
  12417. GGML_ASSERT(cvec.ctxs.empty());
  12418. GGML_ASSERT(cvec.bufs.empty());
  12419. // count layer buffer types
  12420. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  12421. for (int64_t i = 0; i < model.hparams.n_layer; i++) {
  12422. buft_layer_count[model.buft_layer[i].buft]++;
  12423. }
  12424. // allocate contexts
  12425. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  12426. for (auto & it : buft_layer_count) {
  12427. int n_layers = it.second;
  12428. struct ggml_init_params params = {
  12429. /*.mem_size =*/ n_layers * ggml_tensor_overhead(),
  12430. /*.mem_buffer =*/ NULL,
  12431. /*.no_alloc =*/ true,
  12432. };
  12433. ggml_context * ctx = ggml_init(params);
  12434. if (!ctx) {
  12435. LLAMA_LOG_ERROR("%s: failed to allocate context for control vector\n", __func__);
  12436. return 1;
  12437. }
  12438. ctx_map[it.first] = ctx;
  12439. }
  12440. // make tensors
  12441. cvec.tensors.push_back(nullptr); // there's never a tensor for layer 0
  12442. for (size_t il = 1; il < model.hparams.n_layer; il++) {
  12443. struct ggml_context * ctx = ctx_map.at(model.buft_layer[il].buft);
  12444. ggml_tensor * tensor = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, model.hparams.n_embd);
  12445. cvec.tensors.push_back(tensor);
  12446. }
  12447. // allocate tensors / buffers and zero
  12448. for (auto it : ctx_map) {
  12449. ggml_backend_buffer_type_t buft = it.first;
  12450. ggml_context * ctx = it.second;
  12451. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  12452. if (!buf) {
  12453. LLAMA_LOG_ERROR("%s: failed to allocate buffer for control vector\n", __func__);
  12454. return false;
  12455. }
  12456. ggml_backend_buffer_clear(buf, 0);
  12457. cvec.ctxs.push_back(ctx);
  12458. cvec.bufs.push_back(buf);
  12459. }
  12460. return true;
  12461. }
  12462. 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) {
  12463. const llama_model & model = lctx->model;
  12464. llama_control_vector & cvec = lctx->cvec;
  12465. if (data == nullptr) {
  12466. // disable the current control vector (but leave allocated for later)
  12467. cvec.layer_start = -1;
  12468. cvec.layer_end = -1;
  12469. return 0;
  12470. }
  12471. if (n_embd != (int) model.hparams.n_embd) {
  12472. LLAMA_LOG_ERROR("%s: control vector n_embd does not match model\n", __func__);
  12473. return 1;
  12474. }
  12475. if (cvec.tensors.empty()) {
  12476. if (!llama_control_vector_init(cvec, model)) {
  12477. return 1;
  12478. }
  12479. }
  12480. cvec.layer_start = il_start;
  12481. cvec.layer_end = il_end;
  12482. for (size_t il = 1; il < model.hparams.n_layer; il++) {
  12483. assert(cvec.tensors[il] != nullptr);
  12484. const size_t off = n_embd * (il - 1); // buffer doesn't have data for layer 0, since it's never present
  12485. if (off + n_embd <= len) {
  12486. ggml_backend_tensor_set(cvec.tensors[il], data + off, 0, n_embd * ggml_element_size(cvec.tensors[il]));
  12487. }
  12488. }
  12489. return 0;
  12490. }
  12491. struct llama_kv_cache_view llama_kv_cache_view_init(const struct llama_context * ctx, int32_t n_seq_max) {
  12492. struct llama_kv_cache_view result = {
  12493. /*.n_cells = */ 0,
  12494. /*.n_seq_max = */ n_seq_max,
  12495. /*.token_count = */ 0,
  12496. /*.used_cells = */ llama_get_kv_cache_used_cells(ctx),
  12497. /*.max_contiguous = */ 0,
  12498. /*.max_contiguous_idx = */ -1,
  12499. /*.cells = */ nullptr,
  12500. /*.cells_sequences = */ nullptr,
  12501. };
  12502. return result;
  12503. }
  12504. void llama_kv_cache_view_free(struct llama_kv_cache_view * view) {
  12505. if (view->cells != nullptr) {
  12506. free(view->cells);
  12507. view->cells = nullptr;
  12508. }
  12509. if (view->cells_sequences != nullptr) {
  12510. free(view->cells_sequences);
  12511. view->cells_sequences = nullptr;
  12512. }
  12513. }
  12514. void llama_kv_cache_view_update(const struct llama_context * ctx, struct llama_kv_cache_view * view) {
  12515. if (uint32_t(view->n_cells) < ctx->kv_self.size || view->cells == nullptr) {
  12516. view->n_cells = int32_t(ctx->kv_self.size);
  12517. void * p = realloc(view->cells, sizeof(struct llama_kv_cache_view_cell) * view->n_cells);
  12518. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells");
  12519. view->cells = (struct llama_kv_cache_view_cell *)p;
  12520. p = realloc(view->cells_sequences, sizeof(llama_seq_id) * view->n_seq_max * view->n_cells);
  12521. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells sequences");
  12522. view->cells_sequences = (llama_seq_id *)p;
  12523. }
  12524. const std::vector<llama_kv_cell> & kv_cells = ctx->kv_self.cells;
  12525. llama_kv_cache_view_cell * c_curr = view->cells;
  12526. llama_seq_id * cs_curr = view->cells_sequences;
  12527. int32_t used_cells = 0;
  12528. int32_t token_count = 0;
  12529. int32_t curr_contig_idx = -1;
  12530. uint32_t max_contig = 0;
  12531. int32_t max_contig_idx = -1;
  12532. for (int32_t i = 0; i < int32_t(ctx->kv_self.size); i++, c_curr++, cs_curr += view->n_seq_max) {
  12533. const size_t curr_size = kv_cells[i].seq_id.size();
  12534. token_count += curr_size;
  12535. c_curr->pos = kv_cells[i].pos + kv_cells[i].delta;
  12536. if (curr_size > 0) {
  12537. if (curr_contig_idx >= 0 && uint32_t(i - curr_contig_idx) > max_contig) {
  12538. max_contig = i - curr_contig_idx;
  12539. max_contig_idx = curr_contig_idx;
  12540. }
  12541. curr_contig_idx = -1;
  12542. } else if (curr_contig_idx < 0) {
  12543. curr_contig_idx = i;
  12544. }
  12545. int seq_idx = 0;
  12546. for (const llama_seq_id it : kv_cells[i].seq_id) {
  12547. if (seq_idx >= view->n_seq_max) {
  12548. break;
  12549. }
  12550. cs_curr[seq_idx] = it;
  12551. seq_idx++;
  12552. }
  12553. if (seq_idx != 0) {
  12554. used_cells++;
  12555. }
  12556. for (; seq_idx < view->n_seq_max; seq_idx++) {
  12557. cs_curr[seq_idx] = -1;
  12558. }
  12559. }
  12560. if (curr_contig_idx >= 0 && kv_cells.size() - curr_contig_idx > max_contig) {
  12561. max_contig_idx = curr_contig_idx;
  12562. max_contig = kv_cells.size() - curr_contig_idx;
  12563. }
  12564. view->max_contiguous = max_contig;
  12565. view->max_contiguous_idx = max_contig_idx;
  12566. view->token_count = token_count;
  12567. view->used_cells = used_cells;
  12568. if (uint32_t(used_cells) != ctx->kv_self.used) {
  12569. LLAMA_LOG_ERROR("%s: used cells mismatch. kv_cache says %d but we calculated %d\n",
  12570. __func__, ctx->kv_self.used, used_cells);
  12571. }
  12572. }
  12573. int32_t llama_get_kv_cache_token_count(const struct llama_context * ctx) {
  12574. int result = 0;
  12575. for (uint32_t i = 0; i < ctx->kv_self.size; i++) {
  12576. result += ctx->kv_self.cells[i].seq_id.size();
  12577. }
  12578. return result;
  12579. }
  12580. int32_t llama_get_kv_cache_used_cells(const struct llama_context * ctx) {
  12581. return ctx->kv_self.used;
  12582. }
  12583. void llama_kv_cache_clear(struct llama_context * ctx) {
  12584. llama_kv_cache_clear(ctx->kv_self);
  12585. }
  12586. bool llama_kv_cache_seq_rm(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
  12587. return llama_kv_cache_seq_rm(ctx->kv_self, seq_id, p0, p1);
  12588. }
  12589. 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) {
  12590. if (seq_id_src == seq_id_dst) {
  12591. return;
  12592. }
  12593. llama_kv_cache_seq_cp(ctx->kv_self, seq_id_src, seq_id_dst, p0, p1);
  12594. }
  12595. void llama_kv_cache_seq_keep(struct llama_context * ctx, llama_seq_id seq_id) {
  12596. llama_kv_cache_seq_keep(ctx->kv_self, seq_id);
  12597. }
  12598. void llama_kv_cache_seq_add(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos delta) {
  12599. if (delta == 0) {
  12600. return;
  12601. }
  12602. llama_kv_cache_seq_add(ctx->kv_self, seq_id, p0, p1, delta);
  12603. }
  12604. void llama_kv_cache_seq_div(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) {
  12605. if (d == 1) {
  12606. return;
  12607. }
  12608. llama_kv_cache_seq_div(ctx->kv_self, seq_id, p0, p1, d);
  12609. }
  12610. llama_pos llama_kv_cache_seq_pos_max(struct llama_context * ctx, llama_seq_id seq_id) {
  12611. return llama_kv_cache_seq_pos_max(ctx->kv_self, seq_id);
  12612. }
  12613. void llama_kv_cache_defrag(struct llama_context * ctx) {
  12614. llama_kv_cache_defrag(ctx->kv_self);
  12615. }
  12616. void llama_kv_cache_update(struct llama_context * ctx) {
  12617. llama_kv_cache_update_internal(*ctx);
  12618. }
  12619. // deprecated
  12620. size_t llama_get_state_size(const struct llama_context * ctx) {
  12621. return llama_state_get_size(ctx);
  12622. }
  12623. // deprecated
  12624. size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dst) {
  12625. return llama_state_get_data(ctx, dst);
  12626. }
  12627. // deprecated
  12628. size_t llama_set_state_data(struct llama_context * ctx, const uint8_t * src) {
  12629. return llama_state_set_data(ctx, src);
  12630. }
  12631. // deprecated
  12632. 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) {
  12633. return llama_state_load_file(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  12634. }
  12635. // deprecated
  12636. bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  12637. return llama_state_save_file(ctx, path_session, tokens, n_token_count);
  12638. }
  12639. // Returns the *maximum* size of the state
  12640. size_t llama_state_get_size(const struct llama_context * ctx) {
  12641. const auto & cparams = ctx->cparams;
  12642. const auto & hparams = ctx->model.hparams;
  12643. // we don't know size of rng until we actually serialize it. so reserve more than enough memory for its serialized state.
  12644. // for reference, std::mt19937(1337) serializes to 6701 bytes.
  12645. const size_t s_rng_size = sizeof(size_t);
  12646. const size_t s_rng = LLAMA_MAX_RNG_STATE;
  12647. const size_t s_n_outputs = sizeof(size_t);
  12648. // assume worst case for outputs although only currently set ones are serialized
  12649. const size_t s_output_pos = ctx->cparams.n_batch * sizeof(int32_t);
  12650. const size_t s_logits_size = sizeof(size_t);
  12651. const size_t s_logits = ctx->logits_size ? cparams.n_batch * hparams.n_vocab * sizeof(float) : 0;
  12652. const size_t s_embedding_size = sizeof(size_t);
  12653. const size_t s_embedding = ctx->embd_size ? cparams.n_batch * hparams.n_embd * sizeof(float) : 0;
  12654. const size_t s_kv_buf_size = sizeof(size_t);
  12655. const size_t s_kv_head = sizeof(uint32_t);
  12656. const size_t s_kv_size = sizeof(uint32_t);
  12657. const size_t s_kv_used = sizeof(uint32_t);
  12658. const size_t s_kv = ctx->kv_self.total_size();
  12659. const size_t s_kv_cell = sizeof(llama_pos) + sizeof(size_t) + cparams.n_seq_max*sizeof(llama_seq_id);
  12660. const size_t s_kv_cells = ctx->kv_self.size * s_kv_cell;
  12661. const size_t s_total = (
  12662. + s_rng_size
  12663. + s_rng
  12664. + s_n_outputs
  12665. + s_output_pos
  12666. + s_logits_size
  12667. + s_logits
  12668. + s_embedding_size
  12669. + s_embedding
  12670. + s_kv_buf_size
  12671. + s_kv_head
  12672. + s_kv_size
  12673. + s_kv_used
  12674. + s_kv
  12675. + s_kv_cells
  12676. );
  12677. return s_total;
  12678. }
  12679. // llama_context_data
  12680. struct llama_data_context {
  12681. virtual void write(const void * src, size_t size) = 0;
  12682. virtual size_t get_size_written() = 0;
  12683. virtual ~llama_data_context() = default;
  12684. };
  12685. struct llama_data_buffer_context : llama_data_context {
  12686. uint8_t * ptr;
  12687. size_t size_written = 0;
  12688. llama_data_buffer_context(uint8_t * p) : ptr(p) {}
  12689. void write(const void * src, size_t size) override {
  12690. memcpy(ptr, src, size);
  12691. ptr += size;
  12692. size_written += size;
  12693. }
  12694. size_t get_size_written() override {
  12695. return size_written;
  12696. }
  12697. };
  12698. struct llama_data_file_context : llama_data_context {
  12699. llama_file * file;
  12700. size_t size_written = 0;
  12701. llama_data_file_context(llama_file * f) : file(f) {}
  12702. void write(const void * src, size_t size) override {
  12703. file->write_raw(src, size);
  12704. size_written += size;
  12705. }
  12706. size_t get_size_written() override {
  12707. return size_written;
  12708. }
  12709. };
  12710. /** copy state data into either a buffer or file depending on the passed in context
  12711. *
  12712. * file context:
  12713. * llama_file file("/path", "wb");
  12714. * llama_data_file_context data_ctx(&file);
  12715. * llama_state_get_data(ctx, &data_ctx);
  12716. *
  12717. * buffer context:
  12718. * std::vector<uint8_t> buf(max_size, 0);
  12719. * llama_data_buffer_context data_ctx(&buf.data());
  12720. * llama_state_get_data(ctx, &data_ctx);
  12721. *
  12722. */
  12723. static void llama_state_get_data_internal(struct llama_context * ctx, llama_data_context * data_ctx) {
  12724. // copy rng
  12725. {
  12726. std::ostringstream rng_ss;
  12727. rng_ss << ctx->rng;
  12728. const std::string & rng_str = rng_ss.str();
  12729. const size_t rng_size = rng_str.size();
  12730. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  12731. data_ctx->write(&rng_size, sizeof(rng_size));
  12732. data_ctx->write(rng_str.data(), rng_size);
  12733. }
  12734. // copy outputs
  12735. {
  12736. // Can't use ctx->n_outputs because it's not for the
  12737. // entire last batch when n_ubatch is smaller than n_batch
  12738. size_t n_outputs = 0;
  12739. // copy output ids
  12740. {
  12741. std::vector<int32_t> output_pos;
  12742. const size_t n_batch = ctx->cparams.n_batch;
  12743. const auto & output_ids = ctx->output_ids;
  12744. output_pos.resize(ctx->output_size);
  12745. // build a more compact representation of the output ids
  12746. for (size_t i = 0; i < n_batch; ++i) {
  12747. // map an output id to a position in the batch
  12748. int32_t pos = output_ids[i];
  12749. if (pos >= 0) {
  12750. if ((size_t) pos >= n_outputs) {
  12751. n_outputs = pos + 1;
  12752. }
  12753. GGML_ASSERT((size_t) pos < ctx->output_size);
  12754. output_pos[pos] = i;
  12755. }
  12756. }
  12757. data_ctx->write(&n_outputs, sizeof(n_outputs));
  12758. if (n_outputs) {
  12759. data_ctx->write(output_pos.data(), n_outputs * sizeof(int32_t));
  12760. }
  12761. }
  12762. // copy logits
  12763. {
  12764. const size_t logits_size = std::min(ctx->logits_size, n_outputs * ctx->model.hparams.n_vocab);
  12765. data_ctx->write(&logits_size, sizeof(logits_size));
  12766. if (logits_size) {
  12767. data_ctx->write(ctx->logits, logits_size * sizeof(float));
  12768. }
  12769. }
  12770. // copy embeddings
  12771. {
  12772. const size_t embeddings_size = std::min(ctx->embd_size, n_outputs * ctx->model.hparams.n_embd);
  12773. data_ctx->write(&embeddings_size, sizeof(embeddings_size));
  12774. if (embeddings_size) {
  12775. data_ctx->write(ctx->embd, embeddings_size * sizeof(float));
  12776. }
  12777. }
  12778. }
  12779. // copy kv cache
  12780. {
  12781. const auto & kv_self = ctx->kv_self;
  12782. const auto & hparams = ctx->model.hparams;
  12783. const uint32_t n_layer = hparams.n_layer;
  12784. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  12785. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  12786. // NOTE: kv_size and kv_buf_size are mostly used for sanity checks
  12787. const uint32_t kv_head = llama_kv_cache_cell_max(kv_self);
  12788. const uint32_t kv_size = kv_self.size;
  12789. const size_t kv_buf_size = kv_self.total_size() / (kv_size ? kv_size : 1) * kv_head;
  12790. const uint32_t kv_used = kv_self.used;
  12791. data_ctx->write(&kv_buf_size, sizeof(kv_buf_size));
  12792. data_ctx->write(&kv_head, sizeof(kv_head));
  12793. data_ctx->write(&kv_size, sizeof(kv_size));
  12794. data_ctx->write(&kv_used, sizeof(kv_used));
  12795. if (kv_buf_size) {
  12796. const size_t pre_kv_buf_size = data_ctx->get_size_written();
  12797. std::vector<uint8_t> tmp_buf;
  12798. for (int il = 0; il < (int) n_layer; ++il) {
  12799. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_head);
  12800. tmp_buf.resize(k_size);
  12801. ggml_backend_tensor_get(kv_self.k_l[il], tmp_buf.data(), 0, tmp_buf.size());
  12802. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  12803. if (kv_self.recurrent) {
  12804. // v is contiguous for recurrent models
  12805. // TODO: use other tensors for state models than k and v
  12806. const size_t v_size = ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa*kv_head);
  12807. tmp_buf.resize(v_size);
  12808. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), 0, tmp_buf.size());
  12809. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  12810. continue;
  12811. }
  12812. // v is not contiguous, copy row by row
  12813. const size_t v_row_size = ggml_row_size(kv_self.v_l[il]->type, kv_head);
  12814. const size_t v_row_stride = ggml_row_size(kv_self.v_l[il]->type, kv_size);
  12815. tmp_buf.resize(v_row_size);
  12816. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  12817. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), ir*v_row_stride, tmp_buf.size());
  12818. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  12819. }
  12820. }
  12821. GGML_ASSERT(kv_buf_size == data_ctx->get_size_written() - pre_kv_buf_size);
  12822. }
  12823. for (uint32_t i = 0; i < kv_head; ++i) {
  12824. const auto & cell = kv_self.cells[i];
  12825. const llama_pos pos = cell.pos;
  12826. const size_t seq_id_size = cell.seq_id.size();
  12827. data_ctx->write(&pos, sizeof(pos));
  12828. data_ctx->write(&seq_id_size, sizeof(seq_id_size));
  12829. for (auto seq_id : cell.seq_id) {
  12830. data_ctx->write(&seq_id, sizeof(seq_id));
  12831. }
  12832. }
  12833. }
  12834. }
  12835. size_t llama_state_get_data(struct llama_context * ctx, uint8_t * dst) {
  12836. llama_data_buffer_context data_ctx(dst);
  12837. llama_state_get_data_internal(ctx, &data_ctx);
  12838. return data_ctx.get_size_written();
  12839. }
  12840. // Sets the state reading from the specified source address
  12841. size_t llama_state_set_data(struct llama_context * ctx, const uint8_t * src) {
  12842. const uint8_t * inp = src;
  12843. // set rng
  12844. {
  12845. size_t rng_size;
  12846. memcpy(&rng_size, inp, sizeof(rng_size)); inp += sizeof(rng_size);
  12847. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  12848. std::string rng_str((const char *)inp, rng_size); inp += rng_size;
  12849. std::istringstream rng_ss(rng_str);
  12850. rng_ss >> ctx->rng;
  12851. GGML_ASSERT(!rng_ss.fail());
  12852. }
  12853. // set output ids
  12854. {
  12855. size_t n_outputs;
  12856. std::vector<int32_t> output_pos;
  12857. memcpy(&n_outputs, inp, sizeof(n_outputs)); inp += sizeof(n_outputs);
  12858. GGML_ASSERT(n_outputs <= llama_output_reserve(*ctx, n_outputs));
  12859. if (n_outputs) {
  12860. output_pos.resize(n_outputs);
  12861. memcpy(output_pos.data(), inp, n_outputs * sizeof(int32_t));
  12862. inp += n_outputs * sizeof(int32_t);
  12863. for (int32_t i = 0; i < (int32_t) output_pos.size(); ++i) {
  12864. int32_t id = output_pos[i];
  12865. GGML_ASSERT((uint32_t) id < ctx->cparams.n_batch);
  12866. ctx->output_ids[id] = i;
  12867. }
  12868. }
  12869. }
  12870. // set logits
  12871. {
  12872. size_t logits_size;
  12873. memcpy(&logits_size, inp, sizeof(logits_size)); inp += sizeof(logits_size);
  12874. GGML_ASSERT(ctx->logits_size >= logits_size);
  12875. if (logits_size) {
  12876. memcpy(ctx->logits, inp, logits_size * sizeof(float));
  12877. inp += logits_size * sizeof(float);
  12878. }
  12879. }
  12880. // set embeddings
  12881. {
  12882. size_t embeddings_size;
  12883. memcpy(&embeddings_size, inp, sizeof(embeddings_size)); inp += sizeof(embeddings_size);
  12884. GGML_ASSERT(ctx->embd_size >= embeddings_size);
  12885. if (embeddings_size) {
  12886. memcpy(ctx->embd, inp, embeddings_size * sizeof(float));
  12887. inp += embeddings_size * sizeof(float);
  12888. }
  12889. }
  12890. // set kv cache
  12891. {
  12892. const auto & kv_self = ctx->kv_self;
  12893. const auto & hparams = ctx->model.hparams;
  12894. const uint32_t n_layer = hparams.n_layer;
  12895. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  12896. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  12897. size_t kv_buf_size;
  12898. uint32_t kv_head;
  12899. uint32_t kv_size;
  12900. uint32_t kv_used;
  12901. memcpy(&kv_buf_size, inp, sizeof(kv_buf_size)); inp += sizeof(kv_buf_size);
  12902. memcpy(&kv_head, inp, sizeof(kv_head)); inp += sizeof(kv_head);
  12903. memcpy(&kv_size, inp, sizeof(kv_size)); inp += sizeof(kv_size);
  12904. memcpy(&kv_used, inp, sizeof(kv_used)); inp += sizeof(kv_used);
  12905. if (kv_self.size != kv_size) {
  12906. // the KV cache needs to be big enough to load all the KV cells from the saved state
  12907. GGML_ASSERT(kv_self.size >= kv_head);
  12908. 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",
  12909. __func__, kv_head, kv_size, kv_self.size);
  12910. }
  12911. if (kv_buf_size) {
  12912. const size_t pre_kv_buf_size = inp - src;
  12913. GGML_ASSERT(kv_self.total_size() >= kv_buf_size);
  12914. for (int il = 0; il < (int) n_layer; ++il) {
  12915. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_head);
  12916. ggml_backend_tensor_set(kv_self.k_l[il], inp, 0, k_size);
  12917. inp += k_size;
  12918. if (kv_self.recurrent) {
  12919. // v is contiguous for recurrent models
  12920. // TODO: use other tensors for state models than k and v
  12921. const size_t v_size = ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa*kv_head);
  12922. ggml_backend_tensor_set(kv_self.v_l[il], inp, 0, v_size);
  12923. inp += v_size;
  12924. continue;
  12925. }
  12926. // v is not contiguous, copy row by row
  12927. const size_t v_row_size = ggml_row_size(kv_self.v_l[il]->type, kv_head);
  12928. const size_t v_row_stride = ggml_row_size(kv_self.v_l[il]->type, kv_self.size);
  12929. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  12930. ggml_backend_tensor_set(kv_self.v_l[il], inp, ir*v_row_stride, v_row_size);
  12931. inp += v_row_size;
  12932. }
  12933. }
  12934. GGML_ASSERT(kv_buf_size == inp - src - pre_kv_buf_size);
  12935. }
  12936. llama_kv_cache_clear(ctx);
  12937. ctx->kv_self.head = kv_head;
  12938. ctx->kv_self.used = kv_used;
  12939. for (uint32_t i = 0; i < kv_head; ++i) {
  12940. llama_pos pos;
  12941. size_t seq_id_size;
  12942. memcpy(&pos, inp, sizeof(pos)); inp += sizeof(pos);
  12943. memcpy(&seq_id_size, inp, sizeof(seq_id_size)); inp += sizeof(seq_id_size);
  12944. ctx->kv_self.cells[i].pos = pos;
  12945. llama_seq_id seq_id;
  12946. for (size_t j = 0; j < seq_id_size; ++j) {
  12947. memcpy(&seq_id, inp, sizeof(seq_id)); inp += sizeof(seq_id);
  12948. ctx->kv_self.cells[i].seq_id.insert(seq_id);
  12949. }
  12950. }
  12951. }
  12952. const size_t nread = inp - src;
  12953. const size_t max_size = llama_state_get_size(ctx);
  12954. GGML_ASSERT(nread <= max_size);
  12955. return nread;
  12956. }
  12957. 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) {
  12958. llama_file file(path_session, "rb");
  12959. // sanity checks
  12960. {
  12961. const uint32_t magic = file.read_u32();
  12962. const uint32_t version = file.read_u32();
  12963. if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
  12964. LLAMA_LOG_ERROR("%s : unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
  12965. return false;
  12966. }
  12967. llama_hparams session_hparams;
  12968. file.read_raw(&session_hparams, sizeof(llama_hparams));
  12969. if (session_hparams != ctx->model.hparams) {
  12970. LLAMA_LOG_INFO("%s : model hparams didn't match from session file!\n", __func__);
  12971. return false;
  12972. }
  12973. }
  12974. // load the prompt
  12975. {
  12976. const uint32_t n_token_count = file.read_u32();
  12977. if (n_token_count > n_token_capacity) {
  12978. LLAMA_LOG_ERROR("%s : token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  12979. return false;
  12980. }
  12981. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  12982. *n_token_count_out = n_token_count;
  12983. }
  12984. // restore the context state
  12985. {
  12986. const size_t n_state_size_cur = file.size - file.tell();
  12987. const size_t n_state_size_max = llama_state_get_size(ctx);
  12988. if (n_state_size_cur > n_state_size_max) {
  12989. 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);
  12990. return false;
  12991. }
  12992. std::vector<uint8_t> state_data(n_state_size_max);
  12993. file.read_raw(state_data.data(), n_state_size_cur);
  12994. llama_state_set_data(ctx, state_data.data());
  12995. }
  12996. return true;
  12997. }
  12998. 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) {
  12999. try {
  13000. return llama_state_load_file_internal(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  13001. } catch (const std::exception & err) {
  13002. LLAMA_LOG_ERROR("error loading session file: %s\n", err.what());
  13003. return false;
  13004. }
  13005. }
  13006. static bool llama_state_save_file_internal(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  13007. llama_file file(path_session, "wb");
  13008. file.write_u32(LLAMA_SESSION_MAGIC);
  13009. file.write_u32(LLAMA_SESSION_VERSION);
  13010. file.write_raw(&ctx->model.hparams, sizeof(llama_hparams));
  13011. // save the prompt
  13012. file.write_u32((uint32_t) n_token_count);
  13013. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  13014. // save the context state using stream saving
  13015. llama_data_file_context data_ctx(&file);
  13016. llama_state_get_data_internal(ctx, &data_ctx);
  13017. return true;
  13018. }
  13019. bool llama_state_save_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  13020. try {
  13021. return llama_state_save_file_internal(ctx, path_session, tokens, n_token_count);
  13022. } catch (const std::exception & err) {
  13023. LLAMA_LOG_ERROR("error saving session file: %s\n", err.what());
  13024. return false;
  13025. }
  13026. }
  13027. size_t llama_state_seq_get_size(struct llama_context* ctx, llama_seq_id seq_id) {
  13028. // save the size of size_t as a uint32_t for safety check
  13029. const size_t size_t_size_size = sizeof(uint32_t);
  13030. // other values
  13031. const size_t s_cell_count_size = sizeof(uint32_t);
  13032. const size_t s_layer_count_size = sizeof(uint32_t);
  13033. const size_t n_embd_v_gqa_size = sizeof(uint32_t);
  13034. size_t s_cell_count = 0;
  13035. size_t s_cell_data_size = 0;
  13036. const auto & kv_self = ctx->kv_self;
  13037. const auto & hparams = ctx->model.hparams;
  13038. const uint32_t n_layer = hparams.n_layer;
  13039. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  13040. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  13041. for (uint32_t i = 0; i < kv_self.size; ++i) {
  13042. const auto & cell = kv_self.cells[i];
  13043. if (cell.seq_id.count(seq_id) > 0) {
  13044. ++s_cell_count;
  13045. s_cell_data_size += sizeof(llama_pos);
  13046. }
  13047. }
  13048. for (int il = 0; il < (int)n_layer; ++il) {
  13049. // types of keys and values
  13050. s_cell_data_size += sizeof(int32_t) * 2;
  13051. // k_size_row and v_size_el values of layer
  13052. s_cell_data_size += sizeof(size_t) * 2;
  13053. // keys
  13054. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  13055. s_cell_data_size += k_size_row * s_cell_count;
  13056. // values (transposed)
  13057. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  13058. s_cell_data_size += v_size_el * s_cell_count * n_embd_v_gqa;
  13059. }
  13060. const size_t s_total = (
  13061. size_t_size_size +
  13062. s_cell_count_size +
  13063. s_layer_count_size +
  13064. n_embd_v_gqa_size +
  13065. s_cell_data_size
  13066. );
  13067. return s_total;
  13068. }
  13069. static size_t llama_state_seq_get_data_internal(struct llama_context * ctx, llama_data_context & data_ctx, llama_seq_id seq_id) {
  13070. const auto & kv_self = ctx->kv_self;
  13071. GGML_ASSERT(!kv_self.recurrent); // not implemented
  13072. // Save the size of size_t as a uint32_t for safety check
  13073. const uint32_t size_t_size = sizeof(size_t);
  13074. data_ctx.write(&size_t_size, sizeof(size_t_size));
  13075. std::vector<std::pair<uint32_t, uint32_t>> cell_ranges; // ranges, from inclusive, to exclusive
  13076. uint32_t cell_count = 0;
  13077. // Count the number of cells with the specified seq_id
  13078. // Find all the ranges of cells with this seq id
  13079. {
  13080. uint32_t cell_range_begin = kv_self.size;
  13081. for (uint32_t i = 0; i < kv_self.size; ++i) {
  13082. const auto & cell = kv_self.cells[i];
  13083. if (cell.has_seq_id(seq_id)) {
  13084. ++cell_count;
  13085. if (cell_range_begin == kv_self.size) {
  13086. cell_range_begin = i;
  13087. }
  13088. }
  13089. else {
  13090. if (cell_range_begin != kv_self.size) {
  13091. cell_ranges.push_back({ cell_range_begin, i });
  13092. cell_range_begin = kv_self.size;
  13093. }
  13094. }
  13095. }
  13096. if (cell_range_begin != kv_self.size) {
  13097. cell_ranges.push_back({ cell_range_begin, kv_self.size });
  13098. }
  13099. // DEBUG CHECK: Sum of cell counts in ranges should equal the total cell count
  13100. uint32_t cell_count_check = 0;
  13101. for (const auto & range : cell_ranges) {
  13102. cell_count_check += range.second - range.first;
  13103. }
  13104. GGML_ASSERT(cell_count == cell_count_check);
  13105. }
  13106. // Write the cell count
  13107. data_ctx.write(&cell_count, sizeof(cell_count));
  13108. const auto & hparams = ctx->model.hparams;
  13109. const uint32_t n_layer = hparams.n_layer;
  13110. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  13111. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  13112. // Write the layer count
  13113. data_ctx.write(&n_layer, sizeof(n_layer));
  13114. // Write n_embd_v_gqa
  13115. data_ctx.write(&n_embd_v_gqa, sizeof(n_embd_v_gqa));
  13116. // Iterate the ranges and write all the pos (this is the token position in the prompt)
  13117. for (const auto & range : cell_ranges) {
  13118. for (uint32_t i = range.first; i < range.second; ++i) {
  13119. const auto & cell = kv_self.cells[i];
  13120. data_ctx.write(&cell.pos, sizeof(cell.pos));
  13121. }
  13122. }
  13123. // Iterate and write all the keys first, each row is a cell
  13124. // Get whole range at a time
  13125. std::vector<uint8_t> tmp_buf;
  13126. for (int il = 0; il < (int)n_layer; ++il) {
  13127. // Write key type
  13128. const int32_t k_type_i = (int32_t)kv_self.k_l[il]->type;
  13129. data_ctx.write(&k_type_i, sizeof(k_type_i));
  13130. // Write row size of key
  13131. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  13132. data_ctx.write(&k_size_row, sizeof(k_size_row));
  13133. // Read each range of cells of k_size length each into tmp_buf and write out
  13134. for (const auto & range : cell_ranges) {
  13135. const size_t range_size = range.second - range.first;
  13136. tmp_buf.resize(range_size * k_size_row);
  13137. ggml_backend_tensor_get(kv_self.k_l[il], tmp_buf.data(), range.first * k_size_row, range_size * k_size_row);
  13138. data_ctx.write(tmp_buf.data(), tmp_buf.size());
  13139. }
  13140. }
  13141. // For the values, they are transposed, so we also need the element size and get the element ranges from each row
  13142. const uint32_t kv_size = kv_self.size;
  13143. for (int il = 0; il < (int)n_layer; ++il) {
  13144. // Write value type
  13145. const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
  13146. data_ctx.write(&v_type_i, sizeof(v_type_i));
  13147. // Write element size
  13148. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  13149. data_ctx.write(&v_size_el, sizeof(v_size_el));
  13150. // For each row, we get the element values of each cell
  13151. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  13152. // Read each range of cells of v_size_el length each into tmp_buf and write out
  13153. for (const auto & range : cell_ranges) {
  13154. const size_t range_size = range.second - range.first;
  13155. const size_t src_offset = (range.first + j * kv_size) * v_size_el;
  13156. tmp_buf.resize(range_size * v_size_el);
  13157. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), src_offset, tmp_buf.size());
  13158. data_ctx.write(tmp_buf.data(), tmp_buf.size());
  13159. }
  13160. }
  13161. }
  13162. return data_ctx.get_size_written();
  13163. }
  13164. size_t llama_state_seq_get_data(struct llama_context* ctx, uint8_t* dst, llama_seq_id seq_id) {
  13165. llama_data_buffer_context data_ctx(dst);
  13166. return llama_state_seq_get_data_internal(ctx, data_ctx, seq_id);
  13167. }
  13168. size_t llama_state_seq_set_data(struct llama_context * ctx, const uint8_t * src, llama_seq_id dest_seq_id) {
  13169. auto & kv_self = ctx->kv_self;
  13170. GGML_ASSERT(!kv_self.recurrent); // not implemented
  13171. // Wipe the slot
  13172. llama_kv_cache_seq_rm(kv_self, dest_seq_id, -1, -1);
  13173. const uint8_t * inp = src;
  13174. // Read size of size_t
  13175. uint32_t size_t_size;
  13176. memcpy(&size_t_size, inp, sizeof(size_t_size));
  13177. inp += sizeof(size_t_size);
  13178. if (size_t_size != sizeof(size_t)) {
  13179. LLAMA_LOG_ERROR("%s: size_t size mismatch\n", __func__);
  13180. return 0;
  13181. }
  13182. // Read the cell count
  13183. uint32_t cell_count;
  13184. memcpy(&cell_count, inp, sizeof(cell_count));
  13185. inp += sizeof(cell_count);
  13186. // Read the layer count
  13187. uint32_t n_layer_ref;
  13188. memcpy(&n_layer_ref, inp, sizeof(n_layer_ref));
  13189. inp += sizeof(n_layer_ref);
  13190. // Read n_embd_v_gqa
  13191. uint32_t n_embd_v_gqa_ref;
  13192. memcpy(&n_embd_v_gqa_ref, inp, sizeof(n_embd_v_gqa_ref));
  13193. inp += sizeof(n_embd_v_gqa_ref);
  13194. // Sanity check model compatibility
  13195. const auto & hparams = ctx->model.hparams;
  13196. const uint32_t n_layer = hparams.n_layer;
  13197. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  13198. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  13199. if (n_layer != n_layer_ref) {
  13200. LLAMA_LOG_ERROR("%s: mismatched n_layer (%d != %d)\n", __func__, n_layer, n_layer_ref);
  13201. return 0;
  13202. }
  13203. if (n_embd_v_gqa != n_embd_v_gqa_ref) {
  13204. LLAMA_LOG_ERROR("%s: mismatched n_embd_v_gqa (%d != %d)\n", __func__, n_embd_v_gqa, n_embd_v_gqa_ref);
  13205. return 0;
  13206. }
  13207. // Allocate the new cells for the slot
  13208. if (cell_count) {
  13209. llama_batch batch = llama_batch_init(cell_count, 0, 1);
  13210. batch.n_tokens = cell_count;
  13211. for (uint32_t i = 0; i < cell_count; ++i) {
  13212. llama_pos pos;
  13213. memcpy(&pos, inp, sizeof(pos));
  13214. inp += sizeof(pos);
  13215. batch.pos[i] = pos;
  13216. batch.n_seq_id[i] = 1;
  13217. batch.seq_id[i][0] = dest_seq_id;
  13218. }
  13219. if (!llama_kv_cache_find_slot(kv_self, batch)) {
  13220. llama_batch_free(batch);
  13221. LLAMA_LOG_ERROR("%s: failed to find available cells in kv cache\n", __func__);
  13222. return 0;
  13223. }
  13224. // 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)
  13225. // Assume that this is one contiguous block of cells
  13226. GGML_ASSERT(kv_self.head + cell_count <= kv_self.size);
  13227. GGML_ASSERT(kv_self.cells[kv_self.head].pos == batch.pos[0]);
  13228. GGML_ASSERT(kv_self.cells[kv_self.head + cell_count - 1].pos == batch.pos[cell_count - 1]);
  13229. GGML_ASSERT(kv_self.cells[kv_self.head].has_seq_id(dest_seq_id));
  13230. GGML_ASSERT(kv_self.cells[kv_self.head + cell_count - 1].has_seq_id(dest_seq_id));
  13231. // Cleanup
  13232. llama_batch_free(batch);
  13233. }
  13234. const uint32_t kv_size = kv_self.size;
  13235. const uint32_t kv_head = kv_self.head;
  13236. // For each layer, read the keys for each cell, one row is one cell, read as one contiguous blo
  13237. for (int il = 0; il < (int)n_layer; ++il) {
  13238. // Read type of key
  13239. int32_t k_type_i_ref;
  13240. memcpy(&k_type_i_ref, inp, sizeof(k_type_i_ref));
  13241. inp += sizeof(k_type_i_ref);
  13242. const int32_t k_type_i = (int32_t)kv_self.k_l[il]->type;
  13243. if (k_type_i != k_type_i_ref) {
  13244. llama_kv_cache_seq_rm(kv_self, dest_seq_id, -1, -1);
  13245. LLAMA_LOG_ERROR("%s: mismatched key type (%d != %d, layer %d)\n", __func__, k_type_i, k_type_i_ref, il);
  13246. return 0;
  13247. }
  13248. // Read row size of key
  13249. size_t k_size_row_ref;
  13250. memcpy(&k_size_row_ref, inp, sizeof(k_size_row_ref));
  13251. inp += sizeof(k_size_row_ref);
  13252. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  13253. if (k_size_row != k_size_row_ref) {
  13254. llama_kv_cache_seq_rm(kv_self, dest_seq_id, -1, -1);
  13255. LLAMA_LOG_ERROR("%s: mismatched key row size (%zu != %zu, layer %d)\n", __func__, k_size_row, k_size_row_ref, il);
  13256. return 0;
  13257. }
  13258. if (cell_count) {
  13259. // Read and set the keys for the whole cell range
  13260. ggml_backend_tensor_set(kv_self.k_l[il], inp, kv_head * k_size_row, cell_count * k_size_row);
  13261. inp += cell_count * k_size_row;
  13262. }
  13263. }
  13264. // For each layer, read the values for each cell (transposed)
  13265. for (int il = 0; il < (int)n_layer; ++il) {
  13266. // Read type of value
  13267. int32_t v_type_i_ref;
  13268. memcpy(&v_type_i_ref, inp, sizeof(v_type_i_ref));
  13269. inp += sizeof(v_type_i_ref);
  13270. const int32_t v_type_i = (int32_t)kv_self.v_l[il]->type;
  13271. if (v_type_i != v_type_i_ref) {
  13272. llama_kv_cache_seq_rm(kv_self, dest_seq_id, -1, -1);
  13273. LLAMA_LOG_ERROR("%s: mismatched value type (%d != %d, layer %d)\n", __func__, v_type_i, v_type_i_ref, il);
  13274. return 0;
  13275. }
  13276. // Read element size of value
  13277. size_t v_size_el_ref;
  13278. memcpy(&v_size_el_ref, inp, sizeof(v_size_el_ref));
  13279. inp += sizeof(v_size_el_ref);
  13280. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  13281. if (v_size_el != v_size_el_ref) {
  13282. llama_kv_cache_seq_rm(kv_self, dest_seq_id, -1, -1);
  13283. LLAMA_LOG_ERROR("%s: mismatched value element size (%zu != %zu, layer %d)\n", __func__, v_size_el, v_size_el_ref, il);
  13284. return 0;
  13285. }
  13286. if (cell_count) {
  13287. // For each row in the transposed matrix, read the values for the whole cell range
  13288. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  13289. const size_t dst_offset = (kv_head + j * kv_size) * v_size_el;
  13290. ggml_backend_tensor_set(kv_self.v_l[il], inp, dst_offset, cell_count * v_size_el);
  13291. inp += cell_count * v_size_el;
  13292. }
  13293. }
  13294. }
  13295. const size_t nread = inp - src;
  13296. return nread;
  13297. }
  13298. 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) {
  13299. llama_file file(filepath, "wb");
  13300. file.write_u32(LLAMA_STATE_SEQ_MAGIC);
  13301. file.write_u32(LLAMA_STATE_SEQ_VERSION);
  13302. // save the prompt
  13303. file.write_u32((uint32_t)n_token_count);
  13304. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  13305. // save the context state using stream saving
  13306. llama_data_file_context data_ctx(&file);
  13307. llama_state_seq_get_data_internal(ctx, data_ctx, seq_id);
  13308. const size_t res = file.tell();
  13309. GGML_ASSERT(res == sizeof(uint32_t) * 3 + sizeof(llama_token) * n_token_count + data_ctx.get_size_written());
  13310. return res;
  13311. }
  13312. 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) {
  13313. llama_file file(filepath, "rb");
  13314. // version checks
  13315. {
  13316. const uint32_t magic = file.read_u32();
  13317. const uint32_t version = file.read_u32();
  13318. if (magic != LLAMA_STATE_SEQ_MAGIC || version != LLAMA_STATE_SEQ_VERSION) {
  13319. LLAMA_LOG_ERROR("%s: unknown (magic, version) for sequence state file: %08x, %08x\n", __func__, magic, version);
  13320. return 0;
  13321. }
  13322. }
  13323. // load the prompt
  13324. {
  13325. const uint32_t n_token_count = file.read_u32();
  13326. if (n_token_count > n_token_capacity) {
  13327. LLAMA_LOG_ERROR("%s: token count in sequence state file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  13328. return 0;
  13329. }
  13330. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  13331. *n_token_count_out = n_token_count;
  13332. }
  13333. // restore the context state
  13334. {
  13335. const size_t state_size = file.size - file.tell();
  13336. std::vector<uint8_t> state_data(state_size);
  13337. file.read_raw(state_data.data(), state_size);
  13338. const size_t nread = llama_state_seq_set_data(ctx, state_data.data(), dest_seq_id);
  13339. if (!nread) {
  13340. LLAMA_LOG_ERROR("%s: failed to restore sequence state\n", __func__);
  13341. return 0;
  13342. }
  13343. GGML_ASSERT(nread <= state_size);
  13344. GGML_ASSERT(nread + sizeof(uint32_t) * 3 + sizeof(llama_token) * *n_token_count_out == file.tell());
  13345. }
  13346. return file.tell();
  13347. }
  13348. 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) {
  13349. try {
  13350. return llama_state_seq_save_file_internal(ctx, filepath, seq_id, tokens, n_token_count);
  13351. } catch (const std::exception & err) {
  13352. LLAMA_LOG_ERROR("error saving sequence state file: %s\n", err.what());
  13353. return 0;
  13354. }
  13355. }
  13356. 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) {
  13357. try {
  13358. return llama_state_seq_load_file_internal(ctx, filepath, dest_seq_id, tokens_out, n_token_capacity, n_token_count_out);
  13359. } catch (const std::exception & err) {
  13360. LLAMA_LOG_ERROR("error loading sequence state file: %s\n", err.what());
  13361. return 0;
  13362. }
  13363. }
  13364. void llama_set_n_threads(struct llama_context * ctx, uint32_t n_threads, uint32_t n_threads_batch) {
  13365. ctx->cparams.n_threads = n_threads;
  13366. ctx->cparams.n_threads_batch = n_threads_batch;
  13367. }
  13368. void llama_set_abort_callback(struct llama_context * ctx, bool (*abort_callback)(void * data), void * abort_callback_data) {
  13369. ctx->abort_callback = abort_callback;
  13370. ctx->abort_callback_data = abort_callback_data;
  13371. }
  13372. void llama_set_causal_attn(struct llama_context * ctx, bool causal_attn) {
  13373. ctx->cparams.causal_attn = causal_attn;
  13374. }
  13375. struct llama_batch llama_batch_get_one(
  13376. llama_token * tokens,
  13377. int32_t n_tokens,
  13378. llama_pos pos_0,
  13379. llama_seq_id seq_id) {
  13380. return {
  13381. /*n_tokens =*/ n_tokens,
  13382. /*tokens =*/ tokens,
  13383. /*embd =*/ nullptr,
  13384. /*pos =*/ nullptr,
  13385. /*n_seq_id =*/ nullptr,
  13386. /*seq_id =*/ nullptr,
  13387. /*logits =*/ nullptr,
  13388. /*all_pos_0 =*/ pos_0,
  13389. /*all_pos_1 =*/ 1,
  13390. /*all_seq_id =*/ seq_id,
  13391. };
  13392. }
  13393. struct llama_batch llama_batch_init(int32_t n_tokens_alloc, int32_t embd, int32_t n_seq_max) {
  13394. llama_batch batch = { 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, 0, 0, 0, };
  13395. if (embd) {
  13396. batch.embd = (float *) malloc(sizeof(float) * n_tokens_alloc * embd);
  13397. } else {
  13398. batch.token = (llama_token *) malloc(sizeof(llama_token) * n_tokens_alloc);
  13399. }
  13400. batch.pos = (llama_pos *) malloc(sizeof(llama_pos) * n_tokens_alloc);
  13401. batch.n_seq_id = (int32_t *) malloc(sizeof(int32_t) * n_tokens_alloc);
  13402. batch.seq_id = (llama_seq_id **) malloc(sizeof(llama_seq_id *) * (n_tokens_alloc + 1));
  13403. for (int i = 0; i < n_tokens_alloc; ++i) {
  13404. batch.seq_id[i] = (llama_seq_id *) malloc(sizeof(llama_seq_id) * n_seq_max);
  13405. }
  13406. batch.seq_id[n_tokens_alloc] = nullptr;
  13407. batch.logits = (int8_t *) malloc(sizeof(int8_t) * n_tokens_alloc);
  13408. return batch;
  13409. }
  13410. void llama_batch_free(struct llama_batch batch) {
  13411. if (batch.token) free(batch.token);
  13412. if (batch.embd) free(batch.embd);
  13413. if (batch.pos) free(batch.pos);
  13414. if (batch.n_seq_id) free(batch.n_seq_id);
  13415. if (batch.seq_id) {
  13416. for (int i = 0; batch.seq_id[i] != nullptr; ++i) {
  13417. free(batch.seq_id[i]);
  13418. }
  13419. free(batch.seq_id);
  13420. }
  13421. if (batch.logits) free(batch.logits);
  13422. }
  13423. int32_t llama_decode(
  13424. struct llama_context * ctx,
  13425. struct llama_batch batch) {
  13426. const int ret = llama_decode_internal(*ctx, batch);
  13427. if (ret < 0) {
  13428. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  13429. }
  13430. return ret;
  13431. }
  13432. void llama_synchronize(struct llama_context * ctx) {
  13433. ggml_backend_sched_synchronize(ctx->sched);
  13434. // FIXME: if multiple single tokens are evaluated without a synchronization,
  13435. // the stats will be added to the prompt evaluation stats
  13436. // this should only happen when using batch size 1 to evaluate a batch
  13437. // add the evaluation to the stats
  13438. if (ctx->n_queued_tokens == 1) {
  13439. ctx->t_eval_us += ggml_time_us() - ctx->t_compute_start_us;
  13440. ctx->n_eval++;
  13441. } else if (ctx->n_queued_tokens > 1) {
  13442. ctx->t_p_eval_us += ggml_time_us() - ctx->t_compute_start_us;
  13443. ctx->n_p_eval += ctx->n_queued_tokens;
  13444. }
  13445. // get a more accurate load time, upon first eval
  13446. if (ctx->n_queued_tokens > 0 && !ctx->has_evaluated_once) {
  13447. ctx->t_load_us = ggml_time_us() - ctx->t_start_us;
  13448. ctx->has_evaluated_once = true;
  13449. }
  13450. ctx->n_queued_tokens = 0;
  13451. ctx->t_compute_start_us = 0;
  13452. }
  13453. float * llama_get_logits(struct llama_context * ctx) {
  13454. llama_synchronize(ctx);
  13455. return ctx->logits;
  13456. }
  13457. float * llama_get_logits_ith(struct llama_context * ctx, int32_t i) {
  13458. int32_t j = -1;
  13459. llama_synchronize(ctx);
  13460. try {
  13461. if (ctx->logits == nullptr) {
  13462. throw std::runtime_error("no logits");
  13463. }
  13464. if (i < 0) {
  13465. j = ctx->n_outputs + i;
  13466. if (j < 0) {
  13467. throw std::runtime_error(format("negative index out of range [0, %d)", ctx->n_outputs));
  13468. }
  13469. } else if ((size_t) i >= ctx->output_ids.size()) {
  13470. throw std::runtime_error(format("out of range [0, %lu)", ctx->output_ids.size()));
  13471. } else {
  13472. j = ctx->output_ids[i];
  13473. }
  13474. if (j < 0) {
  13475. throw std::runtime_error(format("batch.logits[%d] != true", i));
  13476. }
  13477. if (j >= ctx->n_outputs) {
  13478. // This should not happen
  13479. throw std::runtime_error(format("corrupt output buffer (j=%d, n_outputs=%d)", j, ctx->n_outputs));
  13480. }
  13481. return ctx->logits + j*ctx->model.hparams.n_vocab;
  13482. } catch (const std::exception & err) {
  13483. LLAMA_LOG_ERROR("%s: invalid logits id %d, reason: %s\n", __func__, i, err.what());
  13484. #ifndef NDEBUG
  13485. GGML_ASSERT(false);
  13486. #endif
  13487. return nullptr;
  13488. }
  13489. }
  13490. float * llama_get_embeddings(struct llama_context * ctx) {
  13491. llama_synchronize(ctx);
  13492. return ctx->embd;
  13493. }
  13494. float * llama_get_embeddings_ith(struct llama_context * ctx, int32_t i) {
  13495. int32_t j = -1;
  13496. llama_synchronize(ctx);
  13497. try {
  13498. if (ctx->embd == nullptr) {
  13499. throw std::runtime_error("no embeddings");
  13500. }
  13501. if (i < 0) {
  13502. j = ctx->n_outputs + i;
  13503. if (j < 0) {
  13504. throw std::runtime_error(format("negative index out of range [0, %d)", ctx->n_outputs));
  13505. }
  13506. } else if ((size_t) i >= ctx->output_ids.size()) {
  13507. throw std::runtime_error(format("out of range [0, %lu)", ctx->output_ids.size()));
  13508. } else {
  13509. j = ctx->output_ids[i];
  13510. }
  13511. if (j < 0) {
  13512. throw std::runtime_error(format("batch.logits[%d] != true", i));
  13513. }
  13514. if (j >= ctx->n_outputs) {
  13515. // This should not happen
  13516. throw std::runtime_error(format("corrupt output buffer (j=%d, n_outputs=%d)", j, ctx->n_outputs));
  13517. }
  13518. return ctx->embd + j*ctx->model.hparams.n_embd;
  13519. } catch (const std::exception & err) {
  13520. LLAMA_LOG_ERROR("%s: invalid embeddings id %d, reason: %s\n", __func__, i, err.what());
  13521. #ifndef NDEBUG
  13522. GGML_ASSERT(false);
  13523. #endif
  13524. return nullptr;
  13525. }
  13526. }
  13527. float * llama_get_embeddings_seq(struct llama_context * ctx, llama_seq_id seq_id) {
  13528. llama_synchronize(ctx);
  13529. auto it = ctx->embd_seq.find(seq_id);
  13530. if (it == ctx->embd_seq.end()) {
  13531. return nullptr;
  13532. }
  13533. return it->second.data();
  13534. }
  13535. const char * llama_token_get_text(const struct llama_model * model, llama_token token) {
  13536. GGML_ASSERT(model->vocab.type != LLAMA_VOCAB_TYPE_NONE);
  13537. return model->vocab.id_to_token[token].text.c_str();
  13538. }
  13539. float llama_token_get_score(const struct llama_model * model, llama_token token) {
  13540. GGML_ASSERT(model->vocab.type != LLAMA_VOCAB_TYPE_NONE);
  13541. return model->vocab.id_to_token[token].score;
  13542. }
  13543. llama_token_type llama_token_get_type(const struct llama_model * model, llama_token token) {
  13544. GGML_ASSERT(model->vocab.type != LLAMA_VOCAB_TYPE_NONE);
  13545. return model->vocab.id_to_token[token].type;
  13546. }
  13547. llama_token llama_token_bos(const struct llama_model * model) {
  13548. return model->vocab.special_bos_id;
  13549. }
  13550. llama_token llama_token_eos(const struct llama_model * model) {
  13551. return model->vocab.special_eos_id;
  13552. }
  13553. llama_token llama_token_cls(const struct llama_model * model) {
  13554. return model->vocab.special_cls_id;
  13555. }
  13556. llama_token llama_token_sep(const struct llama_model * model) {
  13557. return model->vocab.special_sep_id;
  13558. }
  13559. llama_token llama_token_nl(const struct llama_model * model) {
  13560. return model->vocab.linefeed_id;
  13561. }
  13562. int32_t llama_add_bos_token(const struct llama_model * model) {
  13563. return model->vocab.special_add_bos;
  13564. }
  13565. int32_t llama_add_eos_token(const struct llama_model * model) {
  13566. return model->vocab.special_add_eos;
  13567. }
  13568. llama_token llama_token_prefix(const struct llama_model * model) {
  13569. return model->vocab.special_prefix_id;
  13570. }
  13571. llama_token llama_token_middle(const struct llama_model * model) {
  13572. return model->vocab.special_middle_id;
  13573. }
  13574. llama_token llama_token_suffix(const struct llama_model * model) {
  13575. return model->vocab.special_suffix_id;
  13576. }
  13577. llama_token llama_token_eot(const struct llama_model * model) {
  13578. return model->vocab.special_eot_id;
  13579. }
  13580. int32_t llama_tokenize(
  13581. const struct llama_model * model,
  13582. const char * text,
  13583. int32_t text_len,
  13584. llama_token * tokens,
  13585. int32_t n_tokens_max,
  13586. bool add_special,
  13587. bool parse_special) {
  13588. auto res = llama_tokenize_internal(model->vocab, std::string(text, text_len), add_special, parse_special);
  13589. if (n_tokens_max < (int) res.size()) {
  13590. // LLAMA_LOG_ERROR("%s: too many tokens\n", __func__);
  13591. return -((int) res.size());
  13592. }
  13593. for (size_t i = 0; i < res.size(); i++) {
  13594. tokens[i] = res[i];
  13595. }
  13596. return res.size();
  13597. }
  13598. static std::string llama_decode_text(const std::string & text) {
  13599. std::string decoded_text;
  13600. auto unicode_sequences = unicode_cpts_from_utf8(text);
  13601. for (auto & unicode_sequence : unicode_sequences) {
  13602. decoded_text += unicode_utf8_to_byte(unicode_cpt_to_utf8(unicode_sequence));
  13603. }
  13604. return decoded_text;
  13605. }
  13606. // does not write null-terminator to buf
  13607. int32_t llama_token_to_piece(const struct llama_model * model, llama_token token, char * buf, int32_t length) {
  13608. if (0 <= token && token < llama_n_vocab(model)) {
  13609. switch (llama_vocab_get_type(model->vocab)) {
  13610. case LLAMA_VOCAB_TYPE_WPM:
  13611. case LLAMA_VOCAB_TYPE_SPM: {
  13612. // NOTE: we accept all unsupported token types,
  13613. // suppressing them like CONTROL tokens.
  13614. if (llama_is_normal_token(model->vocab, token)) {
  13615. std::string result = model->vocab.id_to_token[token].text;
  13616. llama_unescape_whitespace(result);
  13617. if (length < (int) result.length()) {
  13618. return -(int) result.length();
  13619. }
  13620. memcpy(buf, result.c_str(), result.length());
  13621. return result.length();
  13622. } else if (llama_is_user_defined_token(model->vocab, token)) {
  13623. std::string result = model->vocab.id_to_token[token].text;
  13624. if (length < (int) result.length()) {
  13625. return -(int) result.length();
  13626. }
  13627. memcpy(buf, result.c_str(), result.length());
  13628. return result.length();
  13629. } else if (llama_is_unknown_token(model->vocab, token)) { // NOLINT
  13630. if (length < 3) {
  13631. return -3;
  13632. }
  13633. memcpy(buf, "\xe2\x96\x85", 3);
  13634. return 3;
  13635. } else if (llama_is_control_token(model->vocab, token)) {
  13636. ;
  13637. } else if (llama_is_byte_token(model->vocab, token)) {
  13638. if (length < 1) {
  13639. return -1;
  13640. }
  13641. buf[0] = llama_token_to_byte(model->vocab, token);
  13642. return 1;
  13643. }
  13644. break;
  13645. }
  13646. case LLAMA_VOCAB_TYPE_BPE: {
  13647. // NOTE: we accept all unsupported token types,
  13648. // suppressing them like CONTROL tokens.
  13649. if (llama_is_normal_token(model->vocab, token)) {
  13650. std::string result = model->vocab.id_to_token[token].text;
  13651. result = llama_decode_text(result);
  13652. if (length < (int) result.length()) {
  13653. return -(int) result.length();
  13654. }
  13655. memcpy(buf, result.c_str(), result.length());
  13656. return result.length();
  13657. } else if (llama_is_user_defined_token(model->vocab, token)) {
  13658. std::string result = model->vocab.id_to_token[token].text;
  13659. if (length < (int) result.length()) {
  13660. return -(int) result.length();
  13661. }
  13662. memcpy(buf, result.c_str(), result.length());
  13663. return result.length();
  13664. } else if (llama_is_control_token(model->vocab, token)) {
  13665. ;
  13666. }
  13667. break;
  13668. }
  13669. default:
  13670. GGML_ASSERT(false);
  13671. }
  13672. }
  13673. return 0;
  13674. }
  13675. // trim whitespace from the beginning and end of a string
  13676. static std::string trim(const std::string & str) {
  13677. size_t start = 0;
  13678. size_t end = str.size();
  13679. while (start < end && isspace(str[start])) {
  13680. start += 1;
  13681. }
  13682. while (end > start && isspace(str[end - 1])) {
  13683. end -= 1;
  13684. }
  13685. return str.substr(start, end - start);
  13686. }
  13687. // Simple version of "llama_apply_chat_template" that only works with strings
  13688. // This function uses heuristic checks to determine commonly used template. It is not a jinja parser.
  13689. static int32_t llama_chat_apply_template_internal(
  13690. const std::string & tmpl,
  13691. const std::vector<const llama_chat_message *> & chat,
  13692. std::string & dest, bool add_ass) {
  13693. // Taken from the research: https://github.com/ggerganov/llama.cpp/issues/5527
  13694. std::stringstream ss;
  13695. if (tmpl == "chatml" || tmpl.find("<|im_start|>") != std::string::npos) {
  13696. // chatml template
  13697. for (auto message : chat) {
  13698. ss << "<|im_start|>" << message->role << "\n" << message->content << "<|im_end|>\n";
  13699. }
  13700. if (add_ass) {
  13701. ss << "<|im_start|>assistant\n";
  13702. }
  13703. } else if (tmpl == "llama2" || tmpl.find("[INST]") != std::string::npos) {
  13704. // llama2 template and its variants
  13705. // [variant] support system message
  13706. bool support_system_message = tmpl.find("<<SYS>>") != std::string::npos;
  13707. // [variant] space before + after response
  13708. bool space_around_response = tmpl.find("' ' + eos_token") != std::string::npos;
  13709. // [variant] add BOS inside history
  13710. bool add_bos_inside_history = tmpl.find("bos_token + '[INST]") != std::string::npos;
  13711. // [variant] trim spaces from the input message
  13712. bool strip_message = tmpl.find("content.strip()") != std::string::npos;
  13713. // construct the prompt
  13714. bool is_inside_turn = true; // skip BOS at the beginning
  13715. ss << "[INST] ";
  13716. for (auto message : chat) {
  13717. std::string content = strip_message ? trim(message->content) : message->content;
  13718. std::string role(message->role);
  13719. if (!is_inside_turn) {
  13720. is_inside_turn = true;
  13721. ss << (add_bos_inside_history ? "<s>[INST] " : "[INST] ");
  13722. }
  13723. if (role == "system") {
  13724. if (support_system_message) {
  13725. ss << "<<SYS>>\n" << content << "\n<</SYS>>\n\n";
  13726. } else {
  13727. // if the model does not support system message, we still include it in the first message, but without <<SYS>>
  13728. ss << content << "\n";
  13729. }
  13730. } else if (role == "user") {
  13731. ss << content << " [/INST]";
  13732. } else {
  13733. ss << (space_around_response ? " " : "") << content << (space_around_response ? " " : "") << "</s>";
  13734. is_inside_turn = false;
  13735. }
  13736. }
  13737. // llama2 templates seem to not care about "add_generation_prompt"
  13738. } else if (tmpl == "zephyr" || tmpl.find("<|user|>") != std::string::npos) {
  13739. // zephyr template
  13740. for (auto message : chat) {
  13741. ss << "<|" << message->role << "|>" << "\n" << message->content << "<|endoftext|>\n";
  13742. }
  13743. if (add_ass) {
  13744. ss << "<|assistant|>\n";
  13745. }
  13746. } else if (tmpl == "monarch" || tmpl.find("bos_token + message['role']") != std::string::npos) {
  13747. // mlabonne/AlphaMonarch-7B template (the <s> is included inside history)
  13748. for (auto message : chat) {
  13749. std::string bos = (message == chat.front()) ? "" : "<s>"; // skip BOS for first message
  13750. ss << bos << message->role << "\n" << message->content << "</s>\n";
  13751. }
  13752. if (add_ass) {
  13753. ss << "<s>assistant\n";
  13754. }
  13755. } else if (tmpl == "gemma" || tmpl.find("<start_of_turn>") != std::string::npos) {
  13756. // google/gemma-7b-it
  13757. std::string system_prompt = "";
  13758. for (auto message : chat) {
  13759. std::string role(message->role);
  13760. if (role == "system") {
  13761. // there is no system message for gemma, but we will merge it with user prompt, so nothing is broken
  13762. system_prompt = trim(message->content);
  13763. continue;
  13764. }
  13765. // in gemma, "assistant" is "model"
  13766. role = role == "assistant" ? "model" : message->role;
  13767. ss << "<start_of_turn>" << role << "\n";
  13768. if (!system_prompt.empty() && role != "model") {
  13769. ss << system_prompt << "\n\n";
  13770. system_prompt = "";
  13771. }
  13772. ss << trim(message->content) << "<end_of_turn>\n";
  13773. }
  13774. if (add_ass) {
  13775. ss << "<start_of_turn>model\n";
  13776. }
  13777. } else if (tmpl == "orion" || tmpl.find("'\\n\\nAssistant: ' + eos_token") != std::string::npos) {
  13778. // OrionStarAI/Orion-14B-Chat
  13779. std::string system_prompt = "";
  13780. for (auto message : chat) {
  13781. std::string role(message->role);
  13782. if (role == "system") {
  13783. // there is no system message support, we will merge it with user prompt
  13784. system_prompt = message->content;
  13785. continue;
  13786. } else if (role == "user") {
  13787. ss << "Human: ";
  13788. if (!system_prompt.empty()) {
  13789. ss << system_prompt << "\n\n";
  13790. system_prompt = "";
  13791. }
  13792. ss << message->content << "\n\nAssistant: </s>";
  13793. } else {
  13794. ss << message->content << "</s>";
  13795. }
  13796. }
  13797. } else if (tmpl == "openchat" || tmpl.find("GPT4 Correct ") != std::string::npos) {
  13798. // openchat/openchat-3.5-0106,
  13799. for (auto message : chat) {
  13800. std::string role(message->role);
  13801. if (role == "system") {
  13802. ss << message->content << "<|end_of_turn|>";
  13803. } else {
  13804. role[0] = toupper(role[0]);
  13805. ss << "GPT4 Correct " << role << ": " << message->content << "<|end_of_turn|>";
  13806. }
  13807. }
  13808. if (add_ass) {
  13809. ss << "GPT4 Correct Assistant:";
  13810. }
  13811. } else if (tmpl == "vicuna" || tmpl == "vicuna-orca" || (tmpl.find("USER: ") != std::string::npos && tmpl.find("ASSISTANT: ") != std::string::npos)) {
  13812. // eachadea/vicuna-13b-1.1 (and Orca variant)
  13813. for (auto message : chat) {
  13814. std::string role(message->role);
  13815. if (role == "system") {
  13816. // Orca-Vicuna variant uses a system prefix
  13817. if (tmpl == "vicuna-orca" || tmpl.find("SYSTEM: ") != std::string::npos) {
  13818. ss << "SYSTEM: " << message->content << "\n";
  13819. } else {
  13820. ss << message->content << "\n\n";
  13821. }
  13822. } else if (role == "user") {
  13823. ss << "USER: " << message->content << "\n";
  13824. } else if (role == "assistant") {
  13825. ss << "ASSISTANT: " << message->content << "</s>\n";
  13826. }
  13827. }
  13828. if (add_ass) {
  13829. ss << "ASSISTANT:";
  13830. }
  13831. } else if (tmpl == "deepseek" || (tmpl.find("### Instruction:") != std::string::npos && tmpl.find("<|EOT|>") != std::string::npos)) {
  13832. // deepseek-ai/deepseek-coder-33b-instruct
  13833. for (auto message : chat) {
  13834. std::string role(message->role);
  13835. if (role == "system") {
  13836. ss << message->content;
  13837. } else if (role == "user") {
  13838. ss << "### Instruction:\n" << message->content << "\n";
  13839. } else if (role == "assistant") {
  13840. ss << "### Response:\n" << message->content << "\n<|EOT|>\n";
  13841. }
  13842. }
  13843. if (add_ass) {
  13844. ss << "### Response:\n";
  13845. }
  13846. } else {
  13847. // template not supported
  13848. return -1;
  13849. }
  13850. dest = ss.str();
  13851. return dest.size();
  13852. }
  13853. LLAMA_API int32_t llama_chat_apply_template(
  13854. const struct llama_model * model,
  13855. const char * tmpl,
  13856. const struct llama_chat_message * chat,
  13857. size_t n_msg,
  13858. bool add_ass,
  13859. char * buf,
  13860. int32_t length) {
  13861. std::string curr_tmpl(tmpl == nullptr ? "" : tmpl);
  13862. if (tmpl == nullptr) {
  13863. GGML_ASSERT(model != nullptr);
  13864. // load template from model
  13865. std::vector<char> model_template(2048, 0); // longest known template is about 1200 bytes
  13866. std::string template_key = "tokenizer.chat_template";
  13867. int32_t res = llama_model_meta_val_str(model, template_key.c_str(), model_template.data(), model_template.size());
  13868. if (res < 0) {
  13869. // worst case: there is no information about template, we will use chatml by default
  13870. curr_tmpl = "chatml"; // see llama_chat_apply_template_internal
  13871. } else {
  13872. curr_tmpl = std::string(model_template.data(), model_template.size());
  13873. }
  13874. }
  13875. // format the chat to string
  13876. std::vector<const llama_chat_message *> chat_vec;
  13877. chat_vec.resize(n_msg);
  13878. for (size_t i = 0; i < n_msg; i++) {
  13879. chat_vec[i] = &chat[i];
  13880. }
  13881. std::string formatted_chat;
  13882. int32_t res = llama_chat_apply_template_internal(curr_tmpl, chat_vec, formatted_chat, add_ass);
  13883. if (res < 0) {
  13884. return res;
  13885. }
  13886. if (buf && length > 0) {
  13887. strncpy(buf, formatted_chat.c_str(), length);
  13888. }
  13889. return res;
  13890. }
  13891. LLAMA_API int llama_split_path(char * split_path, size_t maxlen, const char * path_prefix, int split_no, int split_count) {
  13892. static const char * const SPLIT_PATH_FORMAT = "%s-%05d-of-%05d.gguf";
  13893. if (snprintf(split_path, maxlen, SPLIT_PATH_FORMAT, path_prefix, split_no + 1, split_count)) {
  13894. return strlen(split_path);
  13895. }
  13896. return 0;
  13897. }
  13898. int llama_split_prefix(char * dest, size_t maxlen, const char * split_path, int split_no, int split_count) {
  13899. std::string str_split_path(split_path);
  13900. char postfix[32];
  13901. snprintf(postfix, 32, "-%05d-of-%05d.gguf", split_no + 1, split_count);
  13902. std::string str_postfix(postfix);
  13903. // check if dest ends with postfix
  13904. int size_prefix = str_split_path.size() - str_postfix.size();
  13905. if (size_prefix > 0 && str_split_path.find(str_postfix, size_prefix) != std::string::npos) {
  13906. snprintf(dest, std::min((size_t) size_prefix + 1, maxlen), "%s", split_path);
  13907. return size_prefix;
  13908. }
  13909. return 0;
  13910. }
  13911. struct llama_timings llama_get_timings(struct llama_context * ctx) {
  13912. struct llama_timings result = {
  13913. /*.t_start_ms =*/ 1e-3 * ctx->t_start_us,
  13914. /*.t_end_ms =*/ 1.00 * ggml_time_ms(),
  13915. /*.t_load_ms =*/ 1e-3 * ctx->t_load_us,
  13916. /*.t_sample_ms =*/ 1e-3 * ctx->t_sample_us,
  13917. /*.t_p_eval_ms =*/ 1e-3 * ctx->t_p_eval_us,
  13918. /*.t_eval_ms =*/ 1e-3 * ctx->t_eval_us,
  13919. /*.n_sample =*/ std::max(1, ctx->n_sample),
  13920. /*.n_p_eval =*/ std::max(1, ctx->n_p_eval),
  13921. /*.n_eval =*/ std::max(1, ctx->n_eval),
  13922. };
  13923. return result;
  13924. }
  13925. void llama_print_timings(struct llama_context * ctx) {
  13926. const llama_timings timings = llama_get_timings(ctx);
  13927. LLAMA_LOG_INFO("\n");
  13928. LLAMA_LOG_INFO("%s: load time = %10.2f ms\n", __func__, timings.t_load_ms);
  13929. LLAMA_LOG_INFO("%s: sample time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  13930. __func__, timings.t_sample_ms, timings.n_sample, timings.t_sample_ms / timings.n_sample, 1e3 / timings.t_sample_ms * timings.n_sample);
  13931. LLAMA_LOG_INFO("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  13932. __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);
  13933. LLAMA_LOG_INFO("%s: eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  13934. __func__, timings.t_eval_ms, timings.n_eval, timings.t_eval_ms / timings.n_eval, 1e3 / timings.t_eval_ms * timings.n_eval);
  13935. 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));
  13936. }
  13937. void llama_reset_timings(struct llama_context * ctx) {
  13938. ctx->t_start_us = ggml_time_us();
  13939. ctx->t_sample_us = ctx->n_sample = 0;
  13940. ctx->t_eval_us = ctx->n_eval = 0;
  13941. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  13942. }
  13943. const char * llama_print_system_info(void) {
  13944. static std::string s;
  13945. s = "";
  13946. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  13947. s += "AVX_VNNI = " + std::to_string(ggml_cpu_has_avx_vnni()) + " | ";
  13948. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  13949. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  13950. s += "AVX512_VBMI = " + std::to_string(ggml_cpu_has_avx512_vbmi()) + " | ";
  13951. s += "AVX512_VNNI = " + std::to_string(ggml_cpu_has_avx512_vnni()) + " | ";
  13952. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  13953. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  13954. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  13955. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  13956. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  13957. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  13958. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  13959. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  13960. s += "SSSE3 = " + std::to_string(ggml_cpu_has_ssse3()) + " | ";
  13961. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  13962. s += "MATMUL_INT8 = " + std::to_string(ggml_cpu_has_matmul_int8()) + " | ";
  13963. return s.c_str();
  13964. }
  13965. void llama_dump_timing_info_yaml(FILE * stream, const llama_context * ctx) {
  13966. fprintf(stream, "\n");
  13967. fprintf(stream, "###########\n");
  13968. fprintf(stream, "# Timings #\n");
  13969. fprintf(stream, "###########\n");
  13970. fprintf(stream, "\n");
  13971. fprintf(stream, "mst_eval: %.2f # ms / token during generation\n",
  13972. 1.0e-3 * ctx->t_eval_us / ctx->n_eval);
  13973. fprintf(stream, "mst_p_eval: %.2f # ms / token during prompt processing\n",
  13974. 1.0e-3 * ctx->t_p_eval_us / ctx->n_p_eval);
  13975. fprintf(stream, "mst_sample: %.2f # ms / token during sampling\n",
  13976. 1.0e-3 * ctx->t_sample_us / ctx->n_sample);
  13977. fprintf(stream, "n_eval: %d # number of tokens generated (excluding the first one)\n", ctx->n_eval);
  13978. fprintf(stream, "n_p_eval: %d # number of tokens processed in batches at the beginning\n", ctx->n_p_eval);
  13979. fprintf(stream, "n_sample: %d # number of sampled tokens\n", ctx->n_sample);
  13980. fprintf(stream, "t_eval_us: %" PRId64 " # total microseconds spent generating tokens\n", ctx->t_eval_us);
  13981. fprintf(stream, "t_load_us: %" PRId64 " # total microseconds spent loading the model\n", ctx->t_load_us);
  13982. fprintf(stream, "t_p_eval_us: %" PRId64 " # total microseconds spent prompt processing\n", ctx->t_p_eval_us);
  13983. fprintf(stream, "t_sample_us: %" PRId64 " # total microseconds spent sampling\n", ctx->t_sample_us);
  13984. fprintf(stream, "ts_eval: %.2f # tokens / second during generation\n",
  13985. 1.0e6 * ctx->n_eval / ctx->t_eval_us);
  13986. fprintf(stream, "ts_p_eval: %.2f # tokens / second during prompt processing\n",
  13987. 1.0e6 * ctx->n_p_eval / ctx->t_p_eval_us);
  13988. fprintf(stream, "ts_sample: %.2f # tokens / second during sampling\n",
  13989. 1.0e6 * ctx->n_sample / ctx->t_sample_us);
  13990. }
  13991. // For internal test use
  13992. const std::vector<std::pair<std::string, struct ggml_tensor *>> & llama_internal_get_tensor_map(
  13993. struct llama_context * ctx
  13994. ) {
  13995. return ctx->model.tensors_by_name;
  13996. }
  13997. void llama_log_set(ggml_log_callback log_callback, void * user_data) {
  13998. g_state.log_callback = log_callback ? log_callback : llama_log_callback_default;
  13999. g_state.log_callback_user_data = user_data;
  14000. #ifdef GGML_USE_METAL
  14001. ggml_backend_metal_log_set_callback(g_state.log_callback, g_state.log_callback_user_data);
  14002. #endif
  14003. }
  14004. static void llama_log_internal_v(ggml_log_level level, const char * format, va_list args) {
  14005. va_list args_copy;
  14006. va_copy(args_copy, args);
  14007. char buffer[128];
  14008. int len = vsnprintf(buffer, 128, format, args);
  14009. if (len < 128) {
  14010. g_state.log_callback(level, buffer, g_state.log_callback_user_data);
  14011. } else {
  14012. char* buffer2 = new char[len+1];
  14013. vsnprintf(buffer2, len+1, format, args_copy);
  14014. buffer2[len] = 0;
  14015. g_state.log_callback(level, buffer2, g_state.log_callback_user_data);
  14016. delete[] buffer2;
  14017. }
  14018. va_end(args_copy);
  14019. }
  14020. static void llama_log_internal(ggml_log_level level, const char * format, ...) {
  14021. va_list args;
  14022. va_start(args, format);
  14023. llama_log_internal_v(level, format, args);
  14024. va_end(args);
  14025. }
  14026. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data) {
  14027. (void) level;
  14028. (void) user_data;
  14029. fputs(text, stderr);
  14030. fflush(stderr);
  14031. }