llama.cpp 664 KB

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