llama.cpp 622 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908
  1. #define LLAMA_API_INTERNAL
  2. #include "llama.h"
  3. #include "unicode.h"
  4. #include "ggml.h"
  5. #include "ggml-alloc.h"
  6. #include "ggml-backend.h"
  7. #ifdef GGML_USE_CUDA
  8. # include "ggml-cuda.h"
  9. #elif defined(GGML_USE_CLBLAST)
  10. # include "ggml-opencl.h"
  11. #elif defined(GGML_USE_VULKAN)
  12. # include "ggml-vulkan.h"
  13. #elif defined(GGML_USE_SYCL)
  14. # include "ggml-sycl.h"
  15. #elif defined(GGML_USE_KOMPUTE)
  16. # include "ggml-kompute.h"
  17. #endif
  18. #ifdef GGML_USE_METAL
  19. # include "ggml-metal.h"
  20. #endif
  21. #ifdef GGML_USE_MPI
  22. # include "ggml-mpi.h"
  23. #endif
  24. #ifndef QK_K
  25. # ifdef GGML_QKK_64
  26. # define QK_K 64
  27. # else
  28. # define QK_K 256
  29. # endif
  30. #endif
  31. #ifdef __has_include
  32. #if __has_include(<unistd.h>)
  33. #include <unistd.h>
  34. #if defined(_POSIX_MAPPED_FILES)
  35. #include <sys/mman.h>
  36. #include <fcntl.h>
  37. #endif
  38. #if defined(_POSIX_MEMLOCK_RANGE)
  39. #include <sys/resource.h>
  40. #endif
  41. #endif
  42. #endif
  43. #if defined(_WIN32)
  44. #define WIN32_LEAN_AND_MEAN
  45. #ifndef NOMINMAX
  46. #define NOMINMAX
  47. #endif
  48. #include <windows.h>
  49. #ifndef PATH_MAX
  50. #define PATH_MAX MAX_PATH
  51. #endif
  52. #include <io.h>
  53. #endif
  54. #include <algorithm>
  55. #include <array>
  56. #include <cassert>
  57. #include <cctype>
  58. #include <cfloat>
  59. #include <cinttypes>
  60. #include <climits>
  61. #include <cmath>
  62. #include <cstdarg>
  63. #include <cstddef>
  64. #include <cstdint>
  65. #include <cstdio>
  66. #include <cstring>
  67. #include <ctime>
  68. #include <forward_list>
  69. #include <fstream>
  70. #include <functional>
  71. #include <initializer_list>
  72. #include <locale>
  73. #include <map>
  74. #include <memory>
  75. #include <mutex>
  76. #include <numeric>
  77. #include <queue>
  78. #include <random>
  79. #include <regex>
  80. #include <set>
  81. #include <sstream>
  82. #include <thread>
  83. #include <type_traits>
  84. #include <unordered_map>
  85. #if defined(_MSC_VER)
  86. #pragma warning(disable: 4244 4267) // possible loss of data
  87. #endif
  88. #ifdef __GNUC__
  89. #ifdef __MINGW32__
  90. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(gnu_printf, __VA_ARGS__)))
  91. #else
  92. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(printf, __VA_ARGS__)))
  93. #endif
  94. #else
  95. #define LLAMA_ATTRIBUTE_FORMAT(...)
  96. #endif
  97. #define LLAMA_MAX_NODES 8192
  98. #define LLAMA_MAX_EXPERTS 8
  99. //
  100. // logging
  101. //
  102. LLAMA_ATTRIBUTE_FORMAT(2, 3)
  103. static void llama_log_internal (ggml_log_level level, const char* format, ...);
  104. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data);
  105. #define LLAMA_LOG_INFO(...) llama_log_internal(GGML_LOG_LEVEL_INFO , __VA_ARGS__)
  106. #define LLAMA_LOG_WARN(...) llama_log_internal(GGML_LOG_LEVEL_WARN , __VA_ARGS__)
  107. #define LLAMA_LOG_ERROR(...) llama_log_internal(GGML_LOG_LEVEL_ERROR, __VA_ARGS__)
  108. //
  109. // helpers
  110. //
  111. static size_t utf8_len(char src) {
  112. const size_t lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4 };
  113. uint8_t highbits = static_cast<uint8_t>(src) >> 4;
  114. return lookup[highbits];
  115. }
  116. static void replace_all(std::string & s, const std::string & search, const std::string & replace) {
  117. std::string result;
  118. for (size_t pos = 0; ; pos += search.length()) {
  119. auto new_pos = s.find(search, pos);
  120. if (new_pos == std::string::npos) {
  121. result += s.substr(pos, s.size() - pos);
  122. break;
  123. }
  124. result += s.substr(pos, new_pos - pos) + replace;
  125. pos = new_pos;
  126. }
  127. s = std::move(result);
  128. }
  129. static bool is_float_close(float a, float b, float abs_tol) {
  130. // Check for non-negative tolerance
  131. if (abs_tol < 0.0) {
  132. throw std::invalid_argument("Tolerance must be non-negative");
  133. }
  134. // Exact equality check
  135. if (a == b) {
  136. return true;
  137. }
  138. // Check for infinities
  139. if (std::isinf(a) || std::isinf(b)) {
  140. return false;
  141. }
  142. // Regular comparison using the provided absolute tolerance
  143. return std::fabs(b - a) <= abs_tol;
  144. }
  145. static void zeros(std::ofstream & file, size_t n) {
  146. char zero = 0;
  147. for (size_t i = 0; i < n; ++i) {
  148. file.write(&zero, 1);
  149. }
  150. }
  151. LLAMA_ATTRIBUTE_FORMAT(1, 2)
  152. static std::string format(const char * fmt, ...) {
  153. va_list ap;
  154. va_list ap2;
  155. va_start(ap, fmt);
  156. va_copy(ap2, ap);
  157. int size = vsnprintf(NULL, 0, fmt, ap);
  158. GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
  159. std::vector<char> buf(size + 1);
  160. int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
  161. GGML_ASSERT(size2 == size);
  162. va_end(ap2);
  163. va_end(ap);
  164. return std::string(buf.data(), size);
  165. }
  166. //
  167. // gguf constants (sync with gguf.py)
  168. //
  169. enum llm_arch {
  170. LLM_ARCH_LLAMA,
  171. LLM_ARCH_FALCON,
  172. LLM_ARCH_BAICHUAN,
  173. LLM_ARCH_GROK,
  174. LLM_ARCH_GPT2,
  175. LLM_ARCH_GPTJ,
  176. LLM_ARCH_GPTNEOX,
  177. LLM_ARCH_MPT,
  178. LLM_ARCH_STARCODER,
  179. LLM_ARCH_PERSIMMON,
  180. LLM_ARCH_REFACT,
  181. LLM_ARCH_BERT,
  182. LLM_ARCH_NOMIC_BERT,
  183. LLM_ARCH_BLOOM,
  184. LLM_ARCH_STABLELM,
  185. LLM_ARCH_QWEN,
  186. LLM_ARCH_QWEN2,
  187. LLM_ARCH_PHI2,
  188. LLM_ARCH_PLAMO,
  189. LLM_ARCH_CODESHELL,
  190. LLM_ARCH_ORION,
  191. LLM_ARCH_INTERNLM2,
  192. LLM_ARCH_MINICPM,
  193. LLM_ARCH_GEMMA,
  194. LLM_ARCH_STARCODER2,
  195. LLM_ARCH_MAMBA,
  196. LLM_ARCH_XVERSE,
  197. LLM_ARCH_COMMAND_R,
  198. LLM_ARCH_UNKNOWN,
  199. };
  200. static const std::map<llm_arch, const char *> LLM_ARCH_NAMES = {
  201. { LLM_ARCH_LLAMA, "llama" },
  202. { LLM_ARCH_FALCON, "falcon" },
  203. { LLM_ARCH_GROK, "grok" },
  204. { LLM_ARCH_GPT2, "gpt2" },
  205. { LLM_ARCH_GPTJ, "gptj" },
  206. { LLM_ARCH_GPTNEOX, "gptneox" },
  207. { LLM_ARCH_MPT, "mpt" },
  208. { LLM_ARCH_BAICHUAN, "baichuan" },
  209. { LLM_ARCH_STARCODER, "starcoder" },
  210. { LLM_ARCH_PERSIMMON, "persimmon" },
  211. { LLM_ARCH_REFACT, "refact" },
  212. { LLM_ARCH_BERT, "bert" },
  213. { LLM_ARCH_NOMIC_BERT, "nomic-bert" },
  214. { LLM_ARCH_BLOOM, "bloom" },
  215. { LLM_ARCH_STABLELM, "stablelm" },
  216. { LLM_ARCH_QWEN, "qwen" },
  217. { LLM_ARCH_QWEN2, "qwen2" },
  218. { LLM_ARCH_PHI2, "phi2" },
  219. { LLM_ARCH_PLAMO, "plamo" },
  220. { LLM_ARCH_CODESHELL, "codeshell" },
  221. { LLM_ARCH_ORION, "orion" },
  222. { LLM_ARCH_INTERNLM2, "internlm2" },
  223. { LLM_ARCH_MINICPM, "minicpm" },
  224. { LLM_ARCH_GEMMA, "gemma" },
  225. { LLM_ARCH_STARCODER2, "starcoder2" },
  226. { LLM_ARCH_MAMBA, "mamba" },
  227. { LLM_ARCH_XVERSE, "xverse" },
  228. { LLM_ARCH_COMMAND_R, "command-r" },
  229. { LLM_ARCH_UNKNOWN, "(unknown)" },
  230. };
  231. enum llm_kv {
  232. LLM_KV_GENERAL_ARCHITECTURE,
  233. LLM_KV_GENERAL_QUANTIZATION_VERSION,
  234. LLM_KV_GENERAL_ALIGNMENT,
  235. LLM_KV_GENERAL_NAME,
  236. LLM_KV_GENERAL_AUTHOR,
  237. LLM_KV_GENERAL_URL,
  238. LLM_KV_GENERAL_DESCRIPTION,
  239. LLM_KV_GENERAL_LICENSE,
  240. LLM_KV_GENERAL_SOURCE_URL,
  241. LLM_KV_GENERAL_SOURCE_HF_REPO,
  242. LLM_KV_VOCAB_SIZE,
  243. LLM_KV_CONTEXT_LENGTH,
  244. LLM_KV_EMBEDDING_LENGTH,
  245. LLM_KV_BLOCK_COUNT,
  246. LLM_KV_FEED_FORWARD_LENGTH,
  247. LLM_KV_USE_PARALLEL_RESIDUAL,
  248. LLM_KV_TENSOR_DATA_LAYOUT,
  249. LLM_KV_EXPERT_COUNT,
  250. LLM_KV_EXPERT_USED_COUNT,
  251. LLM_KV_POOLING_TYPE,
  252. LLM_KV_LOGIT_SCALE,
  253. LLM_KV_ATTENTION_HEAD_COUNT,
  254. LLM_KV_ATTENTION_HEAD_COUNT_KV,
  255. LLM_KV_ATTENTION_MAX_ALIBI_BIAS,
  256. LLM_KV_ATTENTION_CLAMP_KQV,
  257. LLM_KV_ATTENTION_KEY_LENGTH,
  258. LLM_KV_ATTENTION_VALUE_LENGTH,
  259. LLM_KV_ATTENTION_LAYERNORM_EPS,
  260. LLM_KV_ATTENTION_LAYERNORM_RMS_EPS,
  261. LLM_KV_ATTENTION_CAUSAL,
  262. LLM_KV_ROPE_DIMENSION_COUNT,
  263. LLM_KV_ROPE_FREQ_BASE,
  264. LLM_KV_ROPE_SCALE_LINEAR,
  265. LLM_KV_ROPE_SCALING_TYPE,
  266. LLM_KV_ROPE_SCALING_FACTOR,
  267. LLM_KV_ROPE_SCALING_ORIG_CTX_LEN,
  268. LLM_KV_ROPE_SCALING_FINETUNED,
  269. LLM_KV_SPLIT_NO,
  270. LLM_KV_SPLIT_COUNT,
  271. LLM_KV_SPLIT_TENSORS_COUNT,
  272. LLM_KV_SSM_INNER_SIZE,
  273. LLM_KV_SSM_CONV_KERNEL,
  274. LLM_KV_SSM_STATE_SIZE,
  275. LLM_KV_SSM_TIME_STEP_RANK,
  276. LLM_KV_TOKENIZER_MODEL,
  277. LLM_KV_TOKENIZER_LIST,
  278. LLM_KV_TOKENIZER_TOKEN_TYPE,
  279. LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT,
  280. LLM_KV_TOKENIZER_SCORES,
  281. LLM_KV_TOKENIZER_MERGES,
  282. LLM_KV_TOKENIZER_BOS_ID,
  283. LLM_KV_TOKENIZER_EOS_ID,
  284. LLM_KV_TOKENIZER_UNK_ID,
  285. LLM_KV_TOKENIZER_SEP_ID,
  286. LLM_KV_TOKENIZER_PAD_ID,
  287. LLM_KV_TOKENIZER_ADD_BOS,
  288. LLM_KV_TOKENIZER_ADD_EOS,
  289. LLM_KV_TOKENIZER_ADD_PREFIX,
  290. LLM_KV_TOKENIZER_HF_JSON,
  291. LLM_KV_TOKENIZER_RWKV,
  292. };
  293. static const std::map<llm_kv, const char *> LLM_KV_NAMES = {
  294. { LLM_KV_GENERAL_ARCHITECTURE, "general.architecture" },
  295. { LLM_KV_GENERAL_QUANTIZATION_VERSION, "general.quantization_version" },
  296. { LLM_KV_GENERAL_ALIGNMENT, "general.alignment" },
  297. { LLM_KV_GENERAL_NAME, "general.name" },
  298. { LLM_KV_GENERAL_AUTHOR, "general.author" },
  299. { LLM_KV_GENERAL_URL, "general.url" },
  300. { LLM_KV_GENERAL_DESCRIPTION, "general.description" },
  301. { LLM_KV_GENERAL_LICENSE, "general.license" },
  302. { LLM_KV_GENERAL_SOURCE_URL, "general.source.url" },
  303. { LLM_KV_GENERAL_SOURCE_HF_REPO, "general.source.huggingface.repository" },
  304. { LLM_KV_VOCAB_SIZE, "%s.vocab_size" },
  305. { LLM_KV_CONTEXT_LENGTH, "%s.context_length" },
  306. { LLM_KV_EMBEDDING_LENGTH, "%s.embedding_length" },
  307. { LLM_KV_BLOCK_COUNT, "%s.block_count" },
  308. { LLM_KV_FEED_FORWARD_LENGTH, "%s.feed_forward_length" },
  309. { LLM_KV_USE_PARALLEL_RESIDUAL, "%s.use_parallel_residual" },
  310. { LLM_KV_TENSOR_DATA_LAYOUT, "%s.tensor_data_layout" },
  311. { LLM_KV_EXPERT_COUNT, "%s.expert_count" },
  312. { LLM_KV_EXPERT_USED_COUNT, "%s.expert_used_count" },
  313. { LLM_KV_POOLING_TYPE , "%s.pooling_type" },
  314. { LLM_KV_LOGIT_SCALE, "%s.logit_scale" },
  315. { LLM_KV_ATTENTION_HEAD_COUNT, "%s.attention.head_count" },
  316. { LLM_KV_ATTENTION_HEAD_COUNT_KV, "%s.attention.head_count_kv" },
  317. { LLM_KV_ATTENTION_MAX_ALIBI_BIAS, "%s.attention.max_alibi_bias" },
  318. { LLM_KV_ATTENTION_CLAMP_KQV, "%s.attention.clamp_kqv" },
  319. { LLM_KV_ATTENTION_KEY_LENGTH, "%s.attention.key_length" },
  320. { LLM_KV_ATTENTION_VALUE_LENGTH, "%s.attention.value_length" },
  321. { LLM_KV_ATTENTION_LAYERNORM_EPS, "%s.attention.layer_norm_epsilon" },
  322. { LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, "%s.attention.layer_norm_rms_epsilon" },
  323. { LLM_KV_ATTENTION_CAUSAL, "%s.attention.causal" },
  324. { LLM_KV_ROPE_DIMENSION_COUNT, "%s.rope.dimension_count" },
  325. { LLM_KV_ROPE_FREQ_BASE, "%s.rope.freq_base" },
  326. { LLM_KV_ROPE_SCALE_LINEAR, "%s.rope.scale_linear" },
  327. { LLM_KV_ROPE_SCALING_TYPE, "%s.rope.scaling.type" },
  328. { LLM_KV_ROPE_SCALING_FACTOR, "%s.rope.scaling.factor" },
  329. { LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, "%s.rope.scaling.original_context_length" },
  330. { LLM_KV_ROPE_SCALING_FINETUNED, "%s.rope.scaling.finetuned" },
  331. { LLM_KV_SPLIT_NO, "split.no" },
  332. { LLM_KV_SPLIT_COUNT, "split.count" },
  333. { LLM_KV_SPLIT_TENSORS_COUNT, "split.tensors.count" },
  334. { LLM_KV_SSM_CONV_KERNEL, "%s.ssm.conv_kernel" },
  335. { LLM_KV_SSM_INNER_SIZE, "%s.ssm.inner_size" },
  336. { LLM_KV_SSM_STATE_SIZE, "%s.ssm.state_size" },
  337. { LLM_KV_SSM_TIME_STEP_RANK, "%s.ssm.time_step_rank" },
  338. { LLM_KV_TOKENIZER_MODEL, "tokenizer.ggml.model" },
  339. { LLM_KV_TOKENIZER_LIST, "tokenizer.ggml.tokens" },
  340. { LLM_KV_TOKENIZER_TOKEN_TYPE, "tokenizer.ggml.token_type" },
  341. { LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, "tokenizer.ggml.token_type_count" },
  342. { LLM_KV_TOKENIZER_SCORES, "tokenizer.ggml.scores" },
  343. { LLM_KV_TOKENIZER_MERGES, "tokenizer.ggml.merges" },
  344. { LLM_KV_TOKENIZER_BOS_ID, "tokenizer.ggml.bos_token_id" },
  345. { LLM_KV_TOKENIZER_EOS_ID, "tokenizer.ggml.eos_token_id" },
  346. { LLM_KV_TOKENIZER_UNK_ID, "tokenizer.ggml.unknown_token_id" },
  347. { LLM_KV_TOKENIZER_SEP_ID, "tokenizer.ggml.seperator_token_id" },
  348. { LLM_KV_TOKENIZER_PAD_ID, "tokenizer.ggml.padding_token_id" },
  349. { LLM_KV_TOKENIZER_ADD_BOS, "tokenizer.ggml.add_bos_token" },
  350. { LLM_KV_TOKENIZER_ADD_EOS, "tokenizer.ggml.add_eos_token" },
  351. { LLM_KV_TOKENIZER_ADD_PREFIX, "tokenizer.ggml.add_space_prefix" },
  352. { LLM_KV_TOKENIZER_HF_JSON, "tokenizer.huggingface.json" },
  353. { LLM_KV_TOKENIZER_RWKV, "tokenizer.rwkv.world" },
  354. };
  355. struct LLM_KV {
  356. LLM_KV(llm_arch arch) : arch(arch) {}
  357. llm_arch arch;
  358. std::string operator()(llm_kv kv) const {
  359. return ::format(LLM_KV_NAMES.at(kv), LLM_ARCH_NAMES.at(arch));
  360. }
  361. };
  362. enum llm_tensor {
  363. LLM_TENSOR_TOKEN_EMBD,
  364. LLM_TENSOR_TOKEN_EMBD_NORM,
  365. LLM_TENSOR_TOKEN_TYPES,
  366. LLM_TENSOR_POS_EMBD,
  367. LLM_TENSOR_OUTPUT,
  368. LLM_TENSOR_OUTPUT_NORM,
  369. LLM_TENSOR_ROPE_FREQS,
  370. LLM_TENSOR_ATTN_Q,
  371. LLM_TENSOR_ATTN_K,
  372. LLM_TENSOR_ATTN_V,
  373. LLM_TENSOR_ATTN_QKV,
  374. LLM_TENSOR_ATTN_OUT,
  375. LLM_TENSOR_ATTN_NORM,
  376. LLM_TENSOR_ATTN_NORM_2,
  377. LLM_TENSOR_ATTN_OUT_NORM,
  378. LLM_TENSOR_ATTN_ROT_EMBD,
  379. LLM_TENSOR_FFN_GATE_INP,
  380. LLM_TENSOR_FFN_NORM,
  381. LLM_TENSOR_FFN_GATE,
  382. LLM_TENSOR_FFN_DOWN,
  383. LLM_TENSOR_FFN_UP,
  384. LLM_TENSOR_FFN_ACT,
  385. LLM_TENSOR_FFN_DOWN_EXP,
  386. LLM_TENSOR_FFN_GATE_EXP,
  387. LLM_TENSOR_FFN_UP_EXP,
  388. LLM_TENSOR_ATTN_Q_NORM,
  389. LLM_TENSOR_ATTN_K_NORM,
  390. LLM_TENSOR_LAYER_OUT_NORM,
  391. LLM_TENSOR_SSM_IN,
  392. LLM_TENSOR_SSM_CONV1D,
  393. LLM_TENSOR_SSM_X,
  394. LLM_TENSOR_SSM_DT,
  395. LLM_TENSOR_SSM_A,
  396. LLM_TENSOR_SSM_D,
  397. LLM_TENSOR_SSM_OUT,
  398. };
  399. static const std::map<llm_arch, std::map<llm_tensor, std::string>> LLM_TENSOR_NAMES = {
  400. {
  401. LLM_ARCH_LLAMA,
  402. {
  403. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  404. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  405. { LLM_TENSOR_OUTPUT, "output" },
  406. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  407. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  408. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  409. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  410. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  411. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  412. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  413. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  414. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  415. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  416. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  417. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  418. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  419. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  420. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  421. },
  422. },
  423. {
  424. LLM_ARCH_BAICHUAN,
  425. {
  426. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  427. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  428. { LLM_TENSOR_OUTPUT, "output" },
  429. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  430. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  431. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  432. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  433. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  434. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  435. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  436. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  437. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  438. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  439. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  440. },
  441. },
  442. {
  443. LLM_ARCH_FALCON,
  444. {
  445. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  446. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  447. { LLM_TENSOR_OUTPUT, "output" },
  448. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  449. { LLM_TENSOR_ATTN_NORM_2, "blk.%d.attn_norm_2" },
  450. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  451. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  452. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  453. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  454. },
  455. },
  456. {
  457. LLM_ARCH_GROK,
  458. {
  459. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  460. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  461. { LLM_TENSOR_OUTPUT, "output" },
  462. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  463. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  464. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  465. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  466. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  467. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  468. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  469. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  470. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  471. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  472. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  473. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  474. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  475. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  476. },
  477. },
  478. {
  479. LLM_ARCH_GPT2,
  480. {
  481. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  482. { LLM_TENSOR_POS_EMBD, "position_embd" },
  483. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  484. { LLM_TENSOR_OUTPUT, "output" },
  485. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  486. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  487. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  488. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  489. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  490. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  491. },
  492. },
  493. {
  494. LLM_ARCH_GPTJ,
  495. {
  496. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  497. },
  498. },
  499. {
  500. LLM_ARCH_GPTNEOX,
  501. {
  502. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  503. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  504. { LLM_TENSOR_OUTPUT, "output" },
  505. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  506. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  507. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  508. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  509. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  510. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  511. },
  512. },
  513. {
  514. LLM_ARCH_PERSIMMON,
  515. {
  516. { LLM_TENSOR_TOKEN_EMBD, "token_embd"},
  517. { LLM_TENSOR_OUTPUT_NORM, "output_norm"},
  518. { LLM_TENSOR_OUTPUT, "output"},
  519. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm"},
  520. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv"},
  521. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output"},
  522. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm"},
  523. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm"},
  524. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm"},
  525. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down"},
  526. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up"},
  527. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd"},
  528. },
  529. },
  530. {
  531. LLM_ARCH_MPT,
  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_FFN_NORM, "blk.%d.ffn_norm" },
  538. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  539. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  540. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  541. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  542. { LLM_TENSOR_FFN_ACT, "blk.%d.ffn.act" },
  543. },
  544. },
  545. {
  546. LLM_ARCH_STARCODER,
  547. {
  548. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  549. { LLM_TENSOR_POS_EMBD, "position_embd" },
  550. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  551. { LLM_TENSOR_OUTPUT, "output" },
  552. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  553. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  554. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  555. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  556. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  557. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  558. },
  559. },
  560. {
  561. LLM_ARCH_REFACT,
  562. {
  563. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  564. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  565. { LLM_TENSOR_OUTPUT, "output" },
  566. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  567. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  568. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  569. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  570. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  571. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  572. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  573. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  574. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  575. },
  576. },
  577. {
  578. LLM_ARCH_BERT,
  579. {
  580. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  581. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  582. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  583. { LLM_TENSOR_POS_EMBD, "position_embd" },
  584. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  585. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  586. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  587. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  588. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  589. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  590. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  591. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  592. },
  593. },
  594. {
  595. LLM_ARCH_NOMIC_BERT,
  596. {
  597. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  598. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  599. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  600. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  601. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  602. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  603. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  604. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  605. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  606. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  607. },
  608. },
  609. {
  610. LLM_ARCH_BLOOM,
  611. {
  612. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  613. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  614. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  615. { LLM_TENSOR_OUTPUT, "output" },
  616. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  617. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  618. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  619. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  620. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  621. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  622. },
  623. },
  624. {
  625. LLM_ARCH_STABLELM,
  626. {
  627. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  628. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  629. { LLM_TENSOR_OUTPUT, "output" },
  630. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  631. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  632. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  633. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  634. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  635. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  636. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  637. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  638. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  639. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  640. },
  641. },
  642. {
  643. LLM_ARCH_QWEN,
  644. {
  645. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  646. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  647. { LLM_TENSOR_OUTPUT, "output" },
  648. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  649. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  650. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  651. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  652. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  653. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  654. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  655. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  656. },
  657. },
  658. {
  659. LLM_ARCH_QWEN2,
  660. {
  661. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  662. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  663. { LLM_TENSOR_OUTPUT, "output" },
  664. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  665. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  666. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  667. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  668. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  669. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  670. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  671. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  672. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  673. },
  674. },
  675. {
  676. LLM_ARCH_PHI2,
  677. {
  678. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  679. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  680. { LLM_TENSOR_OUTPUT, "output" },
  681. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  682. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  683. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  684. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  685. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  686. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  687. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  688. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  689. },
  690. },
  691. {
  692. LLM_ARCH_PLAMO,
  693. {
  694. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  695. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  696. { LLM_TENSOR_OUTPUT, "output" },
  697. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  698. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  699. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  700. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  701. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  702. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  703. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  704. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  705. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  706. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  707. },
  708. },
  709. {
  710. LLM_ARCH_CODESHELL,
  711. {
  712. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  713. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  714. { LLM_TENSOR_OUTPUT, "output" },
  715. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  716. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  717. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  718. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  719. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  720. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  721. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  722. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  723. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  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_ORION,
  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_OUT, "blk.%d.attn_output" },
  741. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  742. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  743. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  744. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  745. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  746. },
  747. },
  748. {
  749. LLM_ARCH_INTERNLM2,
  750. {
  751. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  752. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  753. { LLM_TENSOR_OUTPUT, "output" },
  754. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  755. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  756. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  757. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  758. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  759. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  760. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  761. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  762. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  763. },
  764. },
  765. {
  766. LLM_ARCH_MINICPM,
  767. {
  768. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  769. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  770. { LLM_TENSOR_OUTPUT, "output" },
  771. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  772. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  773. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  774. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  775. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  776. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  777. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  778. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  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. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  784. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  785. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  786. },
  787. },
  788. {
  789. LLM_ARCH_GEMMA,
  790. {
  791. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  792. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  793. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  794. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  795. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  796. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  797. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  798. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  799. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  800. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  801. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  802. },
  803. },
  804. {
  805. LLM_ARCH_STARCODER2,
  806. {
  807. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  808. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  809. { LLM_TENSOR_OUTPUT, "output" },
  810. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  811. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  812. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  813. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  814. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  815. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  816. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  817. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  818. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  819. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  820. },
  821. },
  822. {
  823. LLM_ARCH_MAMBA,
  824. {
  825. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  826. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  827. { LLM_TENSOR_OUTPUT, "output" },
  828. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  829. { LLM_TENSOR_SSM_IN, "blk.%d.ssm_in" },
  830. { LLM_TENSOR_SSM_CONV1D, "blk.%d.ssm_conv1d" },
  831. { LLM_TENSOR_SSM_X, "blk.%d.ssm_x" },
  832. { LLM_TENSOR_SSM_DT, "blk.%d.ssm_dt" },
  833. { LLM_TENSOR_SSM_A, "blk.%d.ssm_a" },
  834. { LLM_TENSOR_SSM_D, "blk.%d.ssm_d" },
  835. { LLM_TENSOR_SSM_OUT, "blk.%d.ssm_out" },
  836. },
  837. },
  838. {
  839. LLM_ARCH_XVERSE,
  840. {
  841. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  842. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  843. { LLM_TENSOR_OUTPUT, "output" },
  844. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  845. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  846. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  847. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  848. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  849. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  850. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  851. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  852. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  853. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  854. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  855. },
  856. },
  857. {
  858. LLM_ARCH_COMMAND_R,
  859. {
  860. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  861. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  862. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  863. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  864. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  865. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  866. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  867. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  868. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  869. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  870. },
  871. },
  872. {
  873. LLM_ARCH_UNKNOWN,
  874. {
  875. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  876. },
  877. },
  878. };
  879. static llm_arch llm_arch_from_string(const std::string & name) {
  880. for (const auto & kv : LLM_ARCH_NAMES) { // NOLINT
  881. if (kv.second == name) {
  882. return kv.first;
  883. }
  884. }
  885. return LLM_ARCH_UNKNOWN;
  886. }
  887. // helper to handle gguf constants
  888. // usage:
  889. //
  890. // const auto tn = LLM_TN(LLM_ARCH_LLAMA);
  891. //
  892. // std::string name = tn(LLM_TENSOR_OUTPUT); -> "output"
  893. // std::string name = tn(LLM_TENSOR_TOKEN_EMBD, "bias"); -> "token_embd.bias"
  894. // std::string name = tn(LLM_TENSOR_ATTN_NORM, "weight", 3); -> "blk.3.attn_norm.weight"
  895. //
  896. struct LLM_TN {
  897. LLM_TN(llm_arch arch) : arch(arch) {}
  898. llm_arch arch;
  899. std::string operator()(llm_tensor tensor) const {
  900. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  901. return "__missing__";
  902. }
  903. return LLM_TENSOR_NAMES.at(arch).at(tensor);
  904. }
  905. std::string operator()(llm_tensor tensor, const std::string & suffix) const {
  906. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  907. return "__missing__";
  908. }
  909. return LLM_TENSOR_NAMES.at(arch).at(tensor) + "." + suffix;
  910. }
  911. std::string operator()(llm_tensor tensor, int bid) const {
  912. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  913. return "__missing__";
  914. }
  915. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid);
  916. }
  917. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid) const {
  918. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  919. return "__missing__";
  920. }
  921. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid) + "." + suffix;
  922. }
  923. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid, int xid) const {
  924. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  925. return "__missing__";
  926. }
  927. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid, xid) + "." + suffix;
  928. }
  929. };
  930. //
  931. // gguf helpers
  932. //
  933. static const std::map<llama_rope_scaling_type, const char *> LLAMA_ROPE_SCALING_TYPES = {
  934. { LLAMA_ROPE_SCALING_TYPE_NONE, "none" },
  935. { LLAMA_ROPE_SCALING_TYPE_LINEAR, "linear" },
  936. { LLAMA_ROPE_SCALING_TYPE_YARN, "yarn" },
  937. };
  938. static llama_rope_scaling_type llama_rope_scaling_type_from_string(const std::string & name) {
  939. for (const auto & kv : LLAMA_ROPE_SCALING_TYPES) {
  940. if (kv.second == name) {
  941. return (llama_rope_scaling_type) kv.first;
  942. }
  943. }
  944. return LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED;
  945. }
  946. static std::string gguf_data_to_str(enum gguf_type type, const void * data, int i) {
  947. switch (type) {
  948. case GGUF_TYPE_UINT8: return std::to_string(((const uint8_t *)data)[i]);
  949. case GGUF_TYPE_INT8: return std::to_string(((const int8_t *)data)[i]);
  950. case GGUF_TYPE_UINT16: return std::to_string(((const uint16_t *)data)[i]);
  951. case GGUF_TYPE_INT16: return std::to_string(((const int16_t *)data)[i]);
  952. case GGUF_TYPE_UINT32: return std::to_string(((const uint32_t *)data)[i]);
  953. case GGUF_TYPE_INT32: return std::to_string(((const int32_t *)data)[i]);
  954. case GGUF_TYPE_UINT64: return std::to_string(((const uint64_t *)data)[i]);
  955. case GGUF_TYPE_INT64: return std::to_string(((const int64_t *)data)[i]);
  956. case GGUF_TYPE_FLOAT32: return std::to_string(((const float *)data)[i]);
  957. case GGUF_TYPE_FLOAT64: return std::to_string(((const double *)data)[i]);
  958. case GGUF_TYPE_BOOL: return ((const bool *)data)[i] ? "true" : "false";
  959. default: return format("unknown type %d", type);
  960. }
  961. }
  962. static std::string gguf_kv_to_str(const struct gguf_context * ctx_gguf, int i) {
  963. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  964. switch (type) {
  965. case GGUF_TYPE_STRING:
  966. return gguf_get_val_str(ctx_gguf, i);
  967. case GGUF_TYPE_ARRAY:
  968. {
  969. const enum gguf_type arr_type = gguf_get_arr_type(ctx_gguf, i);
  970. int arr_n = gguf_get_arr_n(ctx_gguf, i);
  971. const void * data = gguf_get_arr_data(ctx_gguf, i);
  972. std::stringstream ss;
  973. ss << "[";
  974. for (int j = 0; j < arr_n; j++) {
  975. if (arr_type == GGUF_TYPE_STRING) {
  976. std::string val = gguf_get_arr_str(ctx_gguf, i, j);
  977. // escape quotes
  978. replace_all(val, "\\", "\\\\");
  979. replace_all(val, "\"", "\\\"");
  980. ss << '"' << val << '"';
  981. } else if (arr_type == GGUF_TYPE_ARRAY) {
  982. ss << "???";
  983. } else {
  984. ss << gguf_data_to_str(arr_type, data, j);
  985. }
  986. if (j < arr_n - 1) {
  987. ss << ", ";
  988. }
  989. }
  990. ss << "]";
  991. return ss.str();
  992. }
  993. default:
  994. return gguf_data_to_str(type, gguf_get_val_data(ctx_gguf, i), 0);
  995. }
  996. }
  997. //
  998. // llama helpers
  999. //
  1000. #if defined(_WIN32)
  1001. static std::string llama_format_win_err(DWORD err) {
  1002. LPSTR buf;
  1003. size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  1004. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, NULL);
  1005. if (!size) {
  1006. return "FormatMessageA failed";
  1007. }
  1008. std::string ret(buf, size);
  1009. LocalFree(buf);
  1010. return ret;
  1011. }
  1012. #endif
  1013. template <typename T>
  1014. struct no_init {
  1015. T value;
  1016. no_init() { /* do nothing */ }
  1017. };
  1018. struct llama_file {
  1019. // use FILE * so we don't have to re-open the file to mmap
  1020. FILE * fp;
  1021. size_t size;
  1022. llama_file(const char * fname, const char * mode) {
  1023. fp = ggml_fopen(fname, mode);
  1024. if (fp == NULL) {
  1025. throw std::runtime_error(format("failed to open %s: %s", fname, strerror(errno)));
  1026. }
  1027. seek(0, SEEK_END);
  1028. size = tell();
  1029. seek(0, SEEK_SET);
  1030. }
  1031. size_t tell() const {
  1032. #ifdef _WIN32
  1033. __int64 ret = _ftelli64(fp);
  1034. #else
  1035. long ret = std::ftell(fp);
  1036. #endif
  1037. GGML_ASSERT(ret != -1); // this really shouldn't fail
  1038. return (size_t) ret;
  1039. }
  1040. void seek(size_t offset, int whence) const {
  1041. #ifdef _WIN32
  1042. int ret = _fseeki64(fp, (__int64) offset, whence);
  1043. #else
  1044. int ret = std::fseek(fp, (long) offset, whence);
  1045. #endif
  1046. GGML_ASSERT(ret == 0); // same
  1047. }
  1048. void read_raw(void * ptr, size_t len) const {
  1049. if (len == 0) {
  1050. return;
  1051. }
  1052. errno = 0;
  1053. std::size_t ret = std::fread(ptr, len, 1, fp);
  1054. if (ferror(fp)) {
  1055. throw std::runtime_error(format("read error: %s", strerror(errno)));
  1056. }
  1057. if (ret != 1) {
  1058. throw std::runtime_error("unexpectedly reached end of file");
  1059. }
  1060. }
  1061. uint32_t read_u32() const {
  1062. uint32_t ret;
  1063. read_raw(&ret, sizeof(ret));
  1064. return ret;
  1065. }
  1066. void write_raw(const void * ptr, size_t len) const {
  1067. if (len == 0) {
  1068. return;
  1069. }
  1070. errno = 0;
  1071. size_t ret = std::fwrite(ptr, len, 1, fp);
  1072. if (ret != 1) {
  1073. throw std::runtime_error(format("write error: %s", strerror(errno)));
  1074. }
  1075. }
  1076. void write_u32(std::uint32_t val) const {
  1077. write_raw(&val, sizeof(val));
  1078. }
  1079. ~llama_file() {
  1080. if (fp) {
  1081. std::fclose(fp);
  1082. }
  1083. }
  1084. };
  1085. using llama_files = std::vector<std::unique_ptr<llama_file>>;
  1086. struct llama_mmap {
  1087. void * addr;
  1088. size_t size;
  1089. llama_mmap(const llama_mmap &) = delete;
  1090. #ifdef _POSIX_MAPPED_FILES
  1091. static constexpr bool SUPPORTED = true;
  1092. // list of mapped fragments (first_offset, last_offset)
  1093. std::vector<std::pair<size_t, size_t>> mapped_fragments;
  1094. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1 /* -1 = max value */, bool numa = false) {
  1095. size = file->size;
  1096. int fd = fileno(file->fp);
  1097. int flags = MAP_SHARED;
  1098. // prefetch/readahead impairs performance on NUMA systems
  1099. if (numa) { prefetch = 0; }
  1100. #ifdef __linux__
  1101. // advise the kernel to read the file sequentially (increases readahead)
  1102. if (posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL)) {
  1103. LLAMA_LOG_WARN("warning: posix_fadvise(.., POSIX_FADV_SEQUENTIAL) failed: %s\n",
  1104. strerror(errno));
  1105. }
  1106. if (prefetch) { flags |= MAP_POPULATE; }
  1107. #endif
  1108. addr = mmap(NULL, file->size, PROT_READ, flags, fd, 0);
  1109. if (addr == MAP_FAILED) { // NOLINT
  1110. throw std::runtime_error(format("mmap failed: %s", strerror(errno)));
  1111. }
  1112. if (prefetch > 0) {
  1113. // advise the kernel to preload the mapped memory
  1114. if (posix_madvise(addr, std::min(file->size, prefetch), POSIX_MADV_WILLNEED)) {
  1115. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_WILLNEED) failed: %s\n",
  1116. strerror(errno));
  1117. }
  1118. }
  1119. if (numa) {
  1120. // advise the kernel not to use readahead
  1121. // (because the next page might not belong on the same node)
  1122. if (posix_madvise(addr, file->size, POSIX_MADV_RANDOM)) {
  1123. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_RANDOM) failed: %s\n",
  1124. strerror(errno));
  1125. }
  1126. }
  1127. // initialize list of mapped_fragments
  1128. mapped_fragments.emplace_back(0, file->size);
  1129. }
  1130. static void align_range(size_t * first, size_t * last, size_t page_size) {
  1131. // align first to the next page
  1132. size_t offset_in_page = *first & (page_size - 1);
  1133. size_t offset_to_page = offset_in_page == 0 ? 0 : page_size - offset_in_page;
  1134. *first += offset_to_page;
  1135. // align last to the previous page
  1136. *last = *last & ~(page_size - 1);
  1137. if (*last <= *first) {
  1138. *last = *first;
  1139. }
  1140. }
  1141. // partially unmap the file in the range [first, last)
  1142. void unmap_fragment(size_t first, size_t last) {
  1143. // note: this function must not be called multiple times with overlapping ranges
  1144. // otherwise, there is a risk of invalidating addresses that have been repurposed for other mappings
  1145. int page_size = sysconf(_SC_PAGESIZE);
  1146. align_range(&first, &last, page_size);
  1147. size_t len = last - first;
  1148. if (len == 0) {
  1149. return;
  1150. }
  1151. GGML_ASSERT(first % page_size == 0);
  1152. GGML_ASSERT(last % page_size == 0);
  1153. GGML_ASSERT(last > first);
  1154. void * next_page_start = (uint8_t *) addr + first;
  1155. // unmap the range
  1156. if (munmap(next_page_start, len)) {
  1157. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  1158. }
  1159. // update the list of mapped fragments to avoid unmapping the same range again in the destructor
  1160. std::vector<std::pair<size_t, size_t>> new_mapped_fragments;
  1161. for (const auto & frag : mapped_fragments) {
  1162. if (frag.first < first && frag.second > last) {
  1163. // the range is in the middle of the fragment, split it
  1164. new_mapped_fragments.emplace_back(frag.first, first);
  1165. new_mapped_fragments.emplace_back(last, frag.second);
  1166. } else if (frag.first < first && frag.second > first) {
  1167. // the range starts in the middle of the fragment
  1168. new_mapped_fragments.emplace_back(frag.first, first);
  1169. } else if (frag.first < last && frag.second > last) {
  1170. // the range ends in the middle of the fragment
  1171. new_mapped_fragments.emplace_back(last, frag.second);
  1172. } else if (frag.first >= first && frag.second <= last) {
  1173. // the range covers the entire fragment
  1174. } else {
  1175. // the range is outside the fragment
  1176. new_mapped_fragments.push_back(frag);
  1177. }
  1178. }
  1179. mapped_fragments = std::move(new_mapped_fragments);
  1180. }
  1181. ~llama_mmap() {
  1182. for (const auto & frag : mapped_fragments) {
  1183. if (munmap((char *) addr + frag.first, frag.second - frag.first)) {
  1184. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  1185. }
  1186. }
  1187. }
  1188. #elif defined(_WIN32)
  1189. static constexpr bool SUPPORTED = true;
  1190. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1, bool numa = false) {
  1191. GGML_UNUSED(numa);
  1192. size = file->size;
  1193. HANDLE hFile = (HANDLE) _get_osfhandle(_fileno(file->fp));
  1194. HANDLE hMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
  1195. if (hMapping == NULL) {
  1196. DWORD error = GetLastError();
  1197. throw std::runtime_error(format("CreateFileMappingA failed: %s", llama_format_win_err(error).c_str()));
  1198. }
  1199. addr = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
  1200. DWORD error = GetLastError();
  1201. CloseHandle(hMapping);
  1202. if (addr == NULL) {
  1203. throw std::runtime_error(format("MapViewOfFile failed: %s", llama_format_win_err(error).c_str()));
  1204. }
  1205. if (prefetch > 0) {
  1206. #if _WIN32_WINNT >= 0x602
  1207. // PrefetchVirtualMemory is only present on Windows 8 and above, so we dynamically load it
  1208. BOOL (WINAPI *pPrefetchVirtualMemory) (HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG);
  1209. HMODULE hKernel32 = GetModuleHandleW(L"kernel32.dll");
  1210. // may fail on pre-Windows 8 systems
  1211. pPrefetchVirtualMemory = reinterpret_cast<decltype(pPrefetchVirtualMemory)> (GetProcAddress(hKernel32, "PrefetchVirtualMemory"));
  1212. if (pPrefetchVirtualMemory) {
  1213. // advise the kernel to preload the mapped memory
  1214. WIN32_MEMORY_RANGE_ENTRY range;
  1215. range.VirtualAddress = addr;
  1216. range.NumberOfBytes = (SIZE_T) std::min(size, prefetch);
  1217. if (!pPrefetchVirtualMemory(GetCurrentProcess(), 1, &range, 0)) {
  1218. LLAMA_LOG_WARN("warning: PrefetchVirtualMemory failed: %s\n",
  1219. llama_format_win_err(GetLastError()).c_str());
  1220. }
  1221. }
  1222. #else
  1223. throw std::runtime_error("PrefetchVirtualMemory unavailable");
  1224. #endif
  1225. }
  1226. }
  1227. void unmap_fragment(size_t first, size_t last) {
  1228. // not supported
  1229. GGML_UNUSED(first);
  1230. GGML_UNUSED(last);
  1231. }
  1232. ~llama_mmap() {
  1233. if (!UnmapViewOfFile(addr)) {
  1234. LLAMA_LOG_WARN("warning: UnmapViewOfFile failed: %s\n",
  1235. llama_format_win_err(GetLastError()).c_str());
  1236. }
  1237. }
  1238. #else
  1239. static constexpr bool SUPPORTED = false;
  1240. llama_mmap(struct llama_file * file, size_t prefetch = -1, bool numa = false) {
  1241. GGML_UNUSED(file);
  1242. GGML_UNUSED(prefetch);
  1243. GGML_UNUSED(numa);
  1244. throw std::runtime_error("mmap not supported");
  1245. }
  1246. void unmap_fragment(size_t first, size_t last) {
  1247. GGML_UNUSED(first);
  1248. GGML_UNUSED(last);
  1249. throw std::runtime_error("mmap not supported");
  1250. }
  1251. #endif
  1252. };
  1253. using llama_mmaps = std::vector<std::unique_ptr<llama_mmap>>;
  1254. // Represents some region of memory being locked using mlock or VirtualLock;
  1255. // will automatically unlock on destruction.
  1256. struct llama_mlock {
  1257. void * addr = NULL;
  1258. size_t size = 0;
  1259. bool failed_already = false;
  1260. llama_mlock() {}
  1261. llama_mlock(const llama_mlock &) = delete;
  1262. ~llama_mlock() {
  1263. if (size) {
  1264. raw_unlock(addr, size);
  1265. }
  1266. }
  1267. void init(void * ptr) {
  1268. GGML_ASSERT(addr == NULL && size == 0); // NOLINT
  1269. addr = ptr;
  1270. }
  1271. void grow_to(size_t target_size) {
  1272. GGML_ASSERT(addr);
  1273. if (failed_already) {
  1274. return;
  1275. }
  1276. size_t granularity = lock_granularity();
  1277. target_size = (target_size + granularity - 1) & ~(granularity - 1);
  1278. if (target_size > size) {
  1279. if (raw_lock((uint8_t *) addr + size, target_size - size)) {
  1280. size = target_size;
  1281. } else {
  1282. failed_already = true;
  1283. }
  1284. }
  1285. }
  1286. #ifdef _POSIX_MEMLOCK_RANGE
  1287. static constexpr bool SUPPORTED = true;
  1288. static size_t lock_granularity() {
  1289. return (size_t) sysconf(_SC_PAGESIZE);
  1290. }
  1291. #ifdef __APPLE__
  1292. #define MLOCK_SUGGESTION \
  1293. "Try increasing the sysctl values 'vm.user_wire_limit' and 'vm.global_user_wire_limit' and/or " \
  1294. "decreasing 'vm.global_no_user_wire_amount'. Also try increasing RLIMIT_MEMLOCK (ulimit -l).\n"
  1295. #else
  1296. #define MLOCK_SUGGESTION \
  1297. "Try increasing RLIMIT_MEMLOCK ('ulimit -l' as root).\n"
  1298. #endif
  1299. bool raw_lock(const void * addr, size_t size) const {
  1300. if (!mlock(addr, size)) {
  1301. return true;
  1302. }
  1303. char* errmsg = std::strerror(errno);
  1304. bool suggest = (errno == ENOMEM);
  1305. // Check if the resource limit is fine after all
  1306. struct rlimit lock_limit;
  1307. if (suggest && getrlimit(RLIMIT_MEMLOCK, &lock_limit)) {
  1308. suggest = false;
  1309. }
  1310. if (suggest && (lock_limit.rlim_max > lock_limit.rlim_cur + size)) {
  1311. suggest = false;
  1312. }
  1313. LLAMA_LOG_WARN("warning: failed to mlock %zu-byte buffer (after previously locking %zu bytes): %s\n%s",
  1314. size, this->size, errmsg, suggest ? MLOCK_SUGGESTION : "");
  1315. return false;
  1316. }
  1317. #undef MLOCK_SUGGESTION
  1318. static void raw_unlock(void * addr, size_t size) {
  1319. if (munlock(addr, size)) {
  1320. LLAMA_LOG_WARN("warning: failed to munlock buffer: %s\n", std::strerror(errno));
  1321. }
  1322. }
  1323. #elif defined(_WIN32)
  1324. static constexpr bool SUPPORTED = true;
  1325. static size_t lock_granularity() {
  1326. SYSTEM_INFO si;
  1327. GetSystemInfo(&si);
  1328. return (size_t) si.dwPageSize;
  1329. }
  1330. bool raw_lock(void * ptr, size_t len) const {
  1331. for (int tries = 1; ; tries++) {
  1332. if (VirtualLock(ptr, len)) {
  1333. return true;
  1334. }
  1335. if (tries == 2) {
  1336. LLAMA_LOG_WARN("warning: failed to VirtualLock %zu-byte buffer (after previously locking %zu bytes): %s\n",
  1337. len, size, llama_format_win_err(GetLastError()).c_str());
  1338. return false;
  1339. }
  1340. // It failed but this was only the first try; increase the working
  1341. // set size and try again.
  1342. SIZE_T min_ws_size, max_ws_size;
  1343. if (!GetProcessWorkingSetSize(GetCurrentProcess(), &min_ws_size, &max_ws_size)) {
  1344. LLAMA_LOG_WARN("warning: GetProcessWorkingSetSize failed: %s\n",
  1345. llama_format_win_err(GetLastError()).c_str());
  1346. return false;
  1347. }
  1348. // Per MSDN: "The maximum number of pages that a process can lock
  1349. // is equal to the number of pages in its minimum working set minus
  1350. // a small overhead."
  1351. // Hopefully a megabyte is enough overhead:
  1352. size_t increment = len + 1048576;
  1353. // The minimum must be <= the maximum, so we need to increase both:
  1354. min_ws_size += increment;
  1355. max_ws_size += increment;
  1356. if (!SetProcessWorkingSetSize(GetCurrentProcess(), min_ws_size, max_ws_size)) {
  1357. LLAMA_LOG_WARN("warning: SetProcessWorkingSetSize failed: %s\n",
  1358. llama_format_win_err(GetLastError()).c_str());
  1359. return false;
  1360. }
  1361. }
  1362. }
  1363. static void raw_unlock(void * ptr, size_t len) {
  1364. if (!VirtualUnlock(ptr, len)) {
  1365. LLAMA_LOG_WARN("warning: failed to VirtualUnlock buffer: %s\n",
  1366. llama_format_win_err(GetLastError()).c_str());
  1367. }
  1368. }
  1369. #else
  1370. static constexpr bool SUPPORTED = false;
  1371. static size_t lock_granularity() {
  1372. return (size_t) 65536;
  1373. }
  1374. bool raw_lock(const void * addr, size_t len) const {
  1375. LLAMA_LOG_WARN("warning: mlock not supported on this system\n");
  1376. return false;
  1377. }
  1378. static void raw_unlock(const void * addr, size_t len) {}
  1379. #endif
  1380. };
  1381. using llama_mlocks = std::vector<std::unique_ptr<llama_mlock>>;
  1382. static std::string llama_token_to_piece(const struct llama_context * ctx, llama_token token) {
  1383. std::vector<char> result(8, 0);
  1384. const int n_tokens = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1385. if (n_tokens < 0) {
  1386. result.resize(-n_tokens);
  1387. int check = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1388. GGML_ASSERT(check == -n_tokens);
  1389. }
  1390. else {
  1391. result.resize(n_tokens);
  1392. }
  1393. return std::string(result.data(), result.size());
  1394. }
  1395. static ggml_backend_buffer_type_t llama_default_buffer_type_cpu(bool host_buffer) {
  1396. ggml_backend_buffer_type_t buft = nullptr;
  1397. #if defined(GGML_USE_CUDA)
  1398. // host buffers should only be used when data is expected to be copied to/from the GPU
  1399. if (host_buffer) {
  1400. buft = ggml_backend_cuda_host_buffer_type();
  1401. }
  1402. #elif defined(GGML_USE_SYCL)
  1403. if (host_buffer) {
  1404. buft = ggml_backend_sycl_host_buffer_type();
  1405. }
  1406. #elif defined(GGML_USE_CPU_HBM)
  1407. buft = ggml_backend_cpu_hbm_buffer_type();
  1408. #elif defined(GGML_USE_VULKAN)
  1409. if (host_buffer) {
  1410. buft = ggml_backend_vk_host_buffer_type();
  1411. }
  1412. #endif
  1413. if (buft == nullptr) {
  1414. buft = ggml_backend_cpu_buffer_type();
  1415. }
  1416. return buft;
  1417. GGML_UNUSED(host_buffer);
  1418. }
  1419. static ggml_backend_buffer_type_t llama_default_buffer_type_offload(int gpu) {
  1420. ggml_backend_buffer_type_t buft = nullptr;
  1421. #ifdef GGML_USE_METAL
  1422. buft = ggml_backend_metal_buffer_type();
  1423. #elif defined(GGML_USE_CUDA)
  1424. buft = ggml_backend_cuda_buffer_type(gpu);
  1425. #elif defined(GGML_USE_VULKAN)
  1426. buft = ggml_backend_vk_buffer_type(gpu);
  1427. #elif defined(GGML_USE_SYCL)
  1428. buft = ggml_backend_sycl_buffer_type(gpu);
  1429. #elif defined(GGML_USE_CLBLAST)
  1430. buft = ggml_backend_opencl_buffer_type();
  1431. #elif defined(GGML_USE_KOMPUTE)
  1432. buft = ggml_backend_kompute_buffer_type(gpu);
  1433. if (buft == nullptr) {
  1434. LLAMA_LOG_WARN("%s: cannot use GPU %d, check `vulkaninfo --summary`\n", __func__, gpu);
  1435. }
  1436. #endif
  1437. if (buft == nullptr) {
  1438. buft = llama_default_buffer_type_cpu(true);
  1439. }
  1440. return buft;
  1441. GGML_UNUSED(gpu);
  1442. }
  1443. static ggml_backend_buffer_type_t llama_default_buffer_type_split(int fallback_gpu, const float * tensor_split) {
  1444. ggml_backend_buffer_type_t buft = nullptr;
  1445. #ifdef GGML_USE_CUDA
  1446. if (ggml_backend_cuda_get_device_count() > 1) {
  1447. buft = ggml_backend_cuda_split_buffer_type(tensor_split);
  1448. }
  1449. #endif
  1450. #ifdef GGML_USE_SYCL
  1451. if (ggml_backend_sycl_get_device_count() > 1) {
  1452. buft = ggml_backend_sycl_split_buffer_type(tensor_split);
  1453. }
  1454. #endif
  1455. if (buft == nullptr) {
  1456. buft = llama_default_buffer_type_offload(fallback_gpu);
  1457. }
  1458. return buft;
  1459. GGML_UNUSED(tensor_split);
  1460. }
  1461. static size_t llama_get_device_count() {
  1462. #if defined(GGML_USE_CUDA)
  1463. return ggml_backend_cuda_get_device_count();
  1464. #elif defined(GGML_USE_SYCL)
  1465. return ggml_backend_sycl_get_device_count();
  1466. #elif defined(GGML_USE_VULKAN)
  1467. return ggml_backend_vk_get_device_count();
  1468. #else
  1469. return 1;
  1470. #endif
  1471. }
  1472. static size_t llama_get_device_memory(int device) {
  1473. #if defined(GGML_USE_CUDA)
  1474. size_t total;
  1475. size_t free;
  1476. ggml_backend_cuda_get_device_memory(device, &total, &free);
  1477. return free;
  1478. #elif defined(GGML_USE_SYCL)
  1479. size_t total;
  1480. size_t free;
  1481. ggml_backend_sycl_get_device_memory(device, &total, &free);
  1482. return free;
  1483. #elif defined(GGML_USE_VULKAN)
  1484. size_t total;
  1485. size_t free;
  1486. ggml_backend_vk_get_device_memory(device, &total, &free);
  1487. return free;
  1488. #else
  1489. return 1;
  1490. GGML_UNUSED(device);
  1491. #endif
  1492. }
  1493. //
  1494. // globals
  1495. //
  1496. struct llama_state {
  1497. llama_state() {
  1498. #ifdef GGML_USE_METAL
  1499. ggml_backend_metal_log_set_callback(log_callback, log_callback_user_data);
  1500. #endif
  1501. }
  1502. // We save the log callback globally
  1503. ggml_log_callback log_callback = llama_log_callback_default;
  1504. void * log_callback_user_data = nullptr;
  1505. };
  1506. static llama_state g_state;
  1507. // available llama models
  1508. enum e_model {
  1509. MODEL_UNKNOWN,
  1510. MODEL_17M,
  1511. MODEL_22M,
  1512. MODEL_33M,
  1513. MODEL_109M,
  1514. MODEL_137M,
  1515. MODEL_335M,
  1516. MODEL_0_5B,
  1517. MODEL_1B,
  1518. MODEL_2B,
  1519. MODEL_3B,
  1520. MODEL_4B,
  1521. MODEL_7B,
  1522. MODEL_8B,
  1523. MODEL_13B,
  1524. MODEL_14B,
  1525. MODEL_15B,
  1526. MODEL_20B,
  1527. MODEL_30B,
  1528. MODEL_34B,
  1529. MODEL_35B,
  1530. MODEL_40B,
  1531. MODEL_65B,
  1532. MODEL_70B,
  1533. MODEL_314B,
  1534. MODEL_SMALL,
  1535. MODEL_MEDIUM,
  1536. MODEL_LARGE,
  1537. MODEL_XL,
  1538. };
  1539. static const size_t kiB = 1024;
  1540. static const size_t MiB = 1024*kiB;
  1541. static const size_t GiB = 1024*MiB;
  1542. struct llama_hparams {
  1543. bool vocab_only;
  1544. bool rope_finetuned;
  1545. uint32_t n_vocab;
  1546. uint32_t n_ctx_train; // context size the model was trained on
  1547. uint32_t n_embd;
  1548. uint32_t n_head;
  1549. uint32_t n_head_kv;
  1550. uint32_t n_layer;
  1551. uint32_t n_rot;
  1552. 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
  1553. uint32_t n_embd_head_v; // dimension of values (d_v) aka n_embd_head
  1554. uint32_t n_ff;
  1555. uint32_t n_expert = 0;
  1556. uint32_t n_expert_used = 0;
  1557. uint32_t n_vocab_type = 0; // for BERT-style token types
  1558. float f_norm_eps;
  1559. float f_norm_rms_eps;
  1560. float rope_freq_base_train;
  1561. float rope_freq_scale_train;
  1562. uint32_t n_yarn_orig_ctx;
  1563. // for State Space Models
  1564. uint32_t ssm_d_conv = 0;
  1565. uint32_t ssm_d_inner = 0;
  1566. uint32_t ssm_d_state = 0;
  1567. uint32_t ssm_dt_rank = 0;
  1568. float f_clamp_kqv = 0.0f;
  1569. float f_max_alibi_bias = 0.0f;
  1570. float f_logit_scale = 0.0f;
  1571. bool causal_attn = true;
  1572. bool need_kq_pos = false;
  1573. enum llama_pooling_type pooling_type = LLAMA_POOLING_TYPE_NONE;
  1574. enum llama_rope_type rope_type = LLAMA_ROPE_TYPE_NONE;
  1575. enum llama_rope_scaling_type rope_scaling_type_train = LLAMA_ROPE_SCALING_TYPE_NONE;
  1576. bool operator!=(const llama_hparams & other) const {
  1577. if (this->vocab_only != other.vocab_only) return true;
  1578. if (this->n_vocab != other.n_vocab) return true;
  1579. if (this->n_ctx_train != other.n_ctx_train) return true;
  1580. if (this->n_embd != other.n_embd) return true;
  1581. if (this->n_head != other.n_head) return true;
  1582. if (this->n_head_kv != other.n_head_kv) return true;
  1583. if (this->n_layer != other.n_layer) return true;
  1584. if (this->n_rot != other.n_rot) return true;
  1585. if (this->n_embd_head_k != other.n_embd_head_k) return true;
  1586. if (this->n_embd_head_v != other.n_embd_head_v) return true;
  1587. if (this->n_ff != other.n_ff) return true;
  1588. if (this->n_expert != other.n_expert) return true;
  1589. if (this->n_expert_used != other.n_expert_used) return true;
  1590. if (this->rope_finetuned != other.rope_finetuned) return true;
  1591. if (this->n_yarn_orig_ctx != other.n_yarn_orig_ctx) return true;
  1592. if (this->ssm_d_conv != other.ssm_d_conv) return true;
  1593. if (this->ssm_d_inner != other.ssm_d_inner) return true;
  1594. if (this->ssm_d_state != other.ssm_d_state) return true;
  1595. if (this->ssm_dt_rank != other.ssm_dt_rank) return true;
  1596. const float EPSILON = 1e-9f;
  1597. if (!is_float_close(this->f_norm_eps, other.f_norm_eps, EPSILON)) return true;
  1598. if (!is_float_close(this->f_norm_rms_eps, other.f_norm_rms_eps, EPSILON)) return true;
  1599. if (!is_float_close(this->rope_freq_base_train, other.rope_freq_base_train, EPSILON)) return true;
  1600. if (!is_float_close(this->rope_freq_scale_train, other.rope_freq_scale_train, EPSILON)) return true;
  1601. return false;
  1602. }
  1603. uint32_t n_gqa() const {
  1604. if (n_head_kv == 0) {
  1605. return 0;
  1606. }
  1607. return n_head/n_head_kv;
  1608. }
  1609. uint32_t n_embd_k_gqa() const { // dimension of key embeddings across all k-v heads
  1610. return n_embd_head_k * n_head_kv;
  1611. }
  1612. uint32_t n_embd_v_gqa() const { // dimension of value embeddings across all k-v heads
  1613. return n_embd_head_v * n_head_kv;
  1614. }
  1615. uint32_t n_embd_k_s() const { // dimension of the rolling state embeddings
  1616. // corresponds to Mamba's conv_states size
  1617. // TODO: maybe support other convolution strides than 1
  1618. // NOTE: since the first column of the conv_state is shifted out each time, it's not actually needed
  1619. return (ssm_d_conv > 0 ? ssm_d_conv - 1 : 0) * ssm_d_inner;
  1620. }
  1621. uint32_t n_embd_v_s() const { // dimension of the recurrent state embeddings
  1622. // corresponds to Mamba's ssm_states size
  1623. return ssm_d_state * ssm_d_inner;
  1624. }
  1625. };
  1626. struct llama_cparams {
  1627. uint32_t n_ctx; // context size used during inference
  1628. uint32_t n_batch;
  1629. uint32_t n_ubatch;
  1630. uint32_t n_seq_max;
  1631. uint32_t n_threads; // number of threads to use for generation
  1632. uint32_t n_threads_batch; // number of threads to use for batch processing
  1633. float rope_freq_base;
  1634. float rope_freq_scale;
  1635. uint32_t n_yarn_orig_ctx;
  1636. // These hyperparameters are not exposed in GGUF, because all
  1637. // existing YaRN models use the same values for them.
  1638. float yarn_ext_factor;
  1639. float yarn_attn_factor;
  1640. float yarn_beta_fast;
  1641. float yarn_beta_slow;
  1642. float defrag_thold;
  1643. bool embeddings;
  1644. bool causal_attn;
  1645. bool offload_kqv;
  1646. enum llama_pooling_type pooling_type;
  1647. ggml_backend_sched_eval_callback cb_eval;
  1648. void * cb_eval_user_data;
  1649. };
  1650. struct llama_layer {
  1651. // normalization
  1652. struct ggml_tensor * attn_norm;
  1653. struct ggml_tensor * attn_norm_b;
  1654. struct ggml_tensor * attn_norm_2;
  1655. struct ggml_tensor * attn_norm_2_b;
  1656. struct ggml_tensor * attn_q_norm;
  1657. struct ggml_tensor * attn_q_norm_b;
  1658. struct ggml_tensor * attn_k_norm;
  1659. struct ggml_tensor * attn_k_norm_b;
  1660. struct ggml_tensor * attn_out_norm;
  1661. struct ggml_tensor * attn_out_norm_b;
  1662. // attention
  1663. struct ggml_tensor * wq;
  1664. struct ggml_tensor * wk;
  1665. struct ggml_tensor * wv;
  1666. struct ggml_tensor * wo;
  1667. struct ggml_tensor * wqkv;
  1668. // attention bias
  1669. struct ggml_tensor * bq;
  1670. struct ggml_tensor * bk;
  1671. struct ggml_tensor * bv;
  1672. struct ggml_tensor * bo;
  1673. struct ggml_tensor * bqkv;
  1674. // normalization
  1675. struct ggml_tensor * ffn_norm;
  1676. struct ggml_tensor * ffn_norm_b;
  1677. struct ggml_tensor * layer_out_norm;
  1678. struct ggml_tensor * layer_out_norm_b;
  1679. // ff
  1680. struct ggml_tensor * ffn_gate; // w1
  1681. struct ggml_tensor * ffn_down; // w2
  1682. struct ggml_tensor * ffn_up; // w3
  1683. // ff MoE
  1684. struct ggml_tensor * ffn_gate_inp;
  1685. struct ggml_tensor * ffn_gate_exp[LLAMA_MAX_EXPERTS];
  1686. struct ggml_tensor * ffn_down_exp[LLAMA_MAX_EXPERTS];
  1687. struct ggml_tensor * ffn_up_exp [LLAMA_MAX_EXPERTS];
  1688. // ff bias
  1689. struct ggml_tensor * ffn_down_b; // b2
  1690. struct ggml_tensor * ffn_up_b; // b3
  1691. struct ggml_tensor * ffn_act;
  1692. // mamba proj
  1693. struct ggml_tensor * ssm_in;
  1694. struct ggml_tensor * ssm_x;
  1695. struct ggml_tensor * ssm_dt;
  1696. struct ggml_tensor * ssm_out;
  1697. // mamba
  1698. struct ggml_tensor * ssm_conv1d;
  1699. struct ggml_tensor * ssm_a;
  1700. struct ggml_tensor * ssm_d;
  1701. // mamba bias
  1702. struct ggml_tensor * ssm_conv1d_b;
  1703. struct ggml_tensor * ssm_dt_b;
  1704. };
  1705. struct llama_kv_cell {
  1706. llama_pos pos = -1;
  1707. llama_pos delta = 0;
  1708. int32_t src = 0; // used by recurrent state models to copy states
  1709. std::set<llama_seq_id> seq_id;
  1710. bool has_seq_id(const llama_seq_id & id) const {
  1711. return seq_id.find(id) != seq_id.end();
  1712. }
  1713. bool is_empty() const {
  1714. return seq_id.empty();
  1715. }
  1716. bool is_same_seq(const llama_kv_cell & other) const {
  1717. return seq_id == other.seq_id;
  1718. }
  1719. };
  1720. // ring-buffer of cached KV data
  1721. struct llama_kv_cache {
  1722. bool has_shift = false;
  1723. bool do_defrag = false;
  1724. bool do_copy = false;
  1725. // with recurrent state models, a cell can hold the state for more than one past token
  1726. bool recurrent = false;
  1727. // Note: The value of head isn't only used to optimize searching
  1728. // for a free KV slot. llama_decode_internal also uses it, so it
  1729. // cannot be freely changed after a slot has been allocated.
  1730. uint32_t head = 0;
  1731. uint32_t size = 0;
  1732. uint32_t used = 0; // used cells (i.e. at least one seq_id)
  1733. // computed before each graph build
  1734. uint32_t n = 0;
  1735. ggml_type type_k = GGML_TYPE_F16;
  1736. ggml_type type_v = GGML_TYPE_F16;
  1737. std::vector<llama_kv_cell> cells;
  1738. std::vector<struct ggml_tensor *> k_l; // per layer
  1739. std::vector<struct ggml_tensor *> v_l;
  1740. std::vector<struct ggml_context *> ctxs;
  1741. std::vector<ggml_backend_buffer_t> bufs;
  1742. size_t total_size() const {
  1743. size_t size = 0;
  1744. for (ggml_backend_buffer_t buf : bufs) {
  1745. size += ggml_backend_buffer_get_size(buf);
  1746. }
  1747. return size;
  1748. }
  1749. ~llama_kv_cache() {
  1750. for (struct ggml_context * ctx : ctxs) {
  1751. ggml_free(ctx);
  1752. }
  1753. for (ggml_backend_buffer_t buf : bufs) {
  1754. ggml_backend_buffer_free(buf);
  1755. }
  1756. }
  1757. };
  1758. struct llama_control_vector {
  1759. std::vector<struct ggml_tensor *> tensors; // per layer
  1760. std::vector<struct ggml_context *> ctxs;
  1761. std::vector<ggml_backend_buffer_t> bufs;
  1762. int32_t layer_start = -1;
  1763. int32_t layer_end = -1;
  1764. ggml_tensor * tensor_for(int il) const {
  1765. if (il < 0 || il < layer_start || il > layer_end || (size_t) il >= tensors.size()) {
  1766. return nullptr;
  1767. }
  1768. return tensors[il];
  1769. }
  1770. ~llama_control_vector() {
  1771. for (struct ggml_context * ctx : ctxs) {
  1772. ggml_free(ctx);
  1773. }
  1774. for (ggml_backend_buffer_t buf : bufs) {
  1775. ggml_backend_buffer_free(buf);
  1776. }
  1777. }
  1778. };
  1779. struct llama_vocab {
  1780. using id = int32_t;
  1781. using token = std::string;
  1782. using ttype = llama_token_type;
  1783. struct token_data {
  1784. token text;
  1785. float score;
  1786. ttype type;
  1787. };
  1788. enum llama_vocab_type type = LLAMA_VOCAB_TYPE_SPM;
  1789. std::unordered_map<token, id> token_to_id;
  1790. std::vector<token_data> id_to_token;
  1791. std::unordered_map<token, id> special_tokens_cache;
  1792. std::map<std::pair<std::string, std::string>, int> bpe_ranks;
  1793. // default LLaMA special tokens
  1794. id special_bos_id = 1;
  1795. id special_eos_id = 2;
  1796. id special_unk_id = 0;
  1797. id special_sep_id = -1;
  1798. id special_pad_id = -1;
  1799. int special_add_bos = -1; // -1 unknown, 1 add, 0 don't add.
  1800. int special_add_eos = -1; // -1 unknown, 1 add, 0 don't add.
  1801. id linefeed_id = 13;
  1802. id special_prefix_id = 32007;
  1803. id special_middle_id = 32009;
  1804. id special_suffix_id = 32008;
  1805. id special_eot_id = 32010;
  1806. bool add_space_prefix = true;
  1807. int find_bpe_rank(const std::string & token_left, const std::string & token_right) const {
  1808. GGML_ASSERT(token_left.find(' ') == std::string::npos);
  1809. GGML_ASSERT(token_left.find('\n') == std::string::npos);
  1810. GGML_ASSERT(token_right.find(' ') == std::string::npos);
  1811. GGML_ASSERT(token_right.find('\n') == std::string::npos);
  1812. auto it = bpe_ranks.find(std::make_pair(token_left, token_right));
  1813. if (it == bpe_ranks.end()) {
  1814. return -1;
  1815. }
  1816. return it->second;
  1817. }
  1818. };
  1819. struct llama_model {
  1820. e_model type = MODEL_UNKNOWN;
  1821. llm_arch arch = LLM_ARCH_UNKNOWN;
  1822. llama_ftype ftype = LLAMA_FTYPE_ALL_F32;
  1823. std::string name = "n/a";
  1824. llama_hparams hparams = {};
  1825. llama_vocab vocab;
  1826. struct ggml_tensor * tok_embd;
  1827. struct ggml_tensor * type_embd;
  1828. struct ggml_tensor * pos_embd;
  1829. struct ggml_tensor * tok_norm;
  1830. struct ggml_tensor * tok_norm_b;
  1831. struct ggml_tensor * output_norm;
  1832. struct ggml_tensor * output_norm_b;
  1833. struct ggml_tensor * output;
  1834. struct ggml_tensor * output_b;
  1835. std::vector<llama_layer> layers;
  1836. llama_split_mode split_mode;
  1837. int main_gpu;
  1838. int n_gpu_layers;
  1839. // gguf metadata
  1840. std::unordered_map<std::string, std::string> gguf_kv;
  1841. // layer -> buffer type mapping
  1842. struct layer_buft {
  1843. layer_buft() : buft_matrix(nullptr), buft(nullptr) {}
  1844. layer_buft(ggml_backend_buffer_type_t matrix) : buft_matrix(matrix), buft(matrix) {}
  1845. layer_buft(ggml_backend_buffer_type_t matrix, ggml_backend_buffer_type_t other) : buft_matrix(matrix), buft(other) {}
  1846. ggml_backend_buffer_type_t buft_matrix; // matrices only - used by split buffers and backends that support only matrix multiplication
  1847. ggml_backend_buffer_type_t buft; // everything else
  1848. };
  1849. layer_buft buft_input;
  1850. layer_buft buft_output;
  1851. std::vector<layer_buft> buft_layer;
  1852. // contexts where the model tensors metadata is stored
  1853. std::vector<struct ggml_context *> ctxs;
  1854. // the model memory buffers for the tensor data
  1855. std::vector<ggml_backend_buffer_t> bufs;
  1856. // model memory mapped files
  1857. llama_mmaps mappings;
  1858. // objects representing data potentially being locked in memory
  1859. llama_mlocks mlock_bufs;
  1860. llama_mlocks mlock_mmaps;
  1861. // for quantize-stats only
  1862. std::vector<std::pair<std::string, struct ggml_tensor *>> tensors_by_name;
  1863. int64_t t_load_us = 0;
  1864. int64_t t_start_us = 0;
  1865. ~llama_model() {
  1866. for (struct ggml_context * ctx : ctxs) {
  1867. ggml_free(ctx);
  1868. }
  1869. for (ggml_backend_buffer_t buf : bufs) {
  1870. #ifdef GGML_USE_CUDA
  1871. if (ggml_backend_buffer_get_type(buf) == ggml_backend_cpu_buffer_type()) {
  1872. ggml_backend_cuda_unregister_host_buffer(ggml_backend_buffer_get_base(buf));
  1873. }
  1874. #endif
  1875. ggml_backend_buffer_free(buf);
  1876. }
  1877. }
  1878. };
  1879. struct llama_context {
  1880. llama_context(const llama_model & model) : model(model), t_start_us(model.t_start_us), t_load_us(model.t_load_us) {}
  1881. ~llama_context() {
  1882. ggml_backend_sched_free(sched);
  1883. for (ggml_backend_t backend : backends) {
  1884. ggml_backend_free(backend);
  1885. }
  1886. ggml_backend_buffer_free(buf_output);
  1887. }
  1888. llama_cparams cparams;
  1889. std::vector<ggml_backend_t> backends;
  1890. #ifdef GGML_USE_METAL
  1891. ggml_backend_t backend_metal = nullptr;
  1892. #endif
  1893. ggml_backend_t backend_cpu = nullptr;
  1894. const llama_model & model;
  1895. // key + value cache for the self attention
  1896. struct llama_kv_cache kv_self;
  1897. std::mt19937 rng;
  1898. bool has_evaluated_once = false;
  1899. int64_t t_start_us;
  1900. int64_t t_load_us;
  1901. int64_t t_sample_us = 0;
  1902. int64_t t_p_eval_us = 0;
  1903. int64_t t_eval_us = 0;
  1904. int64_t t_compute_start_us = 0;
  1905. int64_t n_queued_tokens = 0;
  1906. int32_t n_sample = 0; // number of tokens sampled
  1907. int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1)
  1908. int32_t n_eval = 0; // number of eval calls
  1909. // host buffer for the model output (logits and embeddings)
  1910. ggml_backend_buffer_t buf_output = nullptr;
  1911. // decode output (2-dimensional array: [n_outputs][n_vocab])
  1912. size_t logits_size = 0; // capacity (of floats) for logits
  1913. float * logits = nullptr;
  1914. std::vector<int32_t> output_ids; // map batch token positions to ids of the logits and embd buffers
  1915. size_t output_size = 0; // capacity (of tokens positions) for the output buffers
  1916. int32_t n_outputs = 0; // number of actually-used outputs in the current ubatch
  1917. bool logits_all = false;
  1918. // embeddings output (2-dimensional array: [n_outputs][n_embd])
  1919. // populated only when pooling_type == LLAMA_POOLING_TYPE_NONE
  1920. size_t embd_size = 0; // capacity (of floats) for embeddings
  1921. float * embd = nullptr;
  1922. // sequence embeddings output (map of [n_embd] vectors)
  1923. // populated only when pooling_type != LLAMA_POOLING_TYPE_NONE
  1924. std::map<llama_seq_id, std::vector<float>> embd_seq;
  1925. // memory buffers used to evaluate the model
  1926. std::vector<uint8_t> buf_compute_meta;
  1927. ggml_backend_sched_t sched = nullptr;
  1928. ggml_abort_callback abort_callback = nullptr;
  1929. void * abort_callback_data = nullptr;
  1930. // input tensors
  1931. struct ggml_tensor * inp_tokens; // I32 [n_batch]
  1932. struct ggml_tensor * inp_embd; // F32 [n_embd, n_batch]
  1933. struct ggml_tensor * inp_pos; // I32 [n_batch]
  1934. struct ggml_tensor * inp_out_ids; // I32 [n_outputs]
  1935. struct ggml_tensor * inp_KQ_mask; // F32 [kv_size, n_batch]
  1936. struct ggml_tensor * inp_KQ_pos; // F32 [n_kv]
  1937. struct ggml_tensor * inp_K_shift; // I32 [kv_size]
  1938. struct ggml_tensor * inp_mean; // F32 [n_batch, n_batch]
  1939. struct ggml_tensor * inp_cls; // I32 [n_batch]
  1940. struct ggml_tensor * inp_s_copy; // I32 [kv_size]
  1941. struct ggml_tensor * inp_s_mask; // F32 [1, n_kv]
  1942. struct ggml_tensor * inp_s_seq; // I32 [n_kv, n_batch]
  1943. // control vectors
  1944. struct llama_control_vector cvec;
  1945. #ifdef GGML_USE_MPI
  1946. ggml_mpi_context * ctx_mpi = NULL;
  1947. #endif
  1948. };
  1949. //
  1950. // kv cache helpers
  1951. //
  1952. static bool llama_kv_cache_init(
  1953. struct llama_kv_cache & cache,
  1954. const llama_model & model,
  1955. ggml_type type_k,
  1956. ggml_type type_v,
  1957. uint32_t kv_size,
  1958. bool offload) {
  1959. const struct llama_hparams & hparams = model.hparams;
  1960. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  1961. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  1962. const int64_t n_layer = hparams.n_layer;
  1963. cache.has_shift = false;
  1964. // TODO: find a nicer way to add other recurrent model architectures
  1965. cache.recurrent = model.arch == LLM_ARCH_MAMBA;
  1966. // TODO: support mixed reccurent Transformer architectues
  1967. // NOTE: (!a || b) is a logical implication (a -> b)
  1968. GGML_ASSERT(!cache.recurrent || n_embd_k_gqa == hparams.n_embd_k_s());
  1969. GGML_ASSERT(!cache.recurrent || n_embd_v_gqa == hparams.n_embd_v_s());
  1970. GGML_ASSERT( cache.recurrent || n_embd_k_gqa == hparams.n_embd_k_gqa());
  1971. GGML_ASSERT( cache.recurrent || n_embd_v_gqa == hparams.n_embd_v_gqa());
  1972. cache.head = 0;
  1973. cache.size = kv_size;
  1974. cache.used = 0;
  1975. cache.type_k = type_k;
  1976. cache.type_v = type_v;
  1977. cache.cells.clear();
  1978. cache.cells.resize(kv_size);
  1979. if (cache.recurrent) {
  1980. // init state copy sources
  1981. for (uint32_t i = 0; i < cache.size; ++i) {
  1982. cache.cells[i].src = i;
  1983. }
  1984. }
  1985. #ifdef GGML_USE_CLBLAST
  1986. offload = false;
  1987. #endif
  1988. // count used buffer types
  1989. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  1990. if (offload) {
  1991. for (int64_t i = 0; i < n_layer; ++i) {
  1992. buft_layer_count[model.buft_layer[i].buft]++;
  1993. }
  1994. } else {
  1995. buft_layer_count[llama_default_buffer_type_cpu(true)] = n_layer;
  1996. }
  1997. // create a context for each buffer type
  1998. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  1999. for (auto & it : buft_layer_count) {
  2000. int n_layers = it.second;
  2001. struct ggml_init_params params = {
  2002. /*.mem_size =*/ 2u*n_layers*ggml_tensor_overhead(),
  2003. /*.mem_buffer =*/ NULL,
  2004. /*.no_alloc =*/ true,
  2005. };
  2006. ggml_context * ctx = ggml_init(params);
  2007. if (!ctx) {
  2008. LLAMA_LOG_ERROR("%s: failed to allocate context for kv cache\n", __func__);
  2009. return false;
  2010. }
  2011. ctx_map[it.first] = ctx;
  2012. cache.ctxs.push_back(ctx);
  2013. }
  2014. cache.k_l.reserve(n_layer);
  2015. cache.v_l.reserve(n_layer);
  2016. for (int i = 0; i < (int) n_layer; i++) {
  2017. struct ggml_context * ctx = offload ? ctx_map.at(model.buft_layer[i].buft) : cache.ctxs.front();
  2018. ggml_tensor * k = ggml_new_tensor_1d(ctx, type_k, n_embd_k_gqa*kv_size);
  2019. ggml_tensor * v = ggml_new_tensor_1d(ctx, type_v, n_embd_v_gqa*kv_size);
  2020. ggml_format_name(k, "cache_k_l%d", i);
  2021. ggml_format_name(v, "cache_v_l%d", i);
  2022. cache.k_l.push_back(k);
  2023. cache.v_l.push_back(v);
  2024. }
  2025. // allocate tensors and initialize the buffers to avoid NaNs in the padding
  2026. for (auto it : ctx_map) {
  2027. ggml_backend_buffer_type_t buft = it.first;
  2028. ggml_context * ctx = it.second;
  2029. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  2030. if (!buf) {
  2031. LLAMA_LOG_ERROR("%s: failed to allocate buffer for kv cache\n", __func__);
  2032. return false;
  2033. }
  2034. ggml_backend_buffer_clear(buf, 0);
  2035. 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);
  2036. cache.bufs.push_back(buf);
  2037. }
  2038. return true;
  2039. }
  2040. // find an empty slot of size "n_tokens" in the cache
  2041. // updates the cache head
  2042. // Note: On success, it's important that cache.head points
  2043. // to the first cell of the slot.
  2044. static bool llama_kv_cache_find_slot(
  2045. struct llama_kv_cache & cache,
  2046. const struct llama_batch & batch) {
  2047. const uint32_t n_ctx = cache.size;
  2048. const uint32_t n_tokens = batch.n_tokens;
  2049. if (cache.recurrent) {
  2050. // For recurrent state architectures (like Mamba),
  2051. // each KV cache cell can store the state for a whole sequence.
  2052. llama_seq_id min = cache.size - 1;
  2053. llama_seq_id max = 0;
  2054. for (uint32_t i = 0; i < n_tokens; ++i) {
  2055. for (int32_t j = 0; j < batch.n_seq_id[i]; ++j) {
  2056. llama_seq_id seq_id = batch.seq_id[i][j];
  2057. // make sure it's a valid seq_id
  2058. if ((uint32_t) seq_id < cache.size) {
  2059. if (seq_id > max) {
  2060. max = seq_id;
  2061. }
  2062. if (seq_id < min) {
  2063. min = seq_id;
  2064. }
  2065. // Assuming the tokens are in-order
  2066. if (batch.pos[i] != cache.cells[seq_id].pos + 1) {
  2067. // What should happen when the pos backtracks or skips a value?
  2068. // Clearing the state mid-batch would require special-casing which isn't done.
  2069. LLAMA_LOG_WARN("%s: non-consecutive token position %d after %d for sequence %d\n",
  2070. __func__, batch.pos[i], cache.cells[seq_id].pos, seq_id);
  2071. }
  2072. if (cache.cells[seq_id].pos < 0 && 0 <= batch.pos[i]) {
  2073. cache.used += 1;
  2074. }
  2075. cache.cells[seq_id].pos = batch.pos[i];
  2076. // NOTE: seq_ids are not inserted here; they are handled when the input tensors are set
  2077. } else {
  2078. // too big seq_id
  2079. // TODO: would it be possible to resize the KV cache size instead?
  2080. LLAMA_LOG_ERROR("%s: seq_id=%d >= kv_size=%d Try using a bigger --parallel value\n", __func__, seq_id, cache.size);
  2081. return false;
  2082. }
  2083. }
  2084. }
  2085. // allow getting the range of used cells, from head to head + n
  2086. cache.head = min;
  2087. cache.n = max - min + 1;
  2088. // sanity check
  2089. return max >= min;
  2090. }
  2091. // otherwise, one cell per token.
  2092. if (n_tokens > n_ctx) {
  2093. LLAMA_LOG_ERROR("%s: n_tokens=%d > n_ctx=%d\n", __func__, n_tokens, n_ctx);
  2094. return false;
  2095. }
  2096. uint32_t n_tested = 0;
  2097. while (true) {
  2098. if (cache.head + n_tokens > n_ctx) {
  2099. n_tested += n_ctx - cache.head;
  2100. cache.head = 0;
  2101. continue;
  2102. }
  2103. bool found = true;
  2104. for (uint32_t i = 0; i < n_tokens; i++) {
  2105. if (cache.cells[cache.head + i].pos >= 0) {
  2106. found = false;
  2107. cache.head += i + 1;
  2108. n_tested += i + 1;
  2109. break;
  2110. }
  2111. }
  2112. if (found) {
  2113. break;
  2114. }
  2115. if (n_tested >= n_ctx) {
  2116. //LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens);
  2117. return false;
  2118. }
  2119. }
  2120. for (uint32_t i = 0; i < n_tokens; i++) {
  2121. cache.cells[cache.head + i].pos = batch.pos[i];
  2122. for (int32_t j = 0; j < batch.n_seq_id[i]; j++) {
  2123. cache.cells[cache.head + i].seq_id.insert(batch.seq_id[i][j]);
  2124. }
  2125. }
  2126. cache.used += n_tokens;
  2127. return true;
  2128. }
  2129. // find how many cells are currently in use
  2130. static uint32_t llama_kv_cache_cell_max(const struct llama_kv_cache & cache) {
  2131. for (uint32_t i = cache.size; i > 0; --i) {
  2132. const llama_kv_cell & cell = cache.cells[i - 1];
  2133. if (cell.pos >= 0 && !cell.is_empty()) {
  2134. return i;
  2135. }
  2136. }
  2137. return 0;
  2138. }
  2139. static void llama_kv_cache_clear(struct llama_kv_cache & cache) {
  2140. for (int32_t i = 0; i < (int32_t) cache.size; ++i) {
  2141. cache.cells[i].pos = -1;
  2142. cache.cells[i].seq_id.clear();
  2143. }
  2144. cache.head = 0;
  2145. cache.used = 0;
  2146. }
  2147. static bool llama_kv_cache_seq_rm(
  2148. struct llama_kv_cache & cache,
  2149. llama_seq_id seq_id,
  2150. llama_pos p0,
  2151. llama_pos p1) {
  2152. uint32_t new_head = cache.size;
  2153. if (p0 < 0) p0 = 0;
  2154. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2155. // models like Mamba can't have a state partially erased
  2156. if (cache.recurrent) {
  2157. if (seq_id >= (int64_t) cache.size) {
  2158. // could be fatal
  2159. return false;
  2160. }
  2161. if (0 <= seq_id) {
  2162. // partial intersection is invalid
  2163. if ((0 < p0 && p0 <= cache.cells[seq_id].pos) || (0 < p1 && p1 <= cache.cells[seq_id].pos)) {
  2164. return false;
  2165. }
  2166. } else {
  2167. // seq_id is negative, then the range should include everything or nothing
  2168. if (p0 != p1 && (p0 != 0 || p1 != std::numeric_limits<llama_pos>::max())) {
  2169. return false;
  2170. }
  2171. }
  2172. }
  2173. for (uint32_t i = 0; i < cache.size; ++i) {
  2174. if (cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2175. if (seq_id < 0) {
  2176. cache.cells[i].seq_id.clear();
  2177. } else if (cache.cells[i].has_seq_id(seq_id)) {
  2178. cache.cells[i].seq_id.erase(seq_id);
  2179. } else {
  2180. continue;
  2181. }
  2182. if (cache.cells[i].is_empty()) {
  2183. // keep count of the number of used cells
  2184. if (cache.cells[i].pos >= 0) cache.used--;
  2185. cache.cells[i].pos = -1;
  2186. if (new_head == cache.size) new_head = i;
  2187. }
  2188. }
  2189. }
  2190. // If we freed up a slot, set head to it so searching can start there.
  2191. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  2192. return true;
  2193. }
  2194. static void llama_kv_cache_seq_cp(
  2195. struct llama_kv_cache & cache,
  2196. llama_seq_id seq_id_src,
  2197. llama_seq_id seq_id_dst,
  2198. llama_pos p0,
  2199. llama_pos p1) {
  2200. if (p0 < 0) p0 = 0;
  2201. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2202. if (cache.recurrent) {
  2203. if ((uint32_t) seq_id_dst < cache.size && (uint32_t) seq_id_src < cache.size) {
  2204. seq_id_src = cache.cells[seq_id_src].src;
  2205. GGML_ASSERT((uint32_t) seq_id_src < cache.size);
  2206. // intent to "copy from"
  2207. // supports copy chains thanks to taking the source of the source
  2208. cache.cells[seq_id_dst].src = seq_id_src;
  2209. // preserve the "keep or clear" status of the copied sequence
  2210. if (cache.cells[seq_id_src].has_seq_id(seq_id_src)) {
  2211. cache.cells[seq_id_dst].seq_id.insert(seq_id_dst);
  2212. } else {
  2213. cache.cells[seq_id_dst].seq_id.erase(seq_id_dst);
  2214. }
  2215. cache.do_copy = true;
  2216. cache.cells[seq_id_dst].pos = cache.cells[seq_id_src].pos;
  2217. }
  2218. return;
  2219. }
  2220. // otherwise, this is the KV cache of a Transformer-like model
  2221. cache.head = 0;
  2222. for (uint32_t i = 0; i < cache.size; ++i) {
  2223. if (cache.cells[i].has_seq_id(seq_id_src) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2224. cache.cells[i].seq_id.insert(seq_id_dst);
  2225. }
  2226. }
  2227. }
  2228. static void llama_kv_cache_seq_keep(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  2229. uint32_t new_head = cache.size;
  2230. for (uint32_t i = 0; i < cache.size; ++i) {
  2231. if (!cache.cells[i].has_seq_id(seq_id)) {
  2232. if (cache.cells[i].pos >= 0) cache.used--;
  2233. cache.cells[i].pos = -1;
  2234. cache.cells[i].seq_id.clear();
  2235. if (new_head == cache.size) new_head = i;
  2236. } else {
  2237. cache.cells[i].seq_id.clear();
  2238. cache.cells[i].seq_id.insert(seq_id);
  2239. }
  2240. }
  2241. // If we freed up a slot, set head to it so searching can start there.
  2242. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  2243. }
  2244. static void llama_kv_cache_seq_add(
  2245. struct llama_kv_cache & cache,
  2246. llama_seq_id seq_id,
  2247. llama_pos p0,
  2248. llama_pos p1,
  2249. llama_pos delta) {
  2250. uint32_t new_head = cache.size;
  2251. if (p0 < 0) p0 = 0;
  2252. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2253. if (cache.recurrent) {
  2254. // for Mamba-like models, only the pos needs to be shifted
  2255. if (0 <= seq_id && seq_id < (int64_t) cache.size) {
  2256. llama_kv_cell & cell = cache.cells[seq_id];
  2257. if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
  2258. cell.pos += delta;
  2259. }
  2260. }
  2261. return;
  2262. }
  2263. for (uint32_t i = 0; i < cache.size; ++i) {
  2264. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2265. cache.has_shift = true;
  2266. cache.cells[i].pos += delta;
  2267. cache.cells[i].delta += delta;
  2268. if (cache.cells[i].pos < 0) {
  2269. if (!cache.cells[i].is_empty()) {
  2270. cache.used--;
  2271. }
  2272. cache.cells[i].pos = -1;
  2273. cache.cells[i].seq_id.clear();
  2274. if (new_head == cache.size) {
  2275. new_head = i;
  2276. }
  2277. }
  2278. }
  2279. }
  2280. // If we freed up a slot, set head to it so searching can start there.
  2281. // Otherwise we just start the next search from the beginning.
  2282. cache.head = new_head != cache.size ? new_head : 0;
  2283. }
  2284. static void llama_kv_cache_seq_div(
  2285. struct llama_kv_cache & cache,
  2286. llama_seq_id seq_id,
  2287. llama_pos p0,
  2288. llama_pos p1,
  2289. int d) {
  2290. if (p0 < 0) p0 = 0;
  2291. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2292. if (cache.recurrent) {
  2293. // for Mamba-like models, only the pos needs to be changed
  2294. if (0 <= seq_id && seq_id < (int64_t) cache.size) {
  2295. llama_kv_cell & cell = cache.cells[seq_id];
  2296. if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
  2297. cell.pos /= d;
  2298. }
  2299. }
  2300. return;
  2301. }
  2302. for (uint32_t i = 0; i < cache.size; ++i) {
  2303. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2304. cache.has_shift = true;
  2305. {
  2306. llama_pos p_old = cache.cells[i].pos;
  2307. cache.cells[i].pos /= d;
  2308. cache.cells[i].delta += cache.cells[i].pos - p_old;
  2309. }
  2310. }
  2311. }
  2312. }
  2313. static llama_pos llama_kv_cache_seq_pos_max(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  2314. llama_pos result = 0;
  2315. for (uint32_t i = 0; i < cache.size; ++i) {
  2316. if (cache.cells[i].has_seq_id(seq_id)) {
  2317. result = std::max(result, cache.cells[i].pos);
  2318. }
  2319. }
  2320. return result;
  2321. }
  2322. static void llama_kv_cache_defrag(struct llama_kv_cache & cache) {
  2323. cache.do_defrag = true;
  2324. }
  2325. //
  2326. // model loading and saving
  2327. //
  2328. enum llama_fver {
  2329. GGUF_FILE_VERSION_V1 = 1,
  2330. GGUF_FILE_VERSION_V2 = 2,
  2331. GGUF_FILE_VERSION_V3 = 3,
  2332. };
  2333. static const char * llama_file_version_name(llama_fver version) {
  2334. switch (version) {
  2335. case GGUF_FILE_VERSION_V1: return "GGUF V1 (support until nov 2023)";
  2336. case GGUF_FILE_VERSION_V2: return "GGUF V2";
  2337. case GGUF_FILE_VERSION_V3: return "GGUF V3 (latest)";
  2338. }
  2339. return "unknown";
  2340. }
  2341. static std::string llama_format_tensor_shape(const std::vector<int64_t> & ne) {
  2342. char buf[256];
  2343. snprintf(buf, sizeof(buf), "%5" PRId64, ne.at(0));
  2344. for (size_t i = 1; i < ne.size(); i++) {
  2345. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, ne.at(i));
  2346. }
  2347. return buf;
  2348. }
  2349. static std::string llama_format_tensor_shape(const struct ggml_tensor * t) {
  2350. char buf[256];
  2351. snprintf(buf, sizeof(buf), "%5" PRId64, t->ne[0]);
  2352. for (int i = 1; i < GGML_MAX_DIMS; i++) {
  2353. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, t->ne[i]);
  2354. }
  2355. return buf;
  2356. }
  2357. namespace GGUFMeta {
  2358. template <typename T, gguf_type gt_, T (*gfun)(const gguf_context *, const int)>
  2359. struct GKV_Base_Type {
  2360. static constexpr gguf_type gt = gt_;
  2361. static T getter(const gguf_context * ctx, const int kid) {
  2362. return gfun(ctx, kid);
  2363. }
  2364. };
  2365. template<typename T> struct GKV_Base;
  2366. template<> struct GKV_Base<bool >: GKV_Base_Type<bool, GGUF_TYPE_BOOL, gguf_get_val_bool> {};
  2367. template<> struct GKV_Base<uint8_t >: GKV_Base_Type<uint8_t, GGUF_TYPE_UINT8, gguf_get_val_u8 > {};
  2368. template<> struct GKV_Base<uint16_t >: GKV_Base_Type<uint16_t, GGUF_TYPE_UINT16, gguf_get_val_u16 > {};
  2369. template<> struct GKV_Base<uint32_t >: GKV_Base_Type<uint32_t, GGUF_TYPE_UINT32, gguf_get_val_u32 > {};
  2370. template<> struct GKV_Base<uint64_t >: GKV_Base_Type<uint64_t, GGUF_TYPE_UINT64, gguf_get_val_u64 > {};
  2371. template<> struct GKV_Base<int8_t >: GKV_Base_Type<int8_t, GGUF_TYPE_INT8, gguf_get_val_i8 > {};
  2372. template<> struct GKV_Base<int16_t >: GKV_Base_Type<int16_t, GGUF_TYPE_INT16, gguf_get_val_i16 > {};
  2373. template<> struct GKV_Base<int32_t >: GKV_Base_Type<int32_t, GGUF_TYPE_INT32, gguf_get_val_i32 > {};
  2374. template<> struct GKV_Base<int64_t >: GKV_Base_Type<int64_t, GGUF_TYPE_INT64, gguf_get_val_i64 > {};
  2375. template<> struct GKV_Base<float >: GKV_Base_Type<float, GGUF_TYPE_FLOAT32, gguf_get_val_f32 > {};
  2376. template<> struct GKV_Base<double >: GKV_Base_Type<double, GGUF_TYPE_FLOAT64, gguf_get_val_f64 > {};
  2377. template<> struct GKV_Base<const char *>: GKV_Base_Type<const char *, GGUF_TYPE_STRING, gguf_get_val_str > {};
  2378. template<> struct GKV_Base<std::string> {
  2379. static constexpr gguf_type gt = GGUF_TYPE_STRING;
  2380. static std::string getter(const gguf_context * ctx, const int kid) {
  2381. return gguf_get_val_str(ctx, kid);
  2382. }
  2383. };
  2384. struct ArrayInfo {
  2385. const gguf_type gt;
  2386. const size_t length;
  2387. const void * data;
  2388. };
  2389. template<> struct GKV_Base<ArrayInfo> {
  2390. public:
  2391. static constexpr gguf_type gt = GGUF_TYPE_ARRAY;
  2392. static ArrayInfo getter(const gguf_context *ctx, const int k) {
  2393. return ArrayInfo {
  2394. gguf_get_arr_type(ctx, k),
  2395. size_t(gguf_get_arr_n(ctx, k)),
  2396. gguf_get_arr_data(ctx, k),
  2397. };
  2398. }
  2399. };
  2400. template<typename T>
  2401. class GKV : public GKV_Base<T> {
  2402. GKV() = delete;
  2403. public:
  2404. static T get_kv(const gguf_context * ctx, const int k) {
  2405. const enum gguf_type kt = gguf_get_kv_type(ctx, k);
  2406. if (kt != GKV::gt) {
  2407. throw std::runtime_error(format("key %s has wrong type %s but expected type %s",
  2408. gguf_get_key(ctx, k), gguf_type_name(kt), gguf_type_name(GKV::gt)));
  2409. }
  2410. return GKV::getter(ctx, k);
  2411. }
  2412. static const char * override_type_to_str(const llama_model_kv_override_type ty) {
  2413. switch (ty) {
  2414. case LLAMA_KV_OVERRIDE_TYPE_BOOL: return "bool";
  2415. case LLAMA_KV_OVERRIDE_TYPE_INT: return "int";
  2416. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: return "float";
  2417. }
  2418. return "unknown";
  2419. }
  2420. static bool validate_override(const llama_model_kv_override_type expected_type, const struct llama_model_kv_override * ovrd) {
  2421. if (!ovrd) { return false; }
  2422. if (ovrd->tag == expected_type) {
  2423. LLAMA_LOG_INFO("%s: Using metadata override (%5s) '%s' = ",
  2424. __func__, override_type_to_str(ovrd->tag), ovrd->key);
  2425. switch (ovrd->tag) {
  2426. case LLAMA_KV_OVERRIDE_TYPE_BOOL: {
  2427. LLAMA_LOG_INFO("%s\n", ovrd->bool_value ? "true" : "false");
  2428. } break;
  2429. case LLAMA_KV_OVERRIDE_TYPE_INT: {
  2430. LLAMA_LOG_INFO("%" PRId64 "\n", ovrd->int_value);
  2431. } break;
  2432. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: {
  2433. LLAMA_LOG_INFO("%.6f\n", ovrd->float_value);
  2434. } break;
  2435. default:
  2436. // Shouldn't be possible to end up here, but just in case...
  2437. throw std::runtime_error(
  2438. format("Unsupported attempt to override %s type for metadata key %s\n",
  2439. override_type_to_str(ovrd->tag), ovrd->key));
  2440. }
  2441. return true;
  2442. }
  2443. LLAMA_LOG_WARN("%s: Warning: Bad metadata override type for key '%s', expected %s but got %s\n",
  2444. __func__, ovrd->key, override_type_to_str(expected_type), override_type_to_str(ovrd->tag));
  2445. return false;
  2446. }
  2447. template<typename OT>
  2448. static typename std::enable_if<std::is_same<OT, bool>::value, bool>::type
  2449. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  2450. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_BOOL, ovrd)) {
  2451. target = ovrd->bool_value;
  2452. return true;
  2453. }
  2454. return false;
  2455. }
  2456. template<typename OT>
  2457. static typename std::enable_if<!std::is_same<OT, bool>::value && std::is_integral<OT>::value, bool>::type
  2458. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  2459. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_INT, ovrd)) {
  2460. target = ovrd->int_value;
  2461. return true;
  2462. }
  2463. return false;
  2464. }
  2465. template<typename OT>
  2466. static typename std::enable_if<std::is_floating_point<OT>::value, bool>::type
  2467. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  2468. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_FLOAT, ovrd)) {
  2469. target = ovrd->float_value;
  2470. return true;
  2471. }
  2472. return false;
  2473. }
  2474. template<typename OT>
  2475. static typename std::enable_if<std::is_same<OT, std::string>::value, bool>::type
  2476. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  2477. (void)target;
  2478. (void)ovrd;
  2479. if (!ovrd) { return false; }
  2480. // Currently, we should never end up here so it would be a bug if we do.
  2481. throw std::runtime_error(format("Unsupported attempt to override string type for metadata key %s\n",
  2482. ovrd ? ovrd->key : "NULL"));
  2483. }
  2484. static bool set(const gguf_context * ctx, const int k, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  2485. if (try_override<T>(target, ovrd)) {
  2486. return true;
  2487. }
  2488. if (k < 0) { return false; }
  2489. target = get_kv(ctx, k);
  2490. return true;
  2491. }
  2492. static bool set(const gguf_context * ctx, const char * key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  2493. return set(ctx, gguf_find_key(ctx, key), target, ovrd);
  2494. }
  2495. static bool set(const gguf_context * ctx, const std::string & key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  2496. return set(ctx, key.c_str(), target, ovrd);
  2497. }
  2498. };
  2499. }
  2500. using llama_buf_map = std::unordered_map<uint32_t, ggml_backend_buffer_t>;
  2501. struct llama_model_loader {
  2502. int n_kv = 0;
  2503. int n_tensors = 0;
  2504. int n_created = 0;
  2505. int64_t n_elements = 0;
  2506. size_t n_bytes = 0;
  2507. bool use_mmap = false;
  2508. llama_files files;
  2509. llama_ftype ftype;
  2510. llama_fver fver;
  2511. llama_mmaps mappings;
  2512. // Holds information on a model weights
  2513. struct llama_tensor_weights {
  2514. uint16_t idx; // source file index
  2515. size_t offs; // tensor data offset in the original file
  2516. ggml_tensor * tensor;
  2517. llama_tensor_weights(uint16_t idx, const char * name, const struct gguf_context * gguf_ctx, ggml_tensor * tensor) : idx(idx), tensor(tensor) {
  2518. const int tensor_idx = gguf_find_tensor(gguf_ctx, name);
  2519. offs = gguf_get_data_offset(gguf_ctx) + gguf_get_tensor_offset(gguf_ctx, tensor_idx);
  2520. }
  2521. };
  2522. std::vector<llama_tensor_weights> weights;
  2523. std::unordered_map<std::string, struct llama_model_kv_override> kv_overrides;
  2524. struct gguf_context * meta = NULL;
  2525. std::vector<ggml_context *> contexts;
  2526. std::string arch_name;
  2527. LLM_KV llm_kv = LLM_KV(LLM_ARCH_UNKNOWN);
  2528. llama_model_loader(const std::string & fname, bool use_mmap, const struct llama_model_kv_override * param_overrides_p) {
  2529. int trace = 0;
  2530. if (getenv("LLAMA_TRACE")) {
  2531. trace = atoi(getenv("LLAMA_TRACE"));
  2532. }
  2533. if (param_overrides_p != nullptr) {
  2534. for (const struct llama_model_kv_override *p = param_overrides_p; p->key[0] != 0; p++) {
  2535. kv_overrides.insert({std::string(p->key), *p});
  2536. }
  2537. }
  2538. struct ggml_context * ctx = NULL;
  2539. struct gguf_init_params params = {
  2540. /*.no_alloc = */ true,
  2541. /*.ctx = */ &ctx,
  2542. };
  2543. meta = gguf_init_from_file(fname.c_str(), params);
  2544. if (!meta) {
  2545. throw std::runtime_error(format("%s: failed to load model from %s\n", __func__, fname.c_str()));
  2546. }
  2547. get_key(llm_kv(LLM_KV_GENERAL_ARCHITECTURE), arch_name, false);
  2548. llm_kv = LLM_KV(llm_arch_from_string(arch_name));
  2549. // Save tensors data offset of the main file.
  2550. // For subsidiary files, `meta` tensor data offset must not be used,
  2551. // so we build a unified tensors index for weights.
  2552. for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  2553. weights.emplace_back(llama_tensor_weights(0, cur->name, meta, cur));
  2554. }
  2555. files.emplace_back(new llama_file(fname.c_str(), "rb"));
  2556. contexts.emplace_back(ctx);
  2557. uint16_t n_split = 0;
  2558. get_key(llm_kv(LLM_KV_SPLIT_COUNT), n_split, false);
  2559. // Load additional GGML contexts
  2560. if (n_split > 1) {
  2561. uint16_t idx = 0;
  2562. get_key(llm_kv(LLM_KV_SPLIT_NO), idx);
  2563. if (idx != 0) {
  2564. throw std::runtime_error(format("illegal split file: %d, model must be loaded with the first split", idx));
  2565. }
  2566. char split_prefix[PATH_MAX] = {0};
  2567. if (!llama_split_prefix(split_prefix, sizeof(split_prefix), fname.c_str(), idx, n_split)) {
  2568. throw std::runtime_error(format("invalid split file: %s", fname.c_str()));
  2569. }
  2570. if (trace > 0) {
  2571. LLAMA_LOG_INFO("%s: loading additional %d GGUFs\n", __func__, n_split);
  2572. }
  2573. char split_path[PATH_MAX] = {0};
  2574. for (idx = 1; idx < n_split; idx++) {
  2575. llama_split_path(split_path, sizeof(split_path), split_prefix, idx, n_split);
  2576. struct gguf_init_params split_params = {
  2577. /*.no_alloc = */ true,
  2578. /*.ctx = */ &ctx,
  2579. };
  2580. struct gguf_context * ctx_gguf = gguf_init_from_file(split_path, split_params);
  2581. if (!ctx_gguf) {
  2582. throw std::runtime_error(format("%s: failed to load GGUF split from %s\n", __func__, split_path));
  2583. }
  2584. // Save tensors data offset info of the shard.
  2585. for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  2586. weights.emplace_back(llama_tensor_weights(idx, cur->name, ctx_gguf, cur));
  2587. }
  2588. files.emplace_back(new llama_file(split_path, "rb"));
  2589. contexts.emplace_back(ctx);
  2590. gguf_free(ctx_gguf);
  2591. }
  2592. get_key(llm_kv(LLM_KV_SPLIT_TENSORS_COUNT), n_tensors);
  2593. // sanity check
  2594. {
  2595. const int n_tensors_loaded = (int) weights.size();
  2596. if (n_tensors != n_tensors_loaded) {
  2597. throw std::runtime_error(format("corrupted model: %d tensors expected but %d found", n_tensors, n_tensors_loaded));
  2598. }
  2599. }
  2600. LLAMA_LOG_INFO("%s: additional %d GGUFs metadata loaded.\n", __func__, n_split - 1);
  2601. }
  2602. n_kv = gguf_get_n_kv(meta);
  2603. n_tensors = weights.size();
  2604. fver = (enum llama_fver) gguf_get_version(meta);
  2605. for (auto & w : weights) {
  2606. n_elements += ggml_nelements(w.tensor);
  2607. n_bytes += ggml_nbytes(w.tensor);
  2608. }
  2609. LLAMA_LOG_INFO("%s: loaded meta data with %d key-value pairs and %d tensors from %s (version %s)\n",
  2610. __func__, n_kv, n_tensors, fname.c_str(), llama_file_version_name(fver));
  2611. // determine file type based on the number of tensors for each quantization and print meta data
  2612. // TODO: make optional
  2613. {
  2614. std::map<enum ggml_type, uint32_t> n_type;
  2615. uint32_t n_type_max = 0;
  2616. enum ggml_type type_max = GGML_TYPE_F32;
  2617. for (int i = 0; i < n_tensors; i++) {
  2618. const ggml_tensor * tensor = weights.at(i).tensor;
  2619. enum ggml_type type = tensor->type;
  2620. n_type[type]++;
  2621. if (n_type_max < n_type[type]) {
  2622. n_type_max = n_type[type];
  2623. type_max = type;
  2624. }
  2625. if (trace > 0) {
  2626. const uint16_t sid = weights.at(i).idx;
  2627. 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());
  2628. }
  2629. }
  2630. switch (type_max) {
  2631. case GGML_TYPE_F32: ftype = LLAMA_FTYPE_ALL_F32; break;
  2632. case GGML_TYPE_F16: ftype = LLAMA_FTYPE_MOSTLY_F16; break;
  2633. case GGML_TYPE_Q4_0: ftype = LLAMA_FTYPE_MOSTLY_Q4_0; break;
  2634. case GGML_TYPE_Q4_1: ftype = LLAMA_FTYPE_MOSTLY_Q4_1; break;
  2635. case GGML_TYPE_Q5_0: ftype = LLAMA_FTYPE_MOSTLY_Q5_0; break;
  2636. case GGML_TYPE_Q5_1: ftype = LLAMA_FTYPE_MOSTLY_Q5_1; break;
  2637. case GGML_TYPE_Q8_0: ftype = LLAMA_FTYPE_MOSTLY_Q8_0; break;
  2638. case GGML_TYPE_Q2_K: ftype = LLAMA_FTYPE_MOSTLY_Q2_K; break;
  2639. case GGML_TYPE_Q3_K: ftype = LLAMA_FTYPE_MOSTLY_Q3_K_M; break;
  2640. case GGML_TYPE_Q4_K: ftype = LLAMA_FTYPE_MOSTLY_Q4_K_M; break;
  2641. case GGML_TYPE_Q5_K: ftype = LLAMA_FTYPE_MOSTLY_Q5_K_M; break;
  2642. case GGML_TYPE_Q6_K: ftype = LLAMA_FTYPE_MOSTLY_Q6_K; break;
  2643. case GGML_TYPE_IQ2_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XXS; break;
  2644. case GGML_TYPE_IQ2_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XS; break;
  2645. case GGML_TYPE_IQ2_S: ftype = LLAMA_FTYPE_MOSTLY_IQ2_S; break;
  2646. case GGML_TYPE_IQ3_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ3_XXS; break;
  2647. case GGML_TYPE_IQ1_S: ftype = LLAMA_FTYPE_MOSTLY_IQ1_S; break;
  2648. case GGML_TYPE_IQ1_M: ftype = LLAMA_FTYPE_MOSTLY_IQ1_M; break;
  2649. case GGML_TYPE_IQ4_NL: ftype = LLAMA_FTYPE_MOSTLY_IQ4_NL; break;
  2650. case GGML_TYPE_IQ4_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ4_XS; break;
  2651. case GGML_TYPE_IQ3_S: ftype = LLAMA_FTYPE_MOSTLY_IQ3_S; break;
  2652. default:
  2653. {
  2654. LLAMA_LOG_WARN("%s: unknown type %s\n", __func__, ggml_type_name(type_max));
  2655. ftype = LLAMA_FTYPE_ALL_F32;
  2656. } break;
  2657. }
  2658. // this is a way to mark that we have "guessed" the file type
  2659. ftype = (llama_ftype) (ftype | LLAMA_FTYPE_GUESSED);
  2660. {
  2661. const int kid = gguf_find_key(meta, "general.file_type");
  2662. if (kid >= 0) {
  2663. ftype = (llama_ftype) gguf_get_val_u32(meta, kid);
  2664. }
  2665. }
  2666. LLAMA_LOG_INFO("%s: Dumping metadata keys/values. Note: KV overrides do not apply in this output.\n", __func__);
  2667. for (int i = 0; i < n_kv; i++) {
  2668. const char * name = gguf_get_key(meta, i);
  2669. const enum gguf_type type = gguf_get_kv_type(meta, i);
  2670. const std::string type_name =
  2671. type == GGUF_TYPE_ARRAY
  2672. ? format("%s[%s,%d]", gguf_type_name(type), gguf_type_name(gguf_get_arr_type(meta, i)), gguf_get_arr_n(meta, i))
  2673. : gguf_type_name(type);
  2674. std::string value = gguf_kv_to_str(meta, i);
  2675. const size_t MAX_VALUE_LEN = 40;
  2676. if (value.size() > MAX_VALUE_LEN) {
  2677. value = format("%s...", value.substr(0, MAX_VALUE_LEN - 3).c_str());
  2678. }
  2679. replace_all(value, "\n", "\\n");
  2680. LLAMA_LOG_INFO("%s: - kv %3d: %42s %-16s = %s\n", __func__, i, name, type_name.c_str(), value.c_str());
  2681. }
  2682. // print type counts
  2683. for (auto & kv : n_type) {
  2684. if (kv.second == 0) {
  2685. continue;
  2686. }
  2687. LLAMA_LOG_INFO("%s: - type %4s: %4d tensors\n", __func__, ggml_type_name(kv.first), kv.second);
  2688. }
  2689. }
  2690. if (!llama_mmap::SUPPORTED) {
  2691. LLAMA_LOG_WARN("%s: mmap is not supported on this platform\n", __func__);
  2692. use_mmap = false;
  2693. }
  2694. this->use_mmap = use_mmap;
  2695. }
  2696. ~llama_model_loader() {
  2697. if (meta) {
  2698. gguf_free(meta);
  2699. }
  2700. for (auto * ctx : contexts) {
  2701. ggml_free(ctx);
  2702. }
  2703. }
  2704. template<typename T>
  2705. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2706. get_arr_n(const std::string & key, T & result, const bool required = true) {
  2707. const int kid = gguf_find_key(meta, key.c_str());
  2708. if (kid < 0) {
  2709. if (required) {
  2710. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2711. }
  2712. return false;
  2713. }
  2714. struct GGUFMeta::ArrayInfo arr_info =
  2715. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(meta, kid);
  2716. result = arr_info.length;
  2717. return true;
  2718. }
  2719. template<typename T>
  2720. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2721. get_arr_n(const enum llm_kv kid, T & result, const bool required = true) {
  2722. return get_arr_n(llm_kv(kid), result, required);
  2723. }
  2724. template<typename T>
  2725. bool get_key(const std::string & key, T & result, const bool required = true) {
  2726. auto it = kv_overrides.find(key);
  2727. const struct llama_model_kv_override * override =
  2728. it != kv_overrides.end() ? &it->second : nullptr;
  2729. const bool found = GGUFMeta::GKV<T>::set(meta, key, result, override);
  2730. if (required && !found) {
  2731. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2732. }
  2733. return found;
  2734. }
  2735. template<typename T>
  2736. bool get_key(const enum llm_kv kid, T & result, const bool required = true) {
  2737. return get_key(llm_kv(kid), result, required);
  2738. }
  2739. std::string get_arch_name() const {
  2740. return arch_name;
  2741. }
  2742. enum llm_arch get_arch() const {
  2743. return llm_kv.arch;
  2744. }
  2745. const char * get_tensor_name(int i) const {
  2746. return weights.at(i).tensor->name;
  2747. }
  2748. const llama_tensor_weights & get_weights(const char * name) const {
  2749. for (const auto & weight : weights) {
  2750. if (strcmp(name, weight.tensor->name) == 0) {
  2751. return weight;
  2752. }
  2753. }
  2754. throw std::runtime_error(format("tensor %s not found", name));
  2755. }
  2756. struct ggml_tensor * get_tensor_meta(const char * name) const {
  2757. try {
  2758. return get_weights(name).tensor;
  2759. } catch (const std::runtime_error & e) {
  2760. return NULL;
  2761. }
  2762. }
  2763. struct ggml_tensor * get_tensor_meta(int i) const {
  2764. return get_tensor_meta(get_tensor_name(i));
  2765. }
  2766. struct ggml_tensor * create_tensor_for(struct ggml_context * ctx, const struct ggml_tensor * cur) {
  2767. struct ggml_tensor * tensor = ggml_dup_tensor(ctx, cur);
  2768. ggml_set_name(tensor, ggml_get_name(cur));
  2769. n_created++;
  2770. return tensor;
  2771. }
  2772. struct ggml_tensor * create_tensor(struct ggml_context * ctx, const std::string & name, const std::vector<int64_t> & ne, bool required = true) {
  2773. const struct ggml_tensor * cur = get_tensor_meta(name.c_str());
  2774. if (cur == NULL) {
  2775. if (!required) {
  2776. return NULL;
  2777. }
  2778. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
  2779. }
  2780. {
  2781. bool is_ok = true;
  2782. for (size_t i = 0; i < ne.size(); ++i) {
  2783. if (ne[i] != cur->ne[i]) {
  2784. is_ok = false;
  2785. break;
  2786. }
  2787. }
  2788. if (!is_ok) {
  2789. throw std::runtime_error(
  2790. format("%s: tensor '%s' has wrong shape; expected %s, got %s",
  2791. __func__, name.c_str(),
  2792. llama_format_tensor_shape(ne).c_str(),
  2793. llama_format_tensor_shape(cur).c_str()));
  2794. }
  2795. }
  2796. return create_tensor_for(ctx, cur);
  2797. }
  2798. void done_getting_tensors() const {
  2799. if (n_created != n_tensors) {
  2800. throw std::runtime_error(format("%s: wrong number of tensors; expected %d, got %d", __func__, n_tensors, n_created));
  2801. }
  2802. }
  2803. void init_mappings(bool prefetch = true, llama_mlocks * mlock_mmaps = nullptr) {
  2804. if (use_mmap) {
  2805. mappings.reserve(files.size());
  2806. mmaps_used.reserve(files.size());
  2807. for (const auto & file : files) {
  2808. std::unique_ptr<llama_mmap> mapping(new llama_mmap(file.get(), prefetch ? -1 : 0, ggml_is_numa()));
  2809. mmaps_used.emplace_back(std::make_pair(mapping->size, 0));
  2810. if (mlock_mmaps) {
  2811. std::unique_ptr<llama_mlock> mlock_mmap(new llama_mlock());
  2812. mlock_mmap->init(mapping->addr);
  2813. mlock_mmaps->emplace_back(std::move(mlock_mmap));
  2814. }
  2815. mappings.emplace_back(std::move(mapping));
  2816. }
  2817. }
  2818. // compute the total size of all tensors for progress reporting
  2819. for (auto & w : weights) {
  2820. size_data += ggml_nbytes(w.tensor);
  2821. }
  2822. }
  2823. void get_mapping_range(size_t * first, size_t * last, void ** addr, int idx, ggml_context * ctx) const {
  2824. GGML_ASSERT(!mappings.empty());
  2825. const auto & mapping = mappings.at(idx);
  2826. *first = mapping->size;
  2827. *last = 0;
  2828. *addr = mapping->addr;
  2829. for (ggml_tensor * tensor = ggml_get_first_tensor(ctx); tensor; tensor = ggml_get_next_tensor(ctx, tensor)) {
  2830. const auto & w = get_weights(ggml_get_name(tensor));
  2831. if (w.idx != idx) {
  2832. continue;
  2833. }
  2834. *first = std::min(*first, w.offs);
  2835. *last = std::max(*last, w.offs + ggml_nbytes(tensor));
  2836. }
  2837. }
  2838. // for backwards compatibility, does not support ggml-backend
  2839. void load_data_for(struct ggml_tensor * cur) const {
  2840. const auto & w = get_weights(ggml_get_name(cur));
  2841. if (use_mmap) {
  2842. const auto & mapping = mappings.at(w.idx);
  2843. if (cur->data == nullptr) {
  2844. cur->data = (uint8_t *)mapping->addr + w.offs;
  2845. } else {
  2846. memcpy(cur->data, (uint8_t *)mapping->addr + w.offs, ggml_nbytes(cur));
  2847. }
  2848. } else {
  2849. GGML_ASSERT(cur->data != nullptr);
  2850. GGML_ASSERT(w.idx < files.size());
  2851. const auto & file = files.at(w.idx);
  2852. file->seek(w.offs, SEEK_SET);
  2853. file->read_raw(cur->data, ggml_nbytes(cur));
  2854. }
  2855. }
  2856. size_t size_done = 0;
  2857. size_t size_data = 0;
  2858. std::vector<std::pair<size_t, size_t>> mmaps_used;
  2859. // Returns false if cancelled by progress_callback
  2860. bool load_all_data(
  2861. struct ggml_context * ctx,
  2862. llama_buf_map & bufs_mmap,
  2863. llama_mlocks * lmlocks,
  2864. llama_progress_callback progress_callback,
  2865. void * progress_callback_user_data) {
  2866. GGML_ASSERT(size_data != 0 && "call init_mappings() first");
  2867. std::vector<no_init<uint8_t>> read_buf;
  2868. for (struct ggml_tensor * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  2869. if (progress_callback) {
  2870. if (!progress_callback((float) size_done / size_data, progress_callback_user_data)) {
  2871. return false;
  2872. }
  2873. }
  2874. const auto & w = get_weights(ggml_get_name(cur));
  2875. size_t n_size = ggml_nbytes(cur);
  2876. if (use_mmap) {
  2877. const auto & mapping = mappings.at(w.idx);
  2878. ggml_backend_buffer_t buf_mmap = nullptr;
  2879. if (bufs_mmap.count(w.idx)) {
  2880. buf_mmap = bufs_mmap.at(w.idx);
  2881. }
  2882. GGML_ASSERT(buf_mmap || cur->data); // either we have a buffer to allocate the tensor in, or it is already allocated
  2883. if (buf_mmap && cur->data == nullptr) {
  2884. ggml_backend_tensor_alloc(buf_mmap, cur, (uint8_t *) mapping->addr + w.offs);
  2885. if (lmlocks) {
  2886. const auto & lmlock = lmlocks->at(w.idx);
  2887. lmlock->grow_to(w.offs + ggml_nbytes(cur));
  2888. }
  2889. auto & mmap_used = mmaps_used[w.idx];
  2890. mmap_used.first = std::min(mmap_used.first, w.offs);
  2891. mmap_used.second = std::max(mmap_used.second, w.offs + n_size);
  2892. } else {
  2893. ggml_backend_tensor_set(cur, (uint8_t *) mapping->addr + w.offs, 0, n_size);
  2894. }
  2895. } else {
  2896. GGML_ASSERT(w.idx < files.size());
  2897. const auto & file = files.at(w.idx);
  2898. if (ggml_backend_buffer_is_host(cur->buffer)) {
  2899. file->seek(w.offs, SEEK_SET);
  2900. file->read_raw(cur->data, ggml_nbytes(cur));
  2901. } else {
  2902. read_buf.resize(ggml_nbytes(cur));
  2903. file->seek(w.offs, SEEK_SET);
  2904. file->read_raw(read_buf.data(), ggml_nbytes(cur));
  2905. ggml_backend_tensor_set(cur, read_buf.data(), 0, n_size);
  2906. }
  2907. }
  2908. size_done += n_size;
  2909. }
  2910. // check if this is the last call and do final cleanup
  2911. if (size_done >= size_data) {
  2912. // unmap offloaded tensors and metadata
  2913. if (use_mmap) {
  2914. for (uint32_t idx = 0; idx < mappings.size(); idx++) {
  2915. const auto & mmap_used = mmaps_used.at(idx);
  2916. auto & mapping = mappings.at(idx);
  2917. mapping->unmap_fragment(0, mmap_used.first);
  2918. if (mmap_used.second != 0) {
  2919. mapping->unmap_fragment(mmap_used.second, mapping->size);
  2920. }
  2921. }
  2922. }
  2923. if (progress_callback) {
  2924. // Even though the model is done loading, we still honor
  2925. // cancellation since we need to free allocations.
  2926. return progress_callback(1.0f, progress_callback_user_data);
  2927. }
  2928. }
  2929. return true;
  2930. }
  2931. };
  2932. template<>
  2933. bool llama_model_loader::get_key(const enum llm_kv kid, enum llama_pooling_type & result, const bool required) {
  2934. uint32_t tmp;
  2935. const bool found = get_key(kid, tmp, required);
  2936. if (found) {
  2937. result = (enum llama_pooling_type) tmp;
  2938. } else {
  2939. result = LLAMA_POOLING_TYPE_UNSPECIFIED;
  2940. }
  2941. return found;
  2942. }
  2943. //
  2944. // load LLaMA models
  2945. //
  2946. static const char * llama_model_arch_name(llm_arch arch) {
  2947. auto it = LLM_ARCH_NAMES.find(arch);
  2948. if (it == LLM_ARCH_NAMES.end()) {
  2949. return "unknown";
  2950. }
  2951. return it->second;
  2952. }
  2953. static std::string llama_model_ftype_name(llama_ftype ftype) {
  2954. if (ftype & LLAMA_FTYPE_GUESSED) {
  2955. return llama_model_ftype_name((enum llama_ftype) (ftype & ~LLAMA_FTYPE_GUESSED)) + " (guessed)";
  2956. }
  2957. switch (ftype) {
  2958. case LLAMA_FTYPE_ALL_F32: return "all F32";
  2959. case LLAMA_FTYPE_MOSTLY_F16: return "F16";
  2960. case LLAMA_FTYPE_MOSTLY_Q4_0: return "Q4_0";
  2961. case LLAMA_FTYPE_MOSTLY_Q4_1: return "Q4_1";
  2962. case LLAMA_FTYPE_MOSTLY_Q4_1_SOME_F16:
  2963. return "Q4_1, some F16";
  2964. case LLAMA_FTYPE_MOSTLY_Q5_0: return "Q5_0";
  2965. case LLAMA_FTYPE_MOSTLY_Q5_1: return "Q5_1";
  2966. case LLAMA_FTYPE_MOSTLY_Q8_0: return "Q8_0";
  2967. // K-quants
  2968. case LLAMA_FTYPE_MOSTLY_Q2_K: return "Q2_K - Medium";
  2969. case LLAMA_FTYPE_MOSTLY_Q2_K_S: return "Q2_K - Small";
  2970. case LLAMA_FTYPE_MOSTLY_Q3_K_S: return "Q3_K - Small";
  2971. case LLAMA_FTYPE_MOSTLY_Q3_K_M: return "Q3_K - Medium";
  2972. case LLAMA_FTYPE_MOSTLY_Q3_K_L: return "Q3_K - Large";
  2973. case LLAMA_FTYPE_MOSTLY_Q4_K_S: return "Q4_K - Small";
  2974. case LLAMA_FTYPE_MOSTLY_Q4_K_M: return "Q4_K - Medium";
  2975. case LLAMA_FTYPE_MOSTLY_Q5_K_S: return "Q5_K - Small";
  2976. case LLAMA_FTYPE_MOSTLY_Q5_K_M: return "Q5_K - Medium";
  2977. case LLAMA_FTYPE_MOSTLY_Q6_K: return "Q6_K";
  2978. case LLAMA_FTYPE_MOSTLY_IQ2_XXS:return "IQ2_XXS - 2.0625 bpw";
  2979. case LLAMA_FTYPE_MOSTLY_IQ2_XS: return "IQ2_XS - 2.3125 bpw";
  2980. case LLAMA_FTYPE_MOSTLY_IQ2_S: return "IQ2_S - 2.5 bpw";
  2981. case LLAMA_FTYPE_MOSTLY_IQ2_M: return "IQ2_M - 2.7 bpw";
  2982. case LLAMA_FTYPE_MOSTLY_IQ3_XS: return "IQ3_XS - 3.3 bpw";
  2983. case LLAMA_FTYPE_MOSTLY_IQ3_XXS:return "IQ3_XXS - 3.0625 bpw";
  2984. case LLAMA_FTYPE_MOSTLY_IQ1_S :return "IQ1_S - 1.5625 bpw";
  2985. case LLAMA_FTYPE_MOSTLY_IQ1_M :return "IQ1_M - 1.75 bpw";
  2986. case LLAMA_FTYPE_MOSTLY_IQ4_NL: return "IQ4_NL - 4.5 bpw";
  2987. case LLAMA_FTYPE_MOSTLY_IQ4_XS: return "IQ4_XS - 4.25 bpw";
  2988. case LLAMA_FTYPE_MOSTLY_IQ3_S: return "IQ3_S - 3.4375 bpw";
  2989. case LLAMA_FTYPE_MOSTLY_IQ3_M: return "IQ3_S mix - 3.66 bpw";
  2990. default: return "unknown, may not work";
  2991. }
  2992. }
  2993. static const char * llama_model_type_name(e_model type) {
  2994. switch (type) {
  2995. case MODEL_22M: return "22M";
  2996. case MODEL_33M: return "33M";
  2997. case MODEL_109M: return "109M";
  2998. case MODEL_137M: return "137M";
  2999. case MODEL_0_5B: return "0.5B";
  3000. case MODEL_1B: return "1B";
  3001. case MODEL_2B: return "2B";
  3002. case MODEL_3B: return "3B";
  3003. case MODEL_7B: return "7B";
  3004. case MODEL_8B: return "8B";
  3005. case MODEL_13B: return "13B";
  3006. case MODEL_14B: return "14B";
  3007. case MODEL_15B: return "15B";
  3008. case MODEL_20B: return "20B";
  3009. case MODEL_30B: return "30B";
  3010. case MODEL_34B: return "34B";
  3011. case MODEL_35B: return "35B";
  3012. case MODEL_40B: return "40B";
  3013. case MODEL_65B: return "65B";
  3014. case MODEL_70B: return "70B";
  3015. case MODEL_314B: return "314B";
  3016. case MODEL_SMALL: return "0.1B";
  3017. case MODEL_MEDIUM: return "0.4B";
  3018. case MODEL_LARGE: return "0.8B";
  3019. case MODEL_XL: return "1.5B";
  3020. default: return "?B";
  3021. }
  3022. }
  3023. static const char * llama_model_vocab_type_name(enum llama_vocab_type type){
  3024. switch (type) {
  3025. case LLAMA_VOCAB_TYPE_NONE: return "no vocab";
  3026. case LLAMA_VOCAB_TYPE_SPM: return "SPM";
  3027. case LLAMA_VOCAB_TYPE_BPE: return "BPE";
  3028. case LLAMA_VOCAB_TYPE_WPM: return "WPM";
  3029. default: return "unknown";
  3030. }
  3031. }
  3032. static void llm_load_arch(llama_model_loader & ml, llama_model & model) {
  3033. model.arch = ml.get_arch();
  3034. if (model.arch == LLM_ARCH_UNKNOWN) {
  3035. throw std::runtime_error("unknown model architecture: '" + ml.get_arch_name() + "'");
  3036. }
  3037. }
  3038. static void llm_load_hparams(
  3039. llama_model_loader & ml,
  3040. llama_model & model) {
  3041. auto & hparams = model.hparams;
  3042. const gguf_context * ctx = ml.meta;
  3043. // get metadata as string
  3044. for (int i = 0; i < gguf_get_n_kv(ctx); i++) {
  3045. enum gguf_type type = gguf_get_kv_type(ctx, i);
  3046. if (type == GGUF_TYPE_ARRAY) {
  3047. continue;
  3048. }
  3049. const char * name = gguf_get_key(ctx, i);
  3050. const std::string value = gguf_kv_to_str(ctx, i);
  3051. model.gguf_kv.emplace(name, value);
  3052. }
  3053. // get general kv
  3054. ml.get_key(LLM_KV_GENERAL_NAME, model.name, false);
  3055. // get hparams kv
  3056. ml.get_key(LLM_KV_VOCAB_SIZE, hparams.n_vocab, false) || ml.get_arr_n(LLM_KV_TOKENIZER_LIST, hparams.n_vocab);
  3057. ml.get_key(LLM_KV_CONTEXT_LENGTH, hparams.n_ctx_train);
  3058. ml.get_key(LLM_KV_EMBEDDING_LENGTH, hparams.n_embd);
  3059. ml.get_key(LLM_KV_FEED_FORWARD_LENGTH, hparams.n_ff);
  3060. ml.get_key(LLM_KV_ATTENTION_HEAD_COUNT, hparams.n_head);
  3061. ml.get_key(LLM_KV_BLOCK_COUNT, hparams.n_layer);
  3062. ml.get_key(LLM_KV_EXPERT_COUNT, hparams.n_expert, false);
  3063. ml.get_key(LLM_KV_EXPERT_USED_COUNT, hparams.n_expert_used, false);
  3064. GGML_ASSERT(hparams.n_expert <= LLAMA_MAX_EXPERTS);
  3065. GGML_ASSERT(hparams.n_expert_used <= hparams.n_expert);
  3066. if (hparams.n_expert > 0) {
  3067. GGML_ASSERT(hparams.n_expert_used > 0);
  3068. } else {
  3069. GGML_ASSERT(hparams.n_expert_used == 0);
  3070. }
  3071. // n_head_kv is optional, default to n_head
  3072. hparams.n_head_kv = hparams.n_head;
  3073. ml.get_key(LLM_KV_ATTENTION_HEAD_COUNT_KV, hparams.n_head_kv, false);
  3074. bool rope_finetuned = false;
  3075. ml.get_key(LLM_KV_ROPE_SCALING_FINETUNED, rope_finetuned, false);
  3076. hparams.rope_finetuned = rope_finetuned;
  3077. hparams.n_yarn_orig_ctx = hparams.n_ctx_train;
  3078. ml.get_key(LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, hparams.n_yarn_orig_ctx, false);
  3079. // rope_freq_base (optional)
  3080. hparams.rope_freq_base_train = 10000.0f;
  3081. ml.get_key(LLM_KV_ROPE_FREQ_BASE, hparams.rope_freq_base_train, false);
  3082. std::string rope_scaling("linear");
  3083. ml.get_key(LLM_KV_ROPE_SCALING_TYPE, rope_scaling, false);
  3084. hparams.rope_scaling_type_train = llama_rope_scaling_type_from_string(rope_scaling);
  3085. GGML_ASSERT(hparams.rope_scaling_type_train != LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED);
  3086. // rope_freq_scale (inverse of the kv) is optional
  3087. float ropescale = 0.0f;
  3088. if (!ml.get_key(LLM_KV_ROPE_SCALING_FACTOR, ropescale, false)) {
  3089. // try the old key name
  3090. ml.get_key(LLM_KV_ROPE_SCALE_LINEAR, ropescale, false);
  3091. }
  3092. hparams.rope_freq_scale_train = ropescale == 0.0f ? 1.0f : 1.0f/ropescale;
  3093. // sanity check for n_rot (optional)
  3094. {
  3095. hparams.n_rot = (hparams.n_head == 0) ? 0 : hparams.n_embd / hparams.n_head;
  3096. ml.get_key(LLM_KV_ROPE_DIMENSION_COUNT, hparams.n_rot, false);
  3097. if (model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON) {
  3098. if (hparams.n_rot != hparams.n_embd / hparams.n_head) {
  3099. throw std::runtime_error(format("invalid n_rot: %u, expected %u", hparams.n_rot, hparams.n_embd / hparams.n_head));
  3100. }
  3101. }
  3102. // gpt-neox n_rot = rotary_pct * (n_embd / n_head)
  3103. // gpt-j n_rot = rotary_dim
  3104. }
  3105. hparams.n_embd_head_k = (hparams.n_head == 0) ? 0 : hparams.n_embd / hparams.n_head;
  3106. ml.get_key(LLM_KV_ATTENTION_KEY_LENGTH, hparams.n_embd_head_k, false);
  3107. hparams.n_embd_head_v = (hparams.n_head == 0) ? 0 : hparams.n_embd / hparams.n_head;
  3108. ml.get_key(LLM_KV_ATTENTION_VALUE_LENGTH, hparams.n_embd_head_v, false);
  3109. // arch-specific KVs
  3110. switch (model.arch) {
  3111. case LLM_ARCH_LLAMA:
  3112. {
  3113. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3114. switch (hparams.n_layer) {
  3115. case 22: model.type = e_model::MODEL_1B; break;
  3116. case 26: model.type = e_model::MODEL_3B; break;
  3117. case 32: model.type = e_model::MODEL_7B; break;
  3118. case 40: model.type = e_model::MODEL_13B; break;
  3119. case 48: model.type = e_model::MODEL_34B; break;
  3120. case 60: model.type = e_model::MODEL_30B; break;
  3121. case 80: model.type = hparams.n_head == hparams.n_head_kv ? e_model::MODEL_65B : e_model::MODEL_70B; break;
  3122. default: model.type = e_model::MODEL_UNKNOWN;
  3123. }
  3124. } break;
  3125. case LLM_ARCH_MINICPM:
  3126. {
  3127. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3128. switch (hparams.n_layer) {
  3129. case 40: model.type = e_model::MODEL_2B; break;
  3130. default: model.type = e_model::MODEL_UNKNOWN;
  3131. }
  3132. } break;
  3133. case LLM_ARCH_GROK:
  3134. {
  3135. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3136. switch (hparams.n_layer) {
  3137. case 64: model.type = e_model::MODEL_314B; break;
  3138. default: model.type = e_model::MODEL_UNKNOWN;
  3139. }
  3140. } break;
  3141. case LLM_ARCH_FALCON:
  3142. {
  3143. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3144. switch (hparams.n_layer) {
  3145. case 32: model.type = e_model::MODEL_7B; break;
  3146. case 60: model.type = e_model::MODEL_40B; break;
  3147. default: model.type = e_model::MODEL_UNKNOWN;
  3148. }
  3149. } break;
  3150. case LLM_ARCH_BAICHUAN:
  3151. {
  3152. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3153. switch (hparams.n_layer) {
  3154. case 32: model.type = e_model::MODEL_7B; break;
  3155. case 40: model.type = e_model::MODEL_13B; break;
  3156. default: model.type = e_model::MODEL_UNKNOWN;
  3157. }
  3158. if (model.type == e_model::MODEL_13B) {
  3159. // TODO: become GGUF KV parameter
  3160. hparams.f_max_alibi_bias = 8.0f;
  3161. }
  3162. } break;
  3163. case LLM_ARCH_STARCODER:
  3164. {
  3165. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3166. switch (hparams.n_layer) {
  3167. case 24: model.type = e_model::MODEL_1B; break;
  3168. case 36: model.type = e_model::MODEL_3B; break;
  3169. case 42: model.type = e_model::MODEL_7B; break;
  3170. case 40: model.type = e_model::MODEL_15B; break;
  3171. default: model.type = e_model::MODEL_UNKNOWN;
  3172. }
  3173. } break;
  3174. case LLM_ARCH_PERSIMMON:
  3175. {
  3176. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3177. switch (hparams.n_layer) {
  3178. case 36: model.type = e_model::MODEL_8B; break;
  3179. default: model.type = e_model::MODEL_UNKNOWN;
  3180. }
  3181. } break;
  3182. case LLM_ARCH_REFACT:
  3183. {
  3184. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3185. switch (hparams.n_layer) {
  3186. case 32: model.type = e_model::MODEL_1B; break;
  3187. default: model.type = e_model::MODEL_UNKNOWN;
  3188. }
  3189. // TODO: become GGUF KV parameter
  3190. hparams.f_max_alibi_bias = 8.0f;
  3191. } break;
  3192. case LLM_ARCH_BERT:
  3193. {
  3194. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3195. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  3196. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  3197. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type, false);
  3198. switch (hparams.n_layer) {
  3199. case 3:
  3200. model.type = e_model::MODEL_17M; break; // bge-micro
  3201. case 6:
  3202. model.type = e_model::MODEL_22M; break; // MiniLM-L6
  3203. case 12:
  3204. switch (hparams.n_embd) {
  3205. case 384: model.type = e_model::MODEL_33M; break; // MiniLM-L12, bge-small
  3206. case 768: model.type = e_model::MODEL_109M; break; // bge-base
  3207. } break;
  3208. case 24:
  3209. model.type = e_model::MODEL_335M; break; // bge-large
  3210. }
  3211. } break;
  3212. case LLM_ARCH_NOMIC_BERT:
  3213. {
  3214. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3215. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  3216. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  3217. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type);
  3218. if (hparams.n_layer == 12 && hparams.n_embd == 768) {
  3219. model.type = e_model::MODEL_137M;
  3220. }
  3221. } break;
  3222. case LLM_ARCH_BLOOM:
  3223. {
  3224. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3225. switch (hparams.n_layer) {
  3226. case 24: model.type = e_model::MODEL_1B; break;
  3227. case 30:
  3228. switch (hparams.n_embd) {
  3229. case 2560: model.type = e_model::MODEL_3B; break;
  3230. case 4096: model.type = e_model::MODEL_7B; break;
  3231. } break;
  3232. }
  3233. // TODO: become GGUF KV parameter
  3234. hparams.f_max_alibi_bias = 8.0f;
  3235. } break;
  3236. case LLM_ARCH_MPT:
  3237. {
  3238. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3239. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv, false);
  3240. ml.get_key(LLM_KV_ATTENTION_MAX_ALIBI_BIAS, hparams.f_max_alibi_bias);
  3241. switch (hparams.n_layer) {
  3242. case 32: model.type = e_model::MODEL_7B; break;
  3243. case 48: model.type = e_model::MODEL_30B; break;
  3244. default: model.type = e_model::MODEL_UNKNOWN;
  3245. }
  3246. } break;
  3247. case LLM_ARCH_STABLELM:
  3248. {
  3249. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3250. switch (hparams.n_layer) {
  3251. case 24: model.type = e_model::MODEL_1B; break;
  3252. case 32: model.type = e_model::MODEL_3B; break;
  3253. default: model.type = e_model::MODEL_UNKNOWN;
  3254. }
  3255. } break;
  3256. case LLM_ARCH_QWEN:
  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. } break;
  3265. case LLM_ARCH_QWEN2:
  3266. {
  3267. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3268. switch (hparams.n_layer) {
  3269. case 24: model.type = hparams.n_embd == 1024 ? e_model::MODEL_0_5B : e_model::MODEL_1B; break;
  3270. case 32: model.type = e_model::MODEL_7B; break;
  3271. case 40: model.type = hparams.n_head == 20 ? e_model::MODEL_4B : e_model::MODEL_13B; break;
  3272. case 80: model.type = e_model::MODEL_70B; break;
  3273. default: model.type = e_model::MODEL_UNKNOWN;
  3274. }
  3275. } break;
  3276. case LLM_ARCH_PHI2:
  3277. {
  3278. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3279. switch (hparams.n_layer) {
  3280. case 24: model.type = e_model::MODEL_1B; break;
  3281. case 32: model.type = e_model::MODEL_3B; break;
  3282. default: model.type = e_model::MODEL_UNKNOWN;
  3283. }
  3284. } break;
  3285. case LLM_ARCH_PLAMO:
  3286. {
  3287. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3288. switch (hparams.n_layer) {
  3289. case 40: model.type = e_model::MODEL_13B; break;
  3290. default: model.type = e_model::MODEL_UNKNOWN;
  3291. }
  3292. } break;
  3293. case LLM_ARCH_GPT2:
  3294. {
  3295. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3296. switch (hparams.n_layer) {
  3297. case 12: model.type = e_model::MODEL_SMALL; break;
  3298. case 24: model.type = e_model::MODEL_MEDIUM; break;
  3299. case 36: model.type = e_model::MODEL_LARGE; break;
  3300. case 48: model.type = e_model::MODEL_XL; break;
  3301. default: model.type = e_model::MODEL_UNKNOWN;
  3302. }
  3303. } break;
  3304. case LLM_ARCH_CODESHELL:
  3305. {
  3306. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3307. switch (hparams.n_layer) {
  3308. case 42: model.type = e_model::MODEL_SMALL; break;
  3309. default: model.type = e_model::MODEL_UNKNOWN;
  3310. }
  3311. } break;
  3312. case LLM_ARCH_ORION:
  3313. {
  3314. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3315. switch (hparams.n_layer) {
  3316. case 40: model.type = e_model::MODEL_14B; break;
  3317. default: model.type = e_model::MODEL_UNKNOWN;
  3318. }
  3319. } break;
  3320. case LLM_ARCH_INTERNLM2:
  3321. {
  3322. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3323. switch (hparams.n_layer) {
  3324. case 32: model.type = e_model::MODEL_7B; break;
  3325. case 48: model.type = e_model::MODEL_20B; break;
  3326. default: model.type = e_model::MODEL_UNKNOWN;
  3327. }
  3328. } break;
  3329. case LLM_ARCH_GEMMA:
  3330. {
  3331. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3332. switch (hparams.n_layer) {
  3333. case 18: model.type = e_model::MODEL_2B; break;
  3334. case 28: model.type = e_model::MODEL_7B; break;
  3335. default: model.type = e_model::MODEL_UNKNOWN;
  3336. }
  3337. } break;
  3338. case LLM_ARCH_STARCODER2:
  3339. {
  3340. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3341. switch (hparams.n_layer) {
  3342. case 30: model.type = e_model::MODEL_3B; break;
  3343. case 32: model.type = e_model::MODEL_7B; break;
  3344. case 40: model.type = e_model::MODEL_15B; break;
  3345. default: model.type = e_model::MODEL_UNKNOWN;
  3346. }
  3347. } break;
  3348. case LLM_ARCH_MAMBA:
  3349. {
  3350. ml.get_key(LLM_KV_SSM_CONV_KERNEL, hparams.ssm_d_conv);
  3351. ml.get_key(LLM_KV_SSM_INNER_SIZE, hparams.ssm_d_inner);
  3352. ml.get_key(LLM_KV_SSM_STATE_SIZE, hparams.ssm_d_state);
  3353. ml.get_key(LLM_KV_SSM_TIME_STEP_RANK, hparams.ssm_dt_rank);
  3354. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3355. switch (hparams.n_layer) {
  3356. case 24:
  3357. switch (hparams.n_embd) {
  3358. case 768: model.type = e_model::MODEL_SMALL; break;
  3359. default: model.type = e_model::MODEL_UNKNOWN;
  3360. } break;
  3361. case 48:
  3362. switch (hparams.n_embd) {
  3363. case 1024: model.type = e_model::MODEL_MEDIUM; break;
  3364. case 1536: model.type = e_model::MODEL_LARGE; break;
  3365. case 2048: model.type = e_model::MODEL_XL; break;
  3366. default: model.type = e_model::MODEL_UNKNOWN;
  3367. } break;
  3368. case 64:
  3369. switch (hparams.n_embd) {
  3370. case 2560: model.type = e_model::MODEL_3B; break;
  3371. default: model.type = e_model::MODEL_UNKNOWN;
  3372. } break;
  3373. default: model.type = e_model::MODEL_UNKNOWN;
  3374. }
  3375. } break;
  3376. case LLM_ARCH_XVERSE:
  3377. {
  3378. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3379. switch (hparams.n_layer) {
  3380. case 32: model.type = e_model::MODEL_7B; break;
  3381. case 40: model.type = e_model::MODEL_13B; break;
  3382. case 80: model.type = e_model::MODEL_65B; break;
  3383. default: model.type = e_model::MODEL_UNKNOWN;
  3384. }
  3385. } break;
  3386. case LLM_ARCH_COMMAND_R:
  3387. {
  3388. ml.get_key(LLM_KV_LOGIT_SCALE, hparams.f_logit_scale);
  3389. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3390. switch (hparams.n_layer) {
  3391. case 40: model.type = e_model::MODEL_35B; break;
  3392. default: model.type = e_model::MODEL_UNKNOWN;
  3393. }
  3394. } break;
  3395. default: (void)0;
  3396. }
  3397. model.ftype = ml.ftype;
  3398. if (hparams.f_max_alibi_bias > 0.0f) {
  3399. hparams.need_kq_pos = true;
  3400. }
  3401. hparams.rope_type = llama_rope_type(&model);
  3402. }
  3403. // TODO: This should probably be in llama.h
  3404. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special = false);
  3405. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch);
  3406. static void llm_load_vocab(
  3407. llama_model_loader & ml,
  3408. llama_model & model) {
  3409. auto & vocab = model.vocab;
  3410. struct gguf_context * ctx = ml.meta;
  3411. const auto kv = LLM_KV(model.arch);
  3412. // determine vocab type
  3413. {
  3414. std::string tokenizer_name;
  3415. ml.get_key(LLM_KV_TOKENIZER_MODEL, tokenizer_name);
  3416. if (tokenizer_name == "no_vocab") {
  3417. vocab.type = LLAMA_VOCAB_TYPE_NONE;
  3418. // default special tokens
  3419. vocab.special_bos_id = -1;
  3420. vocab.special_eos_id = -1;
  3421. vocab.special_unk_id = -1;
  3422. vocab.special_sep_id = -1;
  3423. vocab.special_pad_id = -1;
  3424. vocab.linefeed_id = -1;
  3425. return;
  3426. } else if (tokenizer_name == "llama") {
  3427. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  3428. // default special tokens
  3429. vocab.special_bos_id = 1;
  3430. vocab.special_eos_id = 2;
  3431. vocab.special_unk_id = 0;
  3432. vocab.special_sep_id = -1;
  3433. vocab.special_pad_id = -1;
  3434. const int add_space_prefix_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_ADD_PREFIX).c_str());
  3435. if (add_space_prefix_keyidx != -1) {
  3436. vocab.add_space_prefix = gguf_get_val_bool(ctx, add_space_prefix_keyidx);
  3437. } // The default value of add_space_prefix is true.
  3438. } else if (tokenizer_name == "gpt2") {
  3439. vocab.type = LLAMA_VOCAB_TYPE_BPE;
  3440. // read bpe merges and populate bpe ranks
  3441. const int merges_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_MERGES).c_str());
  3442. if (merges_keyidx == -1) {
  3443. throw std::runtime_error("cannot find tokenizer merges in model file\n");
  3444. }
  3445. const int n_merges = gguf_get_arr_n(ctx, merges_keyidx);
  3446. for (int i = 0; i < n_merges; i++) {
  3447. const std::string word = gguf_get_arr_str(ctx, merges_keyidx, i);
  3448. GGML_ASSERT(unicode_cpts_from_utf8(word).size() > 0);
  3449. std::string first;
  3450. std::string second;
  3451. const size_t pos = word.find(' ', 1);
  3452. if (pos != std::string::npos) {
  3453. first = word.substr(0, pos);
  3454. second = word.substr(pos + 1);
  3455. }
  3456. vocab.bpe_ranks.emplace(std::make_pair(first, second), i);
  3457. }
  3458. // default special tokens
  3459. vocab.special_bos_id = 11;
  3460. vocab.special_eos_id = 11;
  3461. vocab.special_unk_id = -1;
  3462. vocab.special_sep_id = -1;
  3463. vocab.special_pad_id = -1;
  3464. } else if (tokenizer_name == "bert") {
  3465. vocab.type = LLAMA_VOCAB_TYPE_WPM;
  3466. // default special tokens
  3467. vocab.special_bos_id = 101;
  3468. vocab.special_eos_id = 102;
  3469. vocab.special_unk_id = 100;
  3470. vocab.special_sep_id = -1;
  3471. vocab.special_pad_id = -1;
  3472. vocab.add_space_prefix = false;
  3473. } else {
  3474. LLAMA_LOG_WARN("%s: unknown tokenizer: '%s'", __func__, tokenizer_name.c_str());
  3475. LLAMA_LOG_WARN("%s: using default tokenizer: 'llama'", __func__);
  3476. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  3477. }
  3478. }
  3479. const int token_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_LIST).c_str());
  3480. if (token_idx == -1) {
  3481. throw std::runtime_error("cannot find tokenizer vocab in model file\n");
  3482. }
  3483. const float * scores = nullptr;
  3484. const int score_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_SCORES).c_str());
  3485. if (score_idx != -1) {
  3486. scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
  3487. }
  3488. const int * toktypes = nullptr;
  3489. const int toktype_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE).c_str());
  3490. if (toktype_idx != -1) {
  3491. toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
  3492. }
  3493. const uint32_t n_vocab = gguf_get_arr_n(ctx, token_idx);
  3494. vocab.id_to_token.resize(n_vocab);
  3495. for (uint32_t i = 0; i < n_vocab; i++) {
  3496. std::string word = gguf_get_arr_str(ctx, token_idx, i);
  3497. GGML_ASSERT(unicode_cpts_from_utf8(word).size() > 0);
  3498. vocab.token_to_id[word] = i;
  3499. auto & token_data = vocab.id_to_token[i];
  3500. token_data.text = std::move(word);
  3501. token_data.score = scores ? scores[i] : 0.0f;
  3502. token_data.type = toktypes ? (llama_token_type) toktypes[i] : LLAMA_TOKEN_TYPE_NORMAL;
  3503. }
  3504. GGML_ASSERT(vocab.id_to_token.size() == vocab.token_to_id.size());
  3505. // determine the newline token: LLaMA "<0x0A>" == 10 == '\n', Falcon 193 == '\n'
  3506. if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  3507. try {
  3508. vocab.linefeed_id = llama_byte_to_token(vocab, '\n');
  3509. } catch (const std::exception & e) {
  3510. LLAMA_LOG_WARN("%s: SPM vocabulary, but newline token not found: %s! Using special_pad_id instead.", __func__, e.what());
  3511. vocab.linefeed_id = vocab.special_pad_id;
  3512. }
  3513. } else if (vocab.type == LLAMA_VOCAB_TYPE_WPM) {
  3514. vocab.linefeed_id = vocab.special_pad_id;
  3515. } else {
  3516. const std::vector<int> ids = llama_tokenize_internal(vocab, "\xC4\x8A", false); // U+010A
  3517. GGML_ASSERT(!ids.empty() && "model vocab missing newline token");
  3518. vocab.linefeed_id = ids[0];
  3519. }
  3520. // special tokens
  3521. {
  3522. const std::vector<std::pair<enum llm_kv, int32_t &>> special_token_types = {
  3523. { LLM_KV_TOKENIZER_BOS_ID, vocab.special_bos_id },
  3524. { LLM_KV_TOKENIZER_EOS_ID, vocab.special_eos_id },
  3525. { LLM_KV_TOKENIZER_UNK_ID, vocab.special_unk_id },
  3526. { LLM_KV_TOKENIZER_SEP_ID, vocab.special_sep_id },
  3527. { LLM_KV_TOKENIZER_PAD_ID, vocab.special_pad_id },
  3528. };
  3529. for (const auto & it : special_token_types) {
  3530. const std::string & key = kv(std::get<0>(it));
  3531. int32_t & id = std::get<1>(it);
  3532. uint32_t new_id;
  3533. if (!ml.get_key(std::get<0>(it), new_id, false)) {
  3534. continue;
  3535. }
  3536. if (new_id >= vocab.id_to_token.size()) {
  3537. LLAMA_LOG_WARN("%s: bad special token: '%s' = %ud, using default id %d\n",
  3538. __func__, key.c_str(), new_id, id);
  3539. } else {
  3540. id = new_id;
  3541. }
  3542. }
  3543. // Handle add_bos_token and add_eos_token
  3544. {
  3545. bool temp = true;
  3546. if (ml.get_key(LLM_KV_TOKENIZER_ADD_BOS, temp, false)) {
  3547. vocab.special_add_bos = int(temp);
  3548. }
  3549. if (ml.get_key(LLM_KV_TOKENIZER_ADD_EOS, temp, false)) {
  3550. vocab.special_add_eos = int(temp);
  3551. }
  3552. }
  3553. }
  3554. // build special tokens cache
  3555. {
  3556. // TODO: It is unclear (to me) at this point, whether special tokes are guaranteed to be of a deterministic type,
  3557. // and will always be correctly labeled in 'added_tokens.json' etc.
  3558. // The assumption is, since special tokens aren't meant to be exposed to end user, they are designed
  3559. // to be unmatchable by the tokenizer, therefore tokens from the vocab, which are unmatchable by the tokenizer
  3560. // are special tokens.
  3561. // From testing, this appears to correlate 1:1 with special tokens.
  3562. //
  3563. // Counting special tokens and verifying in only one direction
  3564. // is sufficient to detect difference in those two sets.
  3565. //
  3566. uint32_t special_tokens_count_by_type = 0;
  3567. uint32_t special_tokens_count_from_verification = 0;
  3568. bool special_tokens_definition_mismatch = false;
  3569. for (const auto & t : vocab.token_to_id) {
  3570. const auto & token = t.first;
  3571. const auto & id = t.second;
  3572. // Count all non-normal tokens in the vocab while iterating
  3573. if (vocab.id_to_token[id].type != LLAMA_TOKEN_TYPE_NORMAL) {
  3574. special_tokens_count_by_type++;
  3575. }
  3576. // Skip single character tokens
  3577. if (token.length() > 1) {
  3578. bool is_tokenizable = false;
  3579. // Split token string representation in two, in all possible ways
  3580. // and check if both halves can be matched to a valid token
  3581. for (unsigned i = 1; i < token.length();) {
  3582. const auto left = token.substr(0, i);
  3583. const auto right = token.substr(i);
  3584. // check if we didnt partition in the middle of a utf sequence
  3585. auto utf = utf8_len(left.at(left.length() - 1));
  3586. if (utf == 1) {
  3587. if (vocab.token_to_id.find(left) != vocab.token_to_id.end() &&
  3588. vocab.token_to_id.find(right) != vocab.token_to_id.end() ) {
  3589. is_tokenizable = true;
  3590. break;
  3591. }
  3592. i++;
  3593. } else {
  3594. // skip over the rest of multibyte utf sequence
  3595. i += utf - 1;
  3596. }
  3597. }
  3598. if (!is_tokenizable) {
  3599. // Some tokens are multibyte, but they are utf sequences with equivalent text length of 1
  3600. // it's faster to re-filter them here, since there are way less candidates now
  3601. // Calculate a total "utf" length of a token string representation
  3602. size_t utf8_str_len = 0;
  3603. for (unsigned i = 0; i < token.length();) {
  3604. utf8_str_len++;
  3605. i += utf8_len(token.at(i));
  3606. }
  3607. // And skip the ones which are one character
  3608. if (utf8_str_len > 1) {
  3609. // At this point what we have left are special tokens only
  3610. vocab.special_tokens_cache[token] = id;
  3611. // Count manually found special tokens
  3612. special_tokens_count_from_verification++;
  3613. // If this manually found special token is not marked as such, flag a mismatch
  3614. if (vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL) {
  3615. special_tokens_definition_mismatch = true;
  3616. }
  3617. }
  3618. }
  3619. }
  3620. }
  3621. if (special_tokens_definition_mismatch || special_tokens_count_from_verification != special_tokens_count_by_type) {
  3622. LLAMA_LOG_WARN("%s: mismatch in special tokens definition ( %u/%zu vs %u/%zu ).\n",
  3623. __func__,
  3624. special_tokens_count_from_verification, vocab.id_to_token.size(),
  3625. special_tokens_count_by_type, vocab.id_to_token.size()
  3626. );
  3627. } else {
  3628. LLAMA_LOG_INFO("%s: special tokens definition check successful ( %u/%zu ).\n",
  3629. __func__,
  3630. special_tokens_count_from_verification, vocab.id_to_token.size()
  3631. );
  3632. }
  3633. }
  3634. }
  3635. static void llm_load_print_meta(llama_model_loader & ml, llama_model & model) {
  3636. const auto & hparams = model.hparams;
  3637. const auto & vocab = model.vocab;
  3638. const char * rope_scaling_type = LLAMA_ROPE_SCALING_TYPES.at(hparams.rope_scaling_type_train);
  3639. // hparams
  3640. LLAMA_LOG_INFO("%s: format = %s\n", __func__, llama_file_version_name(ml.fver));
  3641. LLAMA_LOG_INFO("%s: arch = %s\n", __func__, LLM_ARCH_NAMES.at(model.arch));
  3642. LLAMA_LOG_INFO("%s: vocab type = %s\n", __func__, llama_model_vocab_type_name(vocab.type));
  3643. LLAMA_LOG_INFO("%s: n_vocab = %u\n", __func__, hparams.n_vocab);
  3644. LLAMA_LOG_INFO("%s: n_merges = %u\n", __func__, (int) vocab.bpe_ranks.size());
  3645. LLAMA_LOG_INFO("%s: n_ctx_train = %u\n", __func__, hparams.n_ctx_train);
  3646. LLAMA_LOG_INFO("%s: n_embd = %u\n", __func__, hparams.n_embd);
  3647. LLAMA_LOG_INFO("%s: n_head = %u\n", __func__, hparams.n_head);
  3648. LLAMA_LOG_INFO("%s: n_head_kv = %u\n", __func__, hparams.n_head_kv);
  3649. LLAMA_LOG_INFO("%s: n_layer = %u\n", __func__, hparams.n_layer);
  3650. LLAMA_LOG_INFO("%s: n_rot = %u\n", __func__, hparams.n_rot);
  3651. LLAMA_LOG_INFO("%s: n_embd_head_k = %u\n", __func__, hparams.n_embd_head_k);
  3652. LLAMA_LOG_INFO("%s: n_embd_head_v = %u\n", __func__, hparams.n_embd_head_v);
  3653. LLAMA_LOG_INFO("%s: n_gqa = %u\n", __func__, hparams.n_gqa());
  3654. LLAMA_LOG_INFO("%s: n_embd_k_gqa = %u\n", __func__, hparams.n_embd_k_gqa());
  3655. LLAMA_LOG_INFO("%s: n_embd_v_gqa = %u\n", __func__, hparams.n_embd_v_gqa());
  3656. LLAMA_LOG_INFO("%s: f_norm_eps = %.1e\n", __func__, hparams.f_norm_eps);
  3657. LLAMA_LOG_INFO("%s: f_norm_rms_eps = %.1e\n", __func__, hparams.f_norm_rms_eps);
  3658. LLAMA_LOG_INFO("%s: f_clamp_kqv = %.1e\n", __func__, hparams.f_clamp_kqv);
  3659. LLAMA_LOG_INFO("%s: f_max_alibi_bias = %.1e\n", __func__, hparams.f_max_alibi_bias);
  3660. LLAMA_LOG_INFO("%s: f_logit_scale = %.1e\n", __func__, hparams.f_logit_scale);
  3661. LLAMA_LOG_INFO("%s: n_ff = %u\n", __func__, hparams.n_ff);
  3662. LLAMA_LOG_INFO("%s: n_expert = %u\n", __func__, hparams.n_expert);
  3663. LLAMA_LOG_INFO("%s: n_expert_used = %u\n", __func__, hparams.n_expert_used);
  3664. LLAMA_LOG_INFO("%s: causal attn = %d\n", __func__, hparams.causal_attn);
  3665. LLAMA_LOG_INFO("%s: pooling type = %d\n", __func__, hparams.pooling_type);
  3666. LLAMA_LOG_INFO("%s: rope type = %d\n", __func__, hparams.rope_type);
  3667. LLAMA_LOG_INFO("%s: rope scaling = %s\n", __func__, rope_scaling_type);
  3668. LLAMA_LOG_INFO("%s: freq_base_train = %.1f\n", __func__, hparams.rope_freq_base_train);
  3669. LLAMA_LOG_INFO("%s: freq_scale_train = %g\n", __func__, hparams.rope_freq_scale_train);
  3670. LLAMA_LOG_INFO("%s: n_yarn_orig_ctx = %u\n", __func__, hparams.n_yarn_orig_ctx);
  3671. LLAMA_LOG_INFO("%s: rope_finetuned = %s\n", __func__, hparams.rope_finetuned ? "yes" : "unknown");
  3672. LLAMA_LOG_INFO("%s: ssm_d_conv = %u\n", __func__, hparams.ssm_d_conv);
  3673. LLAMA_LOG_INFO("%s: ssm_d_inner = %u\n", __func__, hparams.ssm_d_inner);
  3674. LLAMA_LOG_INFO("%s: ssm_d_state = %u\n", __func__, hparams.ssm_d_state);
  3675. LLAMA_LOG_INFO("%s: ssm_dt_rank = %u\n", __func__, hparams.ssm_dt_rank);
  3676. LLAMA_LOG_INFO("%s: model type = %s\n", __func__, llama_model_type_name(model.type));
  3677. LLAMA_LOG_INFO("%s: model ftype = %s\n", __func__, llama_model_ftype_name(model.ftype).c_str());
  3678. if (ml.n_elements >= 1e12) {
  3679. LLAMA_LOG_INFO("%s: model params = %.2f T\n", __func__, ml.n_elements*1e-12);
  3680. } else if (ml.n_elements >= 1e9) {
  3681. LLAMA_LOG_INFO("%s: model params = %.2f B\n", __func__, ml.n_elements*1e-9);
  3682. } else if (ml.n_elements >= 1e6) {
  3683. LLAMA_LOG_INFO("%s: model params = %.2f M\n", __func__, ml.n_elements*1e-6);
  3684. } else {
  3685. LLAMA_LOG_INFO("%s: model params = %.2f K\n", __func__, ml.n_elements*1e-3);
  3686. }
  3687. if (ml.n_bytes < GiB) {
  3688. 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);
  3689. } else {
  3690. 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);
  3691. }
  3692. // general kv
  3693. LLAMA_LOG_INFO("%s: general.name = %s\n", __func__, model.name.c_str());
  3694. // special tokens
  3695. 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() ); }
  3696. 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() ); }
  3697. 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() ); }
  3698. 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() ); }
  3699. 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() ); }
  3700. 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() ); }
  3701. }
  3702. // Returns false if cancelled by progress_callback
  3703. static bool llm_load_tensors(
  3704. llama_model_loader & ml,
  3705. llama_model & model,
  3706. int n_gpu_layers,
  3707. enum llama_split_mode split_mode,
  3708. int main_gpu,
  3709. const float * tensor_split,
  3710. bool use_mlock,
  3711. llama_progress_callback progress_callback,
  3712. void * progress_callback_user_data) {
  3713. model.t_start_us = ggml_time_us();
  3714. auto & hparams = model.hparams;
  3715. model.split_mode = split_mode;
  3716. model.main_gpu = main_gpu;
  3717. model.n_gpu_layers = n_gpu_layers;
  3718. const int64_t n_layer = hparams.n_layer;
  3719. const int64_t i_gpu_start = std::max((int64_t) hparams.n_layer - n_gpu_layers, (int64_t) 0);
  3720. // there is very little benefit to offloading the input layer, so always keep it on the CPU
  3721. model.buft_input = llama_default_buffer_type_cpu(true);
  3722. //model.buft_input = llama_default_buffer_type_offload(main_gpu);
  3723. model.buft_layer.resize(n_layer);
  3724. // assign cpu layers
  3725. for (int64_t i = 0; i < i_gpu_start; ++i) {
  3726. model.buft_layer[i] = llama_default_buffer_type_cpu(true);
  3727. }
  3728. if (split_mode == LLAMA_SPLIT_MODE_LAYER) {
  3729. // calculate the split points
  3730. int device_count = llama_get_device_count();
  3731. bool all_zero = tensor_split == nullptr || std::all_of(tensor_split, tensor_split + device_count, [](float x) { return x == 0.0f; });
  3732. std::vector<float> splits(device_count);
  3733. if (all_zero) {
  3734. // default split, by free memory
  3735. for (int i = 0; i < device_count; ++i) {
  3736. splits[i] = llama_get_device_memory(i);
  3737. }
  3738. } else {
  3739. std::copy(tensor_split, tensor_split + device_count, splits.begin());
  3740. }
  3741. // sum and normalize the splits to get the split points
  3742. float split_sum = 0.0f;
  3743. for (int i = 0; i < device_count; ++i) {
  3744. split_sum += splits[i];
  3745. splits[i] = split_sum;
  3746. }
  3747. for (int i = 0; i < device_count; ++i) {
  3748. splits[i] /= split_sum;
  3749. }
  3750. // assign the repeating layers to the devices according to the splits
  3751. int act_gpu_layers = std::min(n_gpu_layers, (int)n_layer + 1);
  3752. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  3753. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(i - i_gpu_start)/act_gpu_layers) - splits.begin();
  3754. model.buft_layer[i] = llama_default_buffer_type_offload(layer_gpu);
  3755. }
  3756. // assign the output layer
  3757. if (n_gpu_layers > n_layer) {
  3758. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(act_gpu_layers - 1)/act_gpu_layers) - splits.begin();
  3759. model.buft_output = llama_default_buffer_type_offload(layer_gpu);
  3760. } else {
  3761. model.buft_output = llama_default_buffer_type_cpu(true);
  3762. }
  3763. } else {
  3764. ggml_backend_buffer_type_t split_buft;
  3765. if (split_mode == LLAMA_SPLIT_MODE_ROW) {
  3766. split_buft = llama_default_buffer_type_split(main_gpu, tensor_split);
  3767. } else {
  3768. // LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_LAYER in backends where it is not supported
  3769. split_buft = llama_default_buffer_type_offload(main_gpu);
  3770. }
  3771. // assign the repeating layers
  3772. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  3773. model.buft_layer[i] = {
  3774. split_buft,
  3775. llama_default_buffer_type_offload(main_gpu)
  3776. };
  3777. }
  3778. // assign the output layer
  3779. if (n_gpu_layers > n_layer) {
  3780. model.buft_output = {
  3781. split_buft,
  3782. llama_default_buffer_type_offload(main_gpu)
  3783. };
  3784. } else {
  3785. model.buft_output = llama_default_buffer_type_cpu(true);
  3786. }
  3787. }
  3788. // count used buffer types
  3789. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  3790. buft_layer_count[model.buft_input.buft]++;
  3791. buft_layer_count[model.buft_input.buft_matrix]++;
  3792. buft_layer_count[model.buft_output.buft]++;
  3793. buft_layer_count[model.buft_output.buft_matrix]++;
  3794. for (int64_t i = 0; i < n_layer; ++i) {
  3795. buft_layer_count[model.buft_layer[i].buft]++;
  3796. buft_layer_count[model.buft_layer[i].buft_matrix]++;
  3797. }
  3798. // create one context per buffer type
  3799. size_t ctx_size = ggml_tensor_overhead()*(ml.n_tensors + 1); // +1 for models where tok_embd is duplicated as output
  3800. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  3801. for (auto & it : buft_layer_count) {
  3802. struct ggml_init_params params = {
  3803. /*.mem_size =*/ ctx_size,
  3804. /*.mem_buffer =*/ NULL,
  3805. /*.no_alloc =*/ true,
  3806. };
  3807. ggml_context * ctx = ggml_init(params);
  3808. if (!ctx) {
  3809. throw std::runtime_error(format("failed to create context"));
  3810. }
  3811. ctx_map[it.first] = ctx;
  3812. model.ctxs.push_back(ctx);
  3813. }
  3814. LLAMA_LOG_INFO("%s: ggml ctx size = %7.2f MiB\n", __func__, model.ctxs.size()*ctx_size/1024.0/1024.0);
  3815. // create tensors for the weights
  3816. {
  3817. const int64_t n_embd = hparams.n_embd;
  3818. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3819. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  3820. const int64_t n_embd_gqa = n_embd_v_gqa;
  3821. const int64_t n_vocab = hparams.n_vocab;
  3822. const int64_t n_vocab_type = hparams.n_vocab_type;
  3823. const int64_t n_ff = hparams.n_ff;
  3824. GGML_ASSERT(n_embd_gqa == n_embd_k_gqa);
  3825. ggml_context * ctx_input = ctx_map.at(model.buft_input.buft);
  3826. ggml_context * ctx_output = ctx_map.at(model.buft_output.buft);
  3827. ggml_context * ctx_output_split = ctx_map.at(model.buft_output.buft_matrix);
  3828. auto ctx_for_layer = [&](int i) { return ctx_map.at(model.buft_layer[i].buft); };
  3829. auto ctx_for_layer_split = [&](int i) { return ctx_map.at(model.buft_layer[i].buft_matrix); };
  3830. model.layers.resize(n_layer);
  3831. const auto tn = LLM_TN(model.arch);
  3832. switch (model.arch) {
  3833. case LLM_ARCH_LLAMA:
  3834. case LLM_ARCH_REFACT:
  3835. case LLM_ARCH_MINICPM:
  3836. {
  3837. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3838. // output
  3839. {
  3840. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3841. if (model.arch != LLM_ARCH_MINICPM){
  3842. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  3843. // if output is NULL, init from the input tok embed
  3844. if (model.output == NULL) {
  3845. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3846. ml.n_created--; // artificial tensor
  3847. ml.size_data += ggml_nbytes(model.output);
  3848. }
  3849. }
  3850. }
  3851. for (int i = 0; i < n_layer; ++i) {
  3852. ggml_context * ctx_layer = ctx_for_layer(i);
  3853. ggml_context * ctx_split = ctx_for_layer_split(i);
  3854. auto & layer = model.layers[i];
  3855. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3856. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3857. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3858. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3859. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3860. // optional bias tensors
  3861. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, false);
  3862. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, false);
  3863. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, false);
  3864. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, false);
  3865. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3866. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd}, false);
  3867. if (layer.ffn_gate_inp == nullptr) {
  3868. GGML_ASSERT(hparams.n_expert == 0);
  3869. GGML_ASSERT(hparams.n_expert_used == 0);
  3870. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3871. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3872. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3873. } else {
  3874. GGML_ASSERT(hparams.n_expert > 0);
  3875. GGML_ASSERT(hparams.n_expert_used > 0);
  3876. // MoE branch
  3877. for (uint32_t x = 0; x < hparams.n_expert; ++x) {
  3878. layer.ffn_gate_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, x), {n_embd, n_ff});
  3879. layer.ffn_down_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, x), { n_ff, n_embd});
  3880. layer.ffn_up_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, x), {n_embd, n_ff});
  3881. }
  3882. }
  3883. }
  3884. } break;
  3885. case LLM_ARCH_GROK:
  3886. {
  3887. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3888. // output
  3889. {
  3890. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3891. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  3892. // if output is NULL, init from the input tok embed
  3893. if (model.output == NULL) {
  3894. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3895. ml.n_created--; // artificial tensor
  3896. ml.size_data += ggml_nbytes(model.output);
  3897. }
  3898. }
  3899. for (int i = 0; i < n_layer; ++i) {
  3900. ggml_context * ctx_layer = ctx_for_layer(i);
  3901. ggml_context * ctx_split = ctx_for_layer_split(i);
  3902. auto & layer = model.layers[i];
  3903. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3904. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3905. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3906. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3907. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3908. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  3909. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3910. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd});
  3911. GGML_ASSERT(hparams.n_expert > 0);
  3912. GGML_ASSERT(hparams.n_expert_used > 0);
  3913. // MoE branch
  3914. for (uint32_t x = 0; x < hparams.n_expert; ++x) {
  3915. layer.ffn_gate_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, x), {n_embd, n_ff});
  3916. layer.ffn_down_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, x), { n_ff, n_embd});
  3917. layer.ffn_up_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, x), {n_embd, n_ff});
  3918. }
  3919. layer.layer_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd});
  3920. }
  3921. } break;
  3922. case LLM_ARCH_BAICHUAN:
  3923. {
  3924. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3925. {
  3926. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3927. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3928. }
  3929. for (int i = 0; i < n_layer; ++i) {
  3930. ggml_context * ctx_layer = ctx_for_layer(i);
  3931. ggml_context * ctx_split = ctx_for_layer_split(i);
  3932. auto & layer = model.layers[i];
  3933. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3934. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3935. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3936. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3937. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3938. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3939. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3940. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3941. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3942. }
  3943. } break;
  3944. case LLM_ARCH_FALCON:
  3945. {
  3946. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3947. // output
  3948. {
  3949. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3950. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3951. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  3952. if (!model.output) {
  3953. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}); // needs to be on GPU
  3954. ml.n_created--; // artificial tensor
  3955. ml.size_data += ggml_nbytes(model.output);
  3956. }
  3957. }
  3958. for (int i = 0; i < n_layer; ++i) {
  3959. ggml_context * ctx_layer = ctx_for_layer(i);
  3960. ggml_context * ctx_split = ctx_for_layer_split(i);
  3961. auto & layer = model.layers[i];
  3962. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3963. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3964. layer.attn_norm_2 = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i), {n_embd}, false);
  3965. layer.attn_norm_2_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "bias", i), {n_embd}, false);
  3966. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3967. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3968. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3969. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3970. }
  3971. } break;
  3972. case LLM_ARCH_STARCODER:
  3973. {
  3974. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3975. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3976. // output
  3977. {
  3978. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3979. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3980. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3981. }
  3982. for (int i = 0; i < n_layer; ++i) {
  3983. ggml_context * ctx_layer = ctx_for_layer(i);
  3984. ggml_context * ctx_split = ctx_for_layer_split(i);
  3985. auto & layer = model.layers[i];
  3986. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3987. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3988. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3989. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3990. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3991. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3992. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3993. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3994. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3995. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3996. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3997. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3998. }
  3999. } break;
  4000. case LLM_ARCH_PERSIMMON:
  4001. {
  4002. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4003. {
  4004. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4005. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4006. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4007. }
  4008. for (int i = 0; i < n_layer; ++i) {
  4009. ggml_context * ctx_layer = ctx_for_layer(i);
  4010. ggml_context * ctx_split = ctx_for_layer_split(i);
  4011. auto & layer = model.layers[i];
  4012. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4013. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4014. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4015. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  4016. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4017. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4018. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4019. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4020. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4021. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4022. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4023. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4024. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {64});
  4025. layer.attn_q_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "bias", i), {64});
  4026. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {64});
  4027. layer.attn_k_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "bias", i), {64});
  4028. }
  4029. } break;
  4030. case LLM_ARCH_BERT:
  4031. case LLM_ARCH_NOMIC_BERT:
  4032. {
  4033. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4034. model.type_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_TYPES, "weight"), {n_embd, n_vocab_type});
  4035. if (model.arch == LLM_ARCH_BERT) {
  4036. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  4037. }
  4038. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  4039. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  4040. for (int i = 0; i < n_layer; ++i) {
  4041. ggml_context * ctx_layer = ctx_for_layer(i);
  4042. ggml_context * ctx_split = ctx_for_layer_split(i);
  4043. auto & layer = model.layers[i];
  4044. if (model.arch == LLM_ARCH_BERT) {
  4045. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4046. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  4047. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4048. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  4049. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4050. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  4051. } else {
  4052. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4053. }
  4054. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4055. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  4056. layer.attn_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "bias", i), {n_embd});
  4057. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4058. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4059. if (model.arch == LLM_ARCH_BERT) {
  4060. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4061. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4062. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4063. } else {
  4064. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4065. }
  4066. layer.layer_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd});
  4067. layer.layer_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "bias", i), {n_embd});
  4068. }
  4069. } break;
  4070. case LLM_ARCH_BLOOM:
  4071. {
  4072. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4073. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  4074. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  4075. // output
  4076. {
  4077. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4078. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4079. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4080. }
  4081. for (int i = 0; i < n_layer; ++i) {
  4082. ggml_context * ctx_layer = ctx_for_layer(i);
  4083. ggml_context * ctx_split = ctx_for_layer_split(i);
  4084. auto & layer = model.layers[i];
  4085. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4086. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4087. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4088. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  4089. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4090. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4091. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4092. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4093. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4094. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4095. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4096. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4097. }
  4098. } break;
  4099. case LLM_ARCH_MPT:
  4100. {
  4101. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4102. // output
  4103. {
  4104. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4105. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, false);
  4106. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  4107. if (!model.output) {
  4108. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}); // needs to be on GPU
  4109. ml.n_created--; // artificial tensor
  4110. ml.size_data += ggml_nbytes(model.output);
  4111. }
  4112. }
  4113. for (int i = 0; i < n_layer; ++i) {
  4114. ggml_context * ctx_layer = ctx_for_layer(i);
  4115. ggml_context * ctx_split = ctx_for_layer_split(i);
  4116. auto & layer = model.layers[i];
  4117. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4118. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, false);
  4119. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4120. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, false);
  4121. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4122. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, false);
  4123. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4124. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, false);
  4125. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4126. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, false);
  4127. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4128. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, false);
  4129. // AWQ ScaleActivation layer
  4130. layer.ffn_act = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_ACT, "scales", i), {n_ff}, false);
  4131. }
  4132. } break;
  4133. case LLM_ARCH_STABLELM:
  4134. {
  4135. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4136. // output
  4137. {
  4138. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4139. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4140. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4141. }
  4142. for (int i = 0; i < n_layer; ++i) {
  4143. ggml_context * ctx_layer = ctx_for_layer(i);
  4144. ggml_context * ctx_split = ctx_for_layer_split(i);
  4145. auto & layer = model.layers[i];
  4146. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4147. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4148. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4149. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4150. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4151. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4152. // optional bias tensors, present in Stable LM 2 1.6B
  4153. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, false);
  4154. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, false);
  4155. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, false);
  4156. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4157. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4158. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4159. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4160. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4161. }
  4162. } break;
  4163. case LLM_ARCH_QWEN:
  4164. {
  4165. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4166. // output
  4167. {
  4168. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4169. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4170. }
  4171. for (int i = 0; i < n_layer; ++i) {
  4172. ggml_context * ctx_layer = ctx_for_layer(i);
  4173. ggml_context * ctx_split = ctx_for_layer_split(i);
  4174. auto & layer = model.layers[i];
  4175. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4176. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd*3});
  4177. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd*3});
  4178. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4179. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4180. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff/2});
  4181. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff/2, n_embd});
  4182. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff/2});
  4183. }
  4184. } break;
  4185. case LLM_ARCH_QWEN2:
  4186. {
  4187. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4188. // output
  4189. {
  4190. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4191. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4192. }
  4193. for (int i = 0; i < n_layer; ++i) {
  4194. ggml_context * ctx_layer = ctx_for_layer(i);
  4195. ggml_context * ctx_split = ctx_for_layer_split(i);
  4196. auto & layer = model.layers[i];
  4197. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4198. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4199. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4200. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4201. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4202. // optional bias tensors
  4203. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  4204. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  4205. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  4206. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4207. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4208. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4209. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4210. }
  4211. } break;
  4212. case LLM_ARCH_PHI2:
  4213. {
  4214. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4215. // output
  4216. {
  4217. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4218. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4219. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4220. model.output_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT, "bias"), {n_vocab});
  4221. }
  4222. for (int i = 0; i < n_layer; ++i) {
  4223. ggml_context * ctx_layer = ctx_for_layer(i);
  4224. ggml_context * ctx_split = ctx_for_layer_split(i);
  4225. auto & layer = model.layers[i];
  4226. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4227. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4228. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, false);
  4229. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, false);
  4230. if (layer.wqkv == nullptr) {
  4231. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4232. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  4233. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4234. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  4235. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4236. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  4237. }
  4238. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4239. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4240. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4241. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4242. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4243. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4244. }
  4245. } break;
  4246. case LLM_ARCH_PLAMO:
  4247. {
  4248. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4249. // output
  4250. {
  4251. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4252. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4253. }
  4254. for (int i = 0; i < n_layer; ++i) {
  4255. ggml_context * ctx_layer = ctx_for_layer(i);
  4256. ggml_context * ctx_split = ctx_for_layer_split(i);
  4257. auto & layer = model.layers[i];
  4258. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4259. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4260. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4261. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4262. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4263. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4264. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4265. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4266. }
  4267. } break;
  4268. case LLM_ARCH_GPT2:
  4269. {
  4270. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4271. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  4272. // output
  4273. {
  4274. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4275. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4276. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4277. }
  4278. for (int i = 0; i < n_layer; ++i) {
  4279. ggml_context * ctx_layer = ctx_for_layer(i);
  4280. ggml_context * ctx_split = ctx_for_layer_split(i);
  4281. auto & layer = model.layers[i];
  4282. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4283. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4284. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4285. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  4286. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4287. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4288. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4289. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4290. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4291. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4292. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4293. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4294. }
  4295. } break;
  4296. case LLM_ARCH_CODESHELL:
  4297. {
  4298. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4299. // output
  4300. {
  4301. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4302. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4303. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4304. }
  4305. for (int i = 0; i < n_layer; ++i) {
  4306. ggml_context * ctx_layer = ctx_for_layer(i);
  4307. ggml_context * ctx_split = ctx_for_layer_split(i);
  4308. auto & layer = model.layers[i];
  4309. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4310. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4311. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4312. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  4313. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4314. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4315. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4316. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4317. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4318. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4319. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4320. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4321. }
  4322. } break;
  4323. case LLM_ARCH_ORION:
  4324. {
  4325. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4326. {
  4327. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4328. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4329. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4330. }
  4331. for (int i = 0; i < n_layer; ++i) {
  4332. ggml_context * ctx_layer = ctx_for_layer(i);
  4333. ggml_context * ctx_split = ctx_for_layer_split(i);
  4334. auto & layer = model.layers[i];
  4335. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4336. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4337. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4338. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4339. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4340. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4341. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4342. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4343. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4344. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4345. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4346. }
  4347. } break;
  4348. case LLM_ARCH_INTERNLM2:
  4349. {
  4350. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4351. // output
  4352. {
  4353. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4354. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4355. }
  4356. for (int i = 0; i < n_layer; ++i) {
  4357. ggml_context * ctx_layer = ctx_for_layer(i);
  4358. ggml_context * ctx_split = ctx_for_layer_split(i);
  4359. auto & layer = model.layers[i];
  4360. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4361. // layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4362. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4363. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4364. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4365. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4366. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4367. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4368. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4369. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4370. }
  4371. } break;
  4372. case LLM_ARCH_GEMMA:
  4373. {
  4374. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4375. // output
  4376. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4377. 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
  4378. ml.n_created--; // artificial tensor
  4379. ml.size_data += ggml_nbytes(model.output);
  4380. const int64_t n_ff = hparams.n_ff;
  4381. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  4382. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  4383. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  4384. for (uint32_t i = 0; i < n_layer; ++i) {
  4385. ggml_context * ctx_layer = ctx_for_layer(i);
  4386. ggml_context * ctx_split = ctx_for_layer_split(i);
  4387. auto & layer = model.layers[i];
  4388. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4389. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * hparams.n_head});
  4390. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  4391. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  4392. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * hparams.n_head, n_embd});
  4393. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4394. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4395. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4396. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4397. }
  4398. } break;
  4399. case LLM_ARCH_STARCODER2:
  4400. {
  4401. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4402. // output
  4403. {
  4404. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4405. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4406. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  4407. // if output is NULL, init from the input tok embed
  4408. if (model.output == NULL) {
  4409. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4410. ml.n_created--; // artificial tensor
  4411. ml.size_data += ggml_nbytes(model.output);
  4412. }
  4413. }
  4414. for (int i = 0; i < n_layer; ++i) {
  4415. ggml_context * ctx_layer = ctx_for_layer(i);
  4416. ggml_context * ctx_split = ctx_for_layer_split(i);
  4417. auto & layer = model.layers[i];
  4418. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4419. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4420. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4421. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4422. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4423. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4424. // optional bias tensors
  4425. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  4426. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  4427. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  4428. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4429. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4430. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4431. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4432. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4433. // optional bias tensors
  4434. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4435. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP , "bias", i), { n_ff});
  4436. }
  4437. } break;
  4438. case LLM_ARCH_MAMBA:
  4439. {
  4440. const int64_t d_conv = hparams.ssm_d_conv;
  4441. const int64_t d_inner = hparams.ssm_d_inner;
  4442. const int64_t d_state = hparams.ssm_d_state;
  4443. const int64_t dt_rank = hparams.ssm_dt_rank;
  4444. // only an expansion factor of 2 is supported for now
  4445. GGML_ASSERT(2 * n_embd == d_inner);
  4446. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4447. // output
  4448. {
  4449. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4450. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  4451. // if output is NULL, init from the input tok embed, duplicated to allow offloading
  4452. if (model.output == NULL) {
  4453. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4454. ml.n_created--; // artificial tensor
  4455. ml.size_data += ggml_nbytes(model.output);
  4456. }
  4457. }
  4458. for (int i = 0; i < n_layer; ++i) {
  4459. ggml_context * ctx_layer = ctx_for_layer(i);
  4460. ggml_context * ctx_split = ctx_for_layer_split(i);
  4461. auto & layer = model.layers[i];
  4462. // norm
  4463. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4464. layer.ssm_in = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_IN, "weight", i), {n_embd, 2*d_inner});
  4465. layer.ssm_conv1d = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_CONV1D, "weight", i), {d_conv, d_inner});
  4466. layer.ssm_conv1d_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_CONV1D, "bias", i), {d_inner});
  4467. layer.ssm_x = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_X, "weight", i), {d_inner, dt_rank + 2*d_state});
  4468. layer.ssm_dt = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_DT, "weight", i), {dt_rank, d_inner});
  4469. layer.ssm_dt_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_DT, "bias", i), {d_inner});
  4470. // no "weight" suffix for these
  4471. layer.ssm_a = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_A, i), {d_state, d_inner});
  4472. layer.ssm_d = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_D, i), {d_inner});
  4473. // out_proj
  4474. layer.ssm_out = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_OUT, "weight", i), {d_inner, n_embd});
  4475. }
  4476. } break;
  4477. case LLM_ARCH_XVERSE:
  4478. {
  4479. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4480. {
  4481. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4482. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4483. }
  4484. for (int i = 0; i < n_layer; ++i) {
  4485. ggml_context * ctx_layer = ctx_for_layer(i);
  4486. ggml_context * ctx_split = ctx_for_layer_split(i);
  4487. auto & layer = model.layers[i];
  4488. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4489. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4490. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4491. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4492. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4493. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4494. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4495. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4496. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4497. }
  4498. } break;
  4499. case LLM_ARCH_COMMAND_R:
  4500. {
  4501. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4502. // output
  4503. {
  4504. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4505. // init output from the input tok embed
  4506. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4507. ml.n_created--; // artificial tensor
  4508. ml.size_data += ggml_nbytes(model.output);
  4509. }
  4510. for (int i = 0; i < n_layer; ++i) {
  4511. ggml_context * ctx_layer = ctx_for_layer(i);
  4512. ggml_context * ctx_split = ctx_for_layer_split(i);
  4513. auto & layer = model.layers[i];
  4514. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4515. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4516. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4517. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4518. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4519. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4520. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4521. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4522. }
  4523. } break;
  4524. default:
  4525. throw std::runtime_error("unknown architecture");
  4526. }
  4527. }
  4528. ml.done_getting_tensors();
  4529. ml.init_mappings(true, use_mlock ? &model.mlock_mmaps : nullptr);
  4530. model.mappings.reserve(ml.mappings.size());
  4531. // create the backend buffers
  4532. std::vector<std::pair<ggml_context *, llama_buf_map>> ctx_bufs;
  4533. ctx_bufs.reserve(ctx_map.size());
  4534. // Ensure we have enough capacity for the maximum backend buffer we will potentially create
  4535. size_t n_max_backend_buffer = ctx_map.size() * ml.files.size();
  4536. model.bufs.reserve(n_max_backend_buffer);
  4537. for (auto & it : ctx_map) {
  4538. ggml_backend_buffer_type_t buft = it.first;
  4539. ggml_context * ctx = it.second;
  4540. llama_buf_map bufs;
  4541. bufs.reserve(n_max_backend_buffer);
  4542. // only the mmap region containing the tensors in the model is mapped to the backend buffer
  4543. // 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
  4544. // this allows using partial offloading when the model size exceeds the metal buffer size, but not the RAM size
  4545. if (ml.use_mmap && buft == llama_default_buffer_type_cpu(true)) {
  4546. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  4547. void * addr = nullptr;
  4548. size_t first, last;
  4549. ml.get_mapping_range(&first, &last, &addr, idx, ctx);
  4550. if (first >= last) {
  4551. continue;
  4552. }
  4553. ggml_backend_buffer_t buf = ggml_backend_cpu_buffer_from_ptr((char *) addr + first, last - first);
  4554. if (buf == nullptr) {
  4555. throw std::runtime_error("unable to allocate backend CPU buffer");
  4556. }
  4557. model.bufs.push_back(buf);
  4558. bufs.emplace(idx, buf);
  4559. #ifdef GGML_USE_CUDA
  4560. if (n_layer >= n_gpu_layers) {
  4561. ggml_backend_cuda_register_host_buffer(
  4562. ggml_backend_buffer_get_base(buf),
  4563. ggml_backend_buffer_get_size(buf));
  4564. }
  4565. #endif
  4566. }
  4567. }
  4568. #ifdef GGML_USE_METAL
  4569. else if (ml.use_mmap && buft == ggml_backend_metal_buffer_type()) {
  4570. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  4571. const size_t max_size = ggml_get_max_tensor_size(ctx);
  4572. void * addr = nullptr;
  4573. size_t first, last;
  4574. ml.get_mapping_range(&first, &last, &addr, idx, ctx);
  4575. if (first >= last) {
  4576. continue;
  4577. }
  4578. ggml_backend_buffer_t buf = ggml_backend_metal_buffer_from_ptr((char *) addr + first, last - first, max_size);
  4579. if (buf == nullptr) {
  4580. throw std::runtime_error("unable to allocate backend metal buffer");
  4581. }
  4582. model.bufs.push_back(buf);
  4583. bufs.emplace(idx, buf);
  4584. }
  4585. }
  4586. #endif
  4587. else {
  4588. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  4589. if (buf == nullptr) {
  4590. throw std::runtime_error("unable to allocate backend buffer");
  4591. }
  4592. model.bufs.push_back(buf);
  4593. if (use_mlock && ggml_backend_buffer_is_host(buf)) {
  4594. model.mlock_bufs.emplace_back(new llama_mlock);
  4595. auto & mlock_buf = model.mlock_bufs.back();
  4596. mlock_buf->init (ggml_backend_buffer_get_base(buf));
  4597. mlock_buf->grow_to(ggml_backend_buffer_get_size(buf));
  4598. }
  4599. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  4600. bufs.emplace(idx, buf);
  4601. }
  4602. }
  4603. if (bufs.empty()) {
  4604. throw std::runtime_error("failed to allocate buffer");
  4605. }
  4606. for (auto & buf : bufs) {
  4607. // indicate that this buffer contains weights
  4608. // 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
  4609. ggml_backend_buffer_set_usage(buf.second, GGML_BACKEND_BUFFER_USAGE_WEIGHTS);
  4610. }
  4611. ctx_bufs.emplace_back(ctx, bufs);
  4612. }
  4613. if (llama_supports_gpu_offload()) {
  4614. const int n_gpu = std::min(n_gpu_layers, int(hparams.n_layer));
  4615. LLAMA_LOG_INFO("%s: offloading %d repeating layers to GPU\n", __func__, n_gpu);
  4616. if (n_gpu_layers > (int) hparams.n_layer) {
  4617. LLAMA_LOG_INFO("%s: offloading non-repeating layers to GPU\n", __func__);
  4618. }
  4619. const int max_backend_supported_layers = hparams.n_layer + 1;
  4620. const int max_offloadable_layers = hparams.n_layer + 1;
  4621. LLAMA_LOG_INFO("%s: offloaded %d/%d layers to GPU\n", __func__, std::min(n_gpu_layers, max_offloadable_layers), max_backend_supported_layers);
  4622. }
  4623. // print memory requirements
  4624. for (ggml_backend_buffer_t buf : model.bufs) {
  4625. 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);
  4626. }
  4627. // populate tensors_by_name
  4628. for (ggml_context * ctx : model.ctxs) {
  4629. for (auto * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  4630. model.tensors_by_name.emplace_back(ggml_get_name(cur), cur);
  4631. }
  4632. }
  4633. // load tensor data
  4634. for (auto & it : ctx_bufs) {
  4635. ggml_context * ctx = it.first;
  4636. auto & bufs = it.second;
  4637. if (!ml.load_all_data(ctx, bufs, use_mlock ? &model.mlock_mmaps : NULL, progress_callback, progress_callback_user_data)) {
  4638. return false;
  4639. }
  4640. }
  4641. for (auto & mapping : ml.mappings) {
  4642. model.mappings.emplace_back(std::move(mapping));
  4643. }
  4644. // loading time will be recalculate after the first eval, so
  4645. // we take page faults deferred by mmap() into consideration
  4646. model.t_load_us = ggml_time_us() - model.t_start_us;
  4647. return true;
  4648. }
  4649. // Returns 0 on success, -1 on error, and -2 on cancellation via llama_progress_callback
  4650. static int llama_model_load(const std::string & fname, llama_model & model, llama_model_params & params) {
  4651. try {
  4652. llama_model_loader ml(fname, params.use_mmap, params.kv_overrides);
  4653. model.hparams.vocab_only = params.vocab_only;
  4654. try {
  4655. llm_load_arch(ml, model);
  4656. } catch(const std::exception & e) {
  4657. throw std::runtime_error("error loading model architecture: " + std::string(e.what()));
  4658. }
  4659. try {
  4660. llm_load_hparams(ml, model);
  4661. } catch(const std::exception & e) {
  4662. throw std::runtime_error("error loading model hyperparameters: " + std::string(e.what()));
  4663. }
  4664. try {
  4665. llm_load_vocab(ml, model);
  4666. } catch(const std::exception & e) {
  4667. throw std::runtime_error("error loading model vocabulary: " + std::string(e.what()));
  4668. }
  4669. llm_load_print_meta(ml, model);
  4670. if (model.vocab.type != LLAMA_VOCAB_TYPE_NONE &&
  4671. model.hparams.n_vocab != model.vocab.id_to_token.size()) {
  4672. throw std::runtime_error("vocab size mismatch");
  4673. }
  4674. if (params.vocab_only) {
  4675. LLAMA_LOG_INFO("%s: vocab only - skipping tensors\n", __func__);
  4676. return 0;
  4677. }
  4678. #ifdef GGML_USE_KOMPUTE
  4679. if (params.n_gpu_layers > 0 && (
  4680. !(model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON)
  4681. || !(
  4682. model.ftype == LLAMA_FTYPE_ALL_F32 ||
  4683. model.ftype == LLAMA_FTYPE_MOSTLY_F16 ||
  4684. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ||
  4685. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_1
  4686. )
  4687. )) {
  4688. // TODO(cebtenzzre): propagate this error outside of llama_load_model_from_file
  4689. LLAMA_LOG_WARN("%s: disabling Kompute due to unsupported model arch or quantization\n", __func__);
  4690. params.n_gpu_layers = 0;
  4691. }
  4692. #endif
  4693. #ifdef GGML_USE_SYCL
  4694. if (params.split_mode == LLAMA_SPLIT_MODE_NONE) {
  4695. ggml_backend_sycl_set_single_device_mode(params.main_gpu);
  4696. //SYCL use device index (0, 1, 2) directly, uer input device id, then convert to device index.
  4697. params.main_gpu = ggml_backend_sycl_get_device_index(params.main_gpu);
  4698. } else {
  4699. ggml_backend_sycl_set_mul_device_mode();
  4700. }
  4701. #endif
  4702. if (!llm_load_tensors(
  4703. ml, model, params.n_gpu_layers, params.split_mode, params.main_gpu, params.tensor_split, params.use_mlock,
  4704. params.progress_callback, params.progress_callback_user_data
  4705. )) {
  4706. return -2;
  4707. }
  4708. } catch (const std::exception & err) {
  4709. LLAMA_LOG_ERROR("%s: error loading model: %s\n", __func__, err.what());
  4710. return -1;
  4711. }
  4712. return 0;
  4713. }
  4714. //
  4715. // llm_build
  4716. //
  4717. using llm_build_cb = std::function<void(struct ggml_tensor * cur, const char * name, int nl)>;
  4718. enum llm_ffn_op_type {
  4719. LLM_FFN_SILU,
  4720. LLM_FFN_GELU,
  4721. LLM_FFN_RELU,
  4722. LLM_FFN_RELU_SQR,
  4723. };
  4724. enum llm_ffn_gate_type {
  4725. LLM_FFN_SEQ,
  4726. LLM_FFN_PAR, // ffn_gate is parallel to ffn_up
  4727. };
  4728. enum llm_norm_type {
  4729. LLM_NORM,
  4730. LLM_NORM_RMS,
  4731. };
  4732. static struct ggml_tensor * llm_build_inp_embd(
  4733. struct ggml_context * ctx,
  4734. struct llama_context & lctx,
  4735. const llama_hparams & hparams,
  4736. const llama_batch & batch,
  4737. struct ggml_tensor * tok_embd,
  4738. const llm_build_cb & cb) {
  4739. const int64_t n_embd = hparams.n_embd;
  4740. struct ggml_tensor * inpL;
  4741. if (batch.token) {
  4742. lctx.inp_tokens = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, batch.n_tokens);
  4743. cb(lctx.inp_tokens, "inp_tokens", -1);
  4744. ggml_set_input(lctx.inp_tokens);
  4745. inpL = ggml_get_rows(ctx, tok_embd, lctx.inp_tokens);
  4746. } else {
  4747. #ifdef GGML_USE_MPI
  4748. GGML_ASSERT(false && "not implemented");
  4749. #endif
  4750. lctx.inp_embd = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, batch.n_tokens);
  4751. inpL = lctx.inp_embd;
  4752. ggml_set_input(lctx.inp_embd);
  4753. }
  4754. cb(inpL, "inp_embd", -1);
  4755. return inpL;
  4756. }
  4757. static void llm_build_kv_store(
  4758. struct ggml_context * ctx,
  4759. const llama_hparams & hparams,
  4760. const llama_kv_cache & kv,
  4761. struct ggml_cgraph * graph,
  4762. struct ggml_tensor * k_cur,
  4763. struct ggml_tensor * v_cur,
  4764. int64_t n_ctx,
  4765. int32_t n_tokens,
  4766. int32_t kv_head,
  4767. const llm_build_cb & cb,
  4768. int64_t il) {
  4769. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  4770. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  4771. GGML_ASSERT(kv.size == n_ctx);
  4772. // compute the transposed [n_tokens, n_embd] V matrix
  4773. assert(v_cur->ne[0] == n_embd_v_gqa && v_cur->ne[1] == n_tokens);
  4774. struct ggml_tensor * v_cur_t = ggml_transpose(ctx, v_cur);
  4775. cb(v_cur_t, "v_cur_t", il);
  4776. struct ggml_tensor * k_cache_view = ggml_view_1d(ctx, kv.k_l[il], n_tokens*n_embd_k_gqa,
  4777. (ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa))*kv_head);
  4778. cb(k_cache_view, "k_cache_view", il);
  4779. struct ggml_tensor * v_cache_view = ggml_view_2d(ctx, kv.v_l[il], n_tokens, n_embd_v_gqa,
  4780. ( n_ctx)*ggml_element_size(kv.v_l[il]),
  4781. (kv_head)*ggml_element_size(kv.v_l[il]));
  4782. cb(v_cache_view, "v_cache_view", il);
  4783. // important: storing RoPE-ed version of K in the KV cache!
  4784. ggml_build_forward_expand(graph, ggml_cpy(ctx, k_cur, k_cache_view));
  4785. ggml_build_forward_expand(graph, ggml_cpy(ctx, v_cur_t, v_cache_view));
  4786. }
  4787. static struct ggml_tensor * llm_build_norm(
  4788. struct ggml_context * ctx,
  4789. struct ggml_tensor * cur,
  4790. const llama_hparams & hparams,
  4791. struct ggml_tensor * mw,
  4792. struct ggml_tensor * mb,
  4793. llm_norm_type type,
  4794. const llm_build_cb & cb,
  4795. int il) {
  4796. switch (type) {
  4797. case LLM_NORM: cur = ggml_norm (ctx, cur, hparams.f_norm_eps); break;
  4798. case LLM_NORM_RMS: cur = ggml_rms_norm(ctx, cur, hparams.f_norm_rms_eps); break;
  4799. }
  4800. if (mw || mb) {
  4801. cb(cur, "norm", il);
  4802. }
  4803. if (mw) {
  4804. cur = ggml_mul(ctx, cur, mw);
  4805. if (mb) {
  4806. cb(cur, "norm_w", il);
  4807. }
  4808. }
  4809. if (mb) {
  4810. cur = ggml_add(ctx, cur, mb);
  4811. }
  4812. return cur;
  4813. }
  4814. static struct ggml_tensor * llm_build_ffn(
  4815. struct ggml_context * ctx,
  4816. struct ggml_tensor * cur,
  4817. struct ggml_tensor * up,
  4818. struct ggml_tensor * up_b,
  4819. struct ggml_tensor * gate,
  4820. struct ggml_tensor * gate_b,
  4821. struct ggml_tensor * down,
  4822. struct ggml_tensor * down_b,
  4823. struct ggml_tensor * act_scales,
  4824. llm_ffn_op_type type_op,
  4825. llm_ffn_gate_type type_gate,
  4826. const llm_build_cb & cb,
  4827. int il) {
  4828. struct ggml_tensor * tmp = ggml_mul_mat(ctx, up, cur);
  4829. cb(tmp, "ffn_up", il);
  4830. if (up_b) {
  4831. tmp = ggml_add(ctx, tmp, up_b);
  4832. cb(tmp, "ffn_up_b", il);
  4833. }
  4834. if (gate) {
  4835. switch (type_gate) {
  4836. case LLM_FFN_SEQ:
  4837. {
  4838. cur = ggml_mul_mat(ctx, gate, tmp);
  4839. cb(cur, "ffn_gate", il);
  4840. } break;
  4841. case LLM_FFN_PAR:
  4842. {
  4843. cur = ggml_mul_mat(ctx, gate, cur);
  4844. cb(cur, "ffn_gate", il);
  4845. } break;
  4846. }
  4847. if (gate_b) {
  4848. cur = ggml_add(ctx, cur, gate_b);
  4849. cb(cur, "ffn_gate_b", il);
  4850. }
  4851. } else {
  4852. cur = tmp;
  4853. }
  4854. switch (type_op) {
  4855. case LLM_FFN_SILU:
  4856. {
  4857. cur = ggml_silu(ctx, cur);
  4858. cb(cur, "ffn_silu", il);
  4859. } break;
  4860. case LLM_FFN_GELU:
  4861. {
  4862. cur = ggml_gelu(ctx, cur);
  4863. cb(cur, "ffn_gelu", il);
  4864. if (act_scales != NULL) {
  4865. cur = ggml_div(ctx, cur, act_scales);
  4866. cb(cur, "ffn_act", il);
  4867. }
  4868. } break;
  4869. case LLM_FFN_RELU:
  4870. {
  4871. cur = ggml_relu(ctx, cur);
  4872. cb(cur, "ffn_relu", il);
  4873. } break;
  4874. case LLM_FFN_RELU_SQR:
  4875. {
  4876. cur = ggml_relu(ctx, cur);
  4877. cb(cur, "ffn_relu", il);
  4878. cur = ggml_sqr(ctx, cur);
  4879. cb(cur, "ffn_sqr(relu)", il);
  4880. } break;
  4881. }
  4882. if (type_gate == LLM_FFN_PAR) {
  4883. cur = ggml_mul(ctx, cur, tmp);
  4884. cb(cur, "ffn_gate_par", il);
  4885. }
  4886. cur = ggml_mul_mat(ctx, down, cur);
  4887. if (down_b) {
  4888. cb(cur, "ffn_down", il);
  4889. }
  4890. if (down_b) {
  4891. cur = ggml_add(ctx, cur, down_b);
  4892. }
  4893. return cur;
  4894. }
  4895. // if max_alibi_bias > 0 then apply ALiBi
  4896. static struct ggml_tensor * llm_build_kqv(
  4897. struct ggml_context * ctx,
  4898. const llama_model & model,
  4899. const llama_hparams & hparams,
  4900. const llama_kv_cache & kv,
  4901. struct ggml_cgraph * graph,
  4902. struct ggml_tensor * wo,
  4903. struct ggml_tensor * wo_b,
  4904. struct ggml_tensor * q_cur,
  4905. struct ggml_tensor * kq_mask,
  4906. struct ggml_tensor * kq_pos,
  4907. int64_t n_ctx,
  4908. int32_t n_tokens,
  4909. int32_t n_kv,
  4910. float kq_scale,
  4911. const llm_build_cb & cb,
  4912. int il) {
  4913. const int64_t n_head = hparams.n_head;
  4914. const int64_t n_head_kv = hparams.n_head_kv;
  4915. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  4916. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  4917. const int64_t n_embd_head_v = hparams.n_embd_head_v;
  4918. struct ggml_tensor * q = ggml_permute(ctx, q_cur, 0, 2, 1, 3);
  4919. cb(q, "q", il);
  4920. struct ggml_tensor * k =
  4921. ggml_view_3d(ctx, kv.k_l[il],
  4922. n_embd_head_k, n_kv, n_head_kv,
  4923. ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa),
  4924. ggml_row_size(kv.k_l[il]->type, n_embd_head_k),
  4925. 0);
  4926. cb(k, "k", il);
  4927. struct ggml_tensor * kq = ggml_mul_mat(ctx, k, q);
  4928. cb(kq, "kq", il);
  4929. if (model.arch == LLM_ARCH_PHI2) {
  4930. // for this arch, we need to perform the KQ multiplication with F32 precision, otherwise we get NaNs
  4931. // ref: https://github.com/ggerganov/llama.cpp/pull/4490#issuecomment-1859055847
  4932. ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  4933. }
  4934. if (model.arch == LLM_ARCH_GROK) {
  4935. // need to do the following:
  4936. // multiply by attn_output_multiplyer of 0.08838834764831845
  4937. // and then :
  4938. // kq = 30 * tanh(kq / 30)
  4939. // before the softmax below
  4940. //try from phi2
  4941. //ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  4942. kq = ggml_tanh(ctx, ggml_scale(ctx, kq, 0.08838834764831845f/30.0f));
  4943. kq = ggml_scale(ctx, kq, 30);
  4944. }
  4945. #if defined(GGML_USE_KOMPUTE)
  4946. #pragma message("TODO: ALiBi support in ggml_soft_max_ext is not implemented for Kompute")
  4947. #pragma message(" Falling back to ggml_alibi(). Will become an error in Mar 2024")
  4948. #pragma message("ref: https://github.com/ggerganov/llama.cpp/pull/5488")
  4949. if (hparams.f_max_alibi_bias > 0.0f) {
  4950. kq = ggml_scale(ctx, kq, kq_scale);
  4951. cb(kq, "kq_scaled", il);
  4952. kq = ggml_alibi(ctx, kq, /*n_past*/ 0, n_head, hparams.f_max_alibi_bias);
  4953. cb(kq, "kq_scaled_alibi", il);
  4954. kq = ggml_add(ctx, kq, kq_mask);
  4955. cb(kq, "kq_masked", il);
  4956. kq = ggml_soft_max(ctx, kq);
  4957. cb(kq, "kq_soft_max", il);
  4958. } else
  4959. #endif
  4960. {
  4961. kq = ggml_soft_max_ext(ctx, kq, kq_mask, kq_pos, kq_scale, hparams.f_max_alibi_bias);
  4962. cb(kq, "kq_soft_max_ext", il);
  4963. }
  4964. GGML_ASSERT(kv.size == n_ctx);
  4965. // split cached v into n_head heads
  4966. struct ggml_tensor * v =
  4967. ggml_view_3d(ctx, kv.v_l[il],
  4968. n_kv, n_embd_head_v, n_head_kv,
  4969. ggml_element_size(kv.v_l[il])*n_ctx,
  4970. ggml_element_size(kv.v_l[il])*n_ctx*n_embd_head_v,
  4971. 0);
  4972. cb(v, "v", il);
  4973. struct ggml_tensor * kqv = ggml_mul_mat(ctx, v, kq);
  4974. cb(kqv, "kqv", il);
  4975. struct ggml_tensor * kqv_merged = ggml_permute(ctx, kqv, 0, 2, 1, 3);
  4976. cb(kqv_merged, "kqv_merged", il);
  4977. struct ggml_tensor * cur = ggml_cont_2d(ctx, kqv_merged, n_embd_head_k*n_head, n_tokens);
  4978. cb(cur, "kqv_merged_cont", il);
  4979. ggml_build_forward_expand(graph, cur);
  4980. cur = ggml_mul_mat(ctx, wo, cur);
  4981. if (wo_b) {
  4982. cb(cur, "kqv_wo", il);
  4983. }
  4984. if (wo_b) {
  4985. cur = ggml_add(ctx, cur, wo_b);
  4986. }
  4987. return cur;
  4988. }
  4989. static struct ggml_tensor * llm_build_kv(
  4990. struct ggml_context * ctx,
  4991. const llama_model & model,
  4992. const llama_hparams & hparams,
  4993. const llama_kv_cache & kv,
  4994. struct ggml_cgraph * graph,
  4995. struct ggml_tensor * wo,
  4996. struct ggml_tensor * wo_b,
  4997. struct ggml_tensor * k_cur,
  4998. struct ggml_tensor * v_cur,
  4999. struct ggml_tensor * q_cur,
  5000. struct ggml_tensor * kq_mask,
  5001. struct ggml_tensor * kq_pos,
  5002. int64_t n_ctx,
  5003. int32_t n_tokens,
  5004. int32_t kv_head,
  5005. int32_t n_kv,
  5006. float kq_scale,
  5007. const llm_build_cb & cb,
  5008. int il) {
  5009. // these nodes are added to the graph together so that they are not reordered
  5010. // by doing so, the number of splits in the graph is reduced
  5011. ggml_build_forward_expand(graph, q_cur);
  5012. ggml_build_forward_expand(graph, k_cur);
  5013. ggml_build_forward_expand(graph, v_cur);
  5014. llm_build_kv_store(ctx, hparams, kv, graph, k_cur, v_cur, n_ctx, n_tokens, kv_head, cb, il);
  5015. struct ggml_tensor * cur;
  5016. cur = llm_build_kqv(ctx, model, hparams, kv, graph, wo, wo_b,
  5017. q_cur, kq_mask, kq_pos, n_ctx, n_tokens, n_kv, kq_scale, cb, il);
  5018. cb(cur, "kqv_out", il);
  5019. return cur;
  5020. }
  5021. struct llm_build_context {
  5022. const llama_model & model;
  5023. llama_context & lctx;
  5024. const llama_hparams & hparams;
  5025. const llama_cparams & cparams;
  5026. const llama_batch & batch;
  5027. const llama_kv_cache & kv_self;
  5028. const int64_t n_embd;
  5029. const int64_t n_layer;
  5030. const int64_t n_rot;
  5031. const int64_t n_ctx; // user-specified context size (can be different from n_ctx_train)
  5032. const int64_t n_head;
  5033. const int64_t n_head_kv;
  5034. const int64_t n_embd_head_k;
  5035. const int64_t n_embd_k_gqa;
  5036. const int64_t n_embd_head_v;
  5037. const int64_t n_embd_v_gqa;
  5038. const int64_t n_expert;
  5039. const int64_t n_expert_used;
  5040. const float freq_base;
  5041. const float freq_scale;
  5042. const float ext_factor;
  5043. const float attn_factor;
  5044. const float beta_fast;
  5045. const float beta_slow;
  5046. const float norm_eps;
  5047. const float norm_rms_eps;
  5048. const int32_t n_tokens;
  5049. const int32_t n_kv; // size of KV cache to consider (n_kv <= kv_self.size)
  5050. const int32_t n_outputs;
  5051. const int32_t kv_head; // index of where we store new KV data in the cache
  5052. const int32_t n_orig_ctx;
  5053. const enum llama_pooling_type pooling_type;
  5054. const enum llama_rope_type rope_type;
  5055. const llm_build_cb & cb;
  5056. std::vector<uint8_t> & buf_compute_meta;
  5057. struct ggml_context * ctx0 = nullptr;
  5058. // TODO: consider making the entire interface noexcept
  5059. llm_build_context(
  5060. llama_context & lctx,
  5061. const llama_batch & batch,
  5062. const llm_build_cb & cb,
  5063. bool worst_case) :
  5064. model (lctx.model),
  5065. lctx (lctx),
  5066. hparams (model.hparams),
  5067. cparams (lctx.cparams),
  5068. batch (batch),
  5069. kv_self (lctx.kv_self),
  5070. n_embd (hparams.n_embd),
  5071. n_layer (hparams.n_layer),
  5072. n_rot (hparams.n_rot),
  5073. n_ctx (cparams.n_ctx),
  5074. n_head (hparams.n_head),
  5075. n_head_kv (hparams.n_head_kv),
  5076. n_embd_head_k (hparams.n_embd_head_k),
  5077. n_embd_k_gqa (hparams.n_embd_k_gqa()),
  5078. n_embd_head_v (hparams.n_embd_head_v),
  5079. n_embd_v_gqa (hparams.n_embd_v_gqa()),
  5080. n_expert (hparams.n_expert),
  5081. n_expert_used (hparams.n_expert_used),
  5082. freq_base (cparams.rope_freq_base),
  5083. freq_scale (cparams.rope_freq_scale),
  5084. ext_factor (cparams.yarn_ext_factor),
  5085. attn_factor (cparams.yarn_attn_factor),
  5086. beta_fast (cparams.yarn_beta_fast),
  5087. beta_slow (cparams.yarn_beta_slow),
  5088. norm_eps (hparams.f_norm_eps),
  5089. norm_rms_eps (hparams.f_norm_rms_eps),
  5090. n_tokens (batch.n_tokens),
  5091. n_kv (worst_case ? kv_self.size : kv_self.n),
  5092. n_outputs (worst_case ? n_tokens : lctx.n_outputs),
  5093. kv_head (worst_case ? (kv_self.recurrent ? 0 : kv_self.size - n_tokens) : kv_self.head),
  5094. n_orig_ctx (cparams.n_yarn_orig_ctx),
  5095. pooling_type (cparams.pooling_type),
  5096. rope_type (hparams.rope_type),
  5097. cb (cb),
  5098. buf_compute_meta (lctx.buf_compute_meta) {
  5099. // all initializations should be done in init()
  5100. }
  5101. void init() {
  5102. struct ggml_init_params params = {
  5103. /*.mem_size =*/ buf_compute_meta.size(),
  5104. /*.mem_buffer =*/ buf_compute_meta.data(),
  5105. /*.no_alloc =*/ true,
  5106. };
  5107. ctx0 = ggml_init(params);
  5108. lctx.inp_tokens = nullptr;
  5109. lctx.inp_embd = nullptr;
  5110. lctx.inp_pos = nullptr;
  5111. lctx.inp_out_ids = nullptr;
  5112. lctx.inp_KQ_mask = nullptr;
  5113. lctx.inp_KQ_pos = nullptr;
  5114. lctx.inp_K_shift = nullptr;
  5115. lctx.inp_mean = nullptr;
  5116. lctx.inp_cls = nullptr;
  5117. lctx.inp_s_copy = nullptr;
  5118. lctx.inp_s_mask = nullptr;
  5119. lctx.inp_s_seq = nullptr;
  5120. }
  5121. void free() {
  5122. if (ctx0) {
  5123. ggml_free(ctx0);
  5124. ctx0 = nullptr;
  5125. }
  5126. }
  5127. struct ggml_cgraph * build_k_shift() {
  5128. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5129. GGML_ASSERT(kv_self.size == n_ctx);
  5130. lctx.inp_K_shift = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_ctx);
  5131. cb(lctx.inp_K_shift, "K_shift", -1);
  5132. ggml_set_input(lctx.inp_K_shift);
  5133. for (int il = 0; il < n_layer; ++il) {
  5134. struct ggml_tensor * tmp =
  5135. // we rotate only the first n_rot dimensions
  5136. ggml_rope_custom_inplace(ctx0,
  5137. ggml_view_3d(ctx0, kv_self.k_l[il],
  5138. n_embd_head_k, n_head_kv, n_ctx,
  5139. ggml_row_size(kv_self.k_l[il]->type, n_embd_head_k),
  5140. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  5141. 0),
  5142. lctx.inp_K_shift, n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5143. ext_factor, attn_factor, beta_fast, beta_slow);
  5144. cb(tmp, "K_shifted", il);
  5145. ggml_build_forward_expand(gf, tmp);
  5146. }
  5147. return gf;
  5148. }
  5149. struct ggml_cgraph * build_s_copy() {
  5150. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5151. GGML_ASSERT(kv_self.recurrent);
  5152. struct ggml_tensor * state_copy = build_inp_s_copy();
  5153. for (int il = 0; il < n_layer; ++il) {
  5154. struct ggml_tensor * conv_states = ggml_reshape_2d(ctx0, kv_self.k_l[il], hparams.n_embd_k_s(), kv_self.size);
  5155. struct ggml_tensor * ssm_states = ggml_reshape_2d(ctx0, kv_self.v_l[il], hparams.n_embd_v_s(), kv_self.size);
  5156. conv_states = ggml_get_rows(ctx0, conv_states, state_copy);
  5157. ssm_states = ggml_get_rows(ctx0, ssm_states, state_copy);
  5158. // TODO: name the intermediate tensors with cb()
  5159. ggml_build_forward_expand(gf, ggml_cpy(ctx0, conv_states, kv_self.k_l[il]));
  5160. ggml_build_forward_expand(gf, ggml_cpy(ctx0, ssm_states, kv_self.v_l[il]));
  5161. }
  5162. return gf;
  5163. }
  5164. struct ggml_cgraph * build_defrag(const std::vector<uint32_t> & ids) {
  5165. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5166. for (uint32_t i = 0; i < ids.size(); ++i) {
  5167. const uint32_t id = ids[i];
  5168. if (i == id || id == ids.size()) {
  5169. continue;
  5170. }
  5171. uint32_t nm = 1;
  5172. while (i + nm < ids.size() && ids[i + nm] == id + nm) {
  5173. nm++;
  5174. }
  5175. for (int il = 0; il < n_layer; ++il) {
  5176. ggml_tensor * view_k_src = ggml_view_2d(ctx0, kv_self.k_l[il],
  5177. n_embd_k_gqa, nm,
  5178. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  5179. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*i));
  5180. ggml_tensor * view_k_dst = ggml_view_2d(ctx0, kv_self.k_l[il],
  5181. n_embd_k_gqa, nm,
  5182. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  5183. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*id));
  5184. ggml_tensor * view_v_src = ggml_view_2d(ctx0, kv_self.v_l[il],
  5185. nm, n_embd_v_gqa,
  5186. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  5187. ggml_row_size(kv_self.v_l[il]->type, i));
  5188. ggml_tensor * view_v_dst = ggml_view_2d(ctx0, kv_self.v_l[il],
  5189. nm, n_embd_v_gqa,
  5190. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  5191. ggml_row_size(kv_self.v_l[il]->type, id));
  5192. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_k_src, view_k_dst));
  5193. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_v_src, view_v_dst));
  5194. }
  5195. i += nm - 1;
  5196. }
  5197. //LLAMA_LOG_INFO("gf->n_nodes = %d\n", gf->n_nodes);
  5198. return gf;
  5199. }
  5200. struct ggml_tensor * build_inp_pos() {
  5201. lctx.inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  5202. cb(lctx.inp_pos, "inp_pos", -1);
  5203. ggml_set_input(lctx.inp_pos);
  5204. return lctx.inp_pos;
  5205. }
  5206. struct ggml_tensor * build_inp_out_ids() {
  5207. lctx.inp_out_ids = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_outputs);
  5208. cb(lctx.inp_out_ids, "inp_out_ids", -1);
  5209. ggml_set_input(lctx.inp_out_ids);
  5210. return lctx.inp_out_ids;
  5211. }
  5212. struct ggml_tensor * build_inp_KQ_mask(bool causal = true) {
  5213. if (causal) {
  5214. lctx.inp_KQ_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_kv, n_tokens);
  5215. } else {
  5216. lctx.inp_KQ_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, n_tokens);
  5217. }
  5218. cb(lctx.inp_KQ_mask, "KQ_mask", -1);
  5219. ggml_set_input(lctx.inp_KQ_mask);
  5220. return lctx.inp_KQ_mask;
  5221. }
  5222. struct ggml_tensor * build_inp_KQ_pos() {
  5223. lctx.inp_KQ_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, n_kv);
  5224. cb(lctx.inp_KQ_pos, "KQ_pos", -1);
  5225. ggml_set_input(lctx.inp_KQ_pos);
  5226. return lctx.inp_KQ_pos;
  5227. }
  5228. struct ggml_tensor * build_inp_mean() {
  5229. lctx.inp_mean = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, n_tokens);
  5230. cb(lctx.inp_mean, "inp_mean", -1);
  5231. ggml_set_input(lctx.inp_mean);
  5232. return lctx.inp_mean;
  5233. }
  5234. struct ggml_tensor * build_inp_cls() {
  5235. lctx.inp_cls = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  5236. cb(lctx.inp_cls, "inp_cls", -1);
  5237. ggml_set_input(lctx.inp_cls);
  5238. return lctx.inp_cls;
  5239. }
  5240. struct ggml_tensor * build_inp_s_copy() {
  5241. lctx.inp_s_copy = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, kv_self.size);
  5242. cb(lctx.inp_s_copy, "inp_s_copy", -1);
  5243. ggml_set_input(lctx.inp_s_copy);
  5244. return lctx.inp_s_copy;
  5245. }
  5246. struct ggml_tensor * build_inp_s_mask() {
  5247. lctx.inp_s_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, 1, n_kv);
  5248. cb(lctx.inp_s_mask, "inp_s_mask", -1);
  5249. ggml_set_input(lctx.inp_s_mask);
  5250. return lctx.inp_s_mask;
  5251. }
  5252. struct ggml_tensor * build_inp_s_seq() {
  5253. lctx.inp_s_seq = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_kv, n_tokens);
  5254. cb(lctx.inp_s_seq, "inp_s_seq", -1);
  5255. ggml_set_input(lctx.inp_s_seq);
  5256. return lctx.inp_s_seq;
  5257. }
  5258. struct ggml_cgraph * build_llama() {
  5259. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5260. // mutable variable, needed during the last layer of the computation to skip unused tokens
  5261. int32_t n_tokens = this->n_tokens;
  5262. const int64_t n_embd_head = hparams.n_embd_head_v;
  5263. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5264. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5265. struct ggml_tensor * cur;
  5266. struct ggml_tensor * inpL;
  5267. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5268. // inp_pos - contains the positions
  5269. struct ggml_tensor * inp_pos = build_inp_pos();
  5270. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5271. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5272. for (int il = 0; il < n_layer; ++il) {
  5273. struct ggml_tensor * inpSA = inpL;
  5274. // norm
  5275. cur = llm_build_norm(ctx0, inpL, hparams,
  5276. model.layers[il].attn_norm, NULL,
  5277. LLM_NORM_RMS, cb, il);
  5278. cb(cur, "attn_norm", il);
  5279. // self-attention
  5280. {
  5281. // compute Q and K and RoPE them
  5282. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5283. cb(Qcur, "Qcur", il);
  5284. if (model.layers[il].bq) {
  5285. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5286. cb(Qcur, "Qcur", il);
  5287. }
  5288. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5289. cb(Kcur, "Kcur", il);
  5290. if (model.layers[il].bk) {
  5291. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5292. cb(Kcur, "Kcur", il);
  5293. }
  5294. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5295. cb(Vcur, "Vcur", il);
  5296. if (model.layers[il].bv) {
  5297. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  5298. cb(Vcur, "Vcur", il);
  5299. }
  5300. Qcur = ggml_rope_custom(
  5301. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5302. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5303. ext_factor, attn_factor, beta_fast, beta_slow
  5304. );
  5305. cb(Qcur, "Qcur", il);
  5306. Kcur = ggml_rope_custom(
  5307. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5308. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5309. ext_factor, attn_factor, beta_fast, beta_slow
  5310. );
  5311. cb(Kcur, "Kcur", il);
  5312. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5313. model.layers[il].wo, model.layers[il].bo,
  5314. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5315. }
  5316. if (il == n_layer - 1) {
  5317. // skip computing output for unused tokens
  5318. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  5319. n_tokens = n_outputs;
  5320. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  5321. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  5322. }
  5323. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5324. cb(ffn_inp, "ffn_inp", il);
  5325. // feed-forward network
  5326. if (model.layers[il].ffn_gate_inp == nullptr) {
  5327. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5328. model.layers[il].ffn_norm, NULL,
  5329. LLM_NORM_RMS, cb, il);
  5330. cb(cur, "ffn_norm", il);
  5331. cur = llm_build_ffn(ctx0, cur,
  5332. model.layers[il].ffn_up, NULL,
  5333. model.layers[il].ffn_gate, NULL,
  5334. model.layers[il].ffn_down, NULL,
  5335. NULL,
  5336. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5337. cb(cur, "ffn_out", il);
  5338. } else {
  5339. // MoE branch
  5340. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5341. model.layers[il].ffn_norm, NULL,
  5342. LLM_NORM_RMS, cb, il);
  5343. cb(cur, "ffn_norm", il);
  5344. ggml_tensor * logits = ggml_mul_mat(ctx0, model.layers[il].ffn_gate_inp, cur); // [n_tokens, num_experts]
  5345. cb(logits, "ffn_moe_logits", il);
  5346. ggml_tensor * probs = ggml_soft_max(ctx0, logits); // [n_tokens, num_experts]
  5347. cb(probs, "ffn_moe_probs", il);
  5348. // select experts
  5349. ggml_tensor * selected_experts = ggml_top_k(ctx0, probs, n_expert_used); // [n_tokens, num_experts_per_tok]
  5350. cb(selected_experts->src[0], "ffn_moe_argsort", il);
  5351. ggml_tensor * weights = ggml_get_rows(ctx0,
  5352. ggml_reshape_3d(ctx0, probs, 1, n_expert, n_tokens), selected_experts);
  5353. cb(weights, "ffn_moe_weights", il);
  5354. weights = ggml_reshape_2d(ctx0, weights, n_expert_used, n_tokens); // [n_tokens, num_experts_per_tok]
  5355. ggml_tensor * weights_sum = ggml_sum_rows(ctx0, weights);
  5356. cb(weights_sum, "ffn_moe_weights_sum", il);
  5357. weights = ggml_div(ctx0, weights, weights_sum); // [n_tokens, num_experts_per_tok]
  5358. cb(weights, "ffn_moe_weights_norm", il);
  5359. // compute expert outputs
  5360. ggml_tensor * moe_out = nullptr;
  5361. for (int i = 0; i < n_expert_used; ++i) {
  5362. ggml_tensor * cur_expert;
  5363. ggml_tensor * cur_up = ggml_mul_mat_id(ctx0, model.layers[il].ffn_up_exp, n_expert, selected_experts, i, cur);
  5364. cb(cur_up, "ffn_moe_up", il);
  5365. ggml_tensor * cur_gate = ggml_mul_mat_id(ctx0, model.layers[il].ffn_gate_exp, n_expert, selected_experts, i, cur);
  5366. cb(cur_gate, "ffn_moe_gate", il);
  5367. cur_gate = ggml_silu(ctx0, cur_gate);
  5368. cb(cur_gate, "ffn_moe_silu", il);
  5369. cur_expert = ggml_mul(ctx0, cur_up, cur_gate); // [n_tokens, n_embd]
  5370. cb(cur_expert, "ffn_moe_gate_par", il);
  5371. cur_expert = ggml_mul_mat_id(ctx0, model.layers[il].ffn_down_exp, n_expert, selected_experts, i, cur_expert); // [n_tokens, n_embd]
  5372. cb(cur_expert, "ffn_moe_down", il);
  5373. cur_expert = ggml_mul(ctx0, cur_expert,
  5374. ggml_view_2d(ctx0, weights, 1, n_tokens, weights->nb[1], i*weights->nb[0]));
  5375. cb(cur_expert, "ffn_moe_weighted", il);
  5376. if (i == 0) {
  5377. moe_out = cur_expert;
  5378. } else {
  5379. moe_out = ggml_add(ctx0, moe_out, cur_expert);
  5380. cb(moe_out, "ffn_moe_out", il);
  5381. }
  5382. }
  5383. cur = moe_out;
  5384. }
  5385. cur = ggml_add(ctx0, cur, ffn_inp);
  5386. cb(cur, "ffn_out", il);
  5387. ggml_tensor * layer_dir = lctx.cvec.tensor_for(il);
  5388. if (layer_dir != nullptr) {
  5389. cur = ggml_add(ctx0, cur, layer_dir);
  5390. }
  5391. cb(cur, "l_out", il);
  5392. // input for next layer
  5393. inpL = cur;
  5394. }
  5395. cur = inpL;
  5396. cur = llm_build_norm(ctx0, cur, hparams,
  5397. model.output_norm, NULL,
  5398. LLM_NORM_RMS, cb, -1);
  5399. cb(cur, "result_norm", -1);
  5400. // lm_head
  5401. cur = ggml_mul_mat(ctx0, model.output, cur);
  5402. cb(cur, "result_output", -1);
  5403. ggml_build_forward_expand(gf, cur);
  5404. return gf;
  5405. }
  5406. struct ggml_cgraph * build_baichuan() {
  5407. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5408. const int64_t n_embd_head = hparams.n_embd_head_v;
  5409. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5410. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5411. struct ggml_tensor * cur;
  5412. struct ggml_tensor * inpL;
  5413. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5414. // inp_pos - contains the positions
  5415. struct ggml_tensor * inp_pos = model.type == MODEL_7B ? build_inp_pos() : nullptr;
  5416. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5417. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5418. // positions of the tokens in the KV cache
  5419. struct ggml_tensor * KQ_pos = build_inp_KQ_pos();
  5420. for (int il = 0; il < n_layer; ++il) {
  5421. struct ggml_tensor * inpSA = inpL;
  5422. cur = llm_build_norm(ctx0, inpL, hparams,
  5423. model.layers[il].attn_norm, NULL,
  5424. LLM_NORM_RMS, cb, il);
  5425. cb(cur, "attn_norm", il);
  5426. // self-attention
  5427. {
  5428. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5429. cb(Qcur, "Qcur", il);
  5430. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5431. cb(Kcur, "Kcur", il);
  5432. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5433. cb(Vcur, "Vcur", il);
  5434. switch (model.type) {
  5435. case MODEL_7B:
  5436. Qcur = ggml_rope_custom(
  5437. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5438. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5439. ext_factor, attn_factor, beta_fast, beta_slow
  5440. );
  5441. Kcur = ggml_rope_custom(
  5442. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5443. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5444. ext_factor, attn_factor, beta_fast, beta_slow
  5445. );
  5446. break;
  5447. case MODEL_13B:
  5448. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd/n_head, n_head, n_tokens);
  5449. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd/n_head, n_head, n_tokens);
  5450. break;
  5451. default:
  5452. GGML_ASSERT(false);
  5453. }
  5454. cb(Qcur, "Qcur", il);
  5455. cb(Kcur, "Kcur", il);
  5456. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5457. model.layers[il].wo, NULL,
  5458. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5459. }
  5460. if (il == n_layer - 1) {
  5461. // skip computing output for unused tokens
  5462. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  5463. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  5464. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  5465. }
  5466. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5467. cb(ffn_inp, "ffn_inp", il);
  5468. // feed-forward network
  5469. {
  5470. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5471. model.layers[il].ffn_norm, NULL,
  5472. LLM_NORM_RMS, cb, il);
  5473. cb(cur, "ffn_norm", il);
  5474. cur = llm_build_ffn(ctx0, cur,
  5475. model.layers[il].ffn_up, NULL,
  5476. model.layers[il].ffn_gate, NULL,
  5477. model.layers[il].ffn_down, NULL,
  5478. NULL,
  5479. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5480. cb(cur, "ffn_out", il);
  5481. }
  5482. cur = ggml_add(ctx0, cur, ffn_inp);
  5483. cb(cur, "l_out", il);
  5484. // input for next layer
  5485. inpL = cur;
  5486. }
  5487. cur = inpL;
  5488. cur = llm_build_norm(ctx0, cur, hparams,
  5489. model.output_norm, NULL,
  5490. LLM_NORM_RMS, cb, -1);
  5491. cb(cur, "result_norm", -1);
  5492. // lm_head
  5493. cur = ggml_mul_mat(ctx0, model.output, cur);
  5494. cb(cur, "result_output", -1);
  5495. ggml_build_forward_expand(gf, cur);
  5496. return gf;
  5497. }
  5498. struct ggml_cgraph * build_xverse() {
  5499. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5500. const int64_t n_embd_head = hparams.n_embd_head_v;
  5501. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5502. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5503. struct ggml_tensor * cur;
  5504. struct ggml_tensor * inpL;
  5505. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5506. // inp_pos - contains the positions
  5507. struct ggml_tensor * inp_pos = build_inp_pos();
  5508. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5509. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5510. // positions of the tokens in the KV cache
  5511. struct ggml_tensor * KQ_pos = build_inp_KQ_pos();
  5512. for (int il = 0; il < n_layer; ++il) {
  5513. struct ggml_tensor * inpSA = inpL;
  5514. cur = llm_build_norm(ctx0, inpL, hparams,
  5515. model.layers[il].attn_norm, NULL,
  5516. LLM_NORM_RMS, cb, il);
  5517. cb(cur, "attn_norm", il);
  5518. // self-attention
  5519. {
  5520. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5521. cb(Qcur, "Qcur", il);
  5522. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5523. cb(Kcur, "Kcur", il);
  5524. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5525. cb(Vcur, "Vcur", il);
  5526. Qcur = ggml_rope_custom(
  5527. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5528. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5529. ext_factor, attn_factor, beta_fast, beta_slow
  5530. );
  5531. cb(Qcur, "Qcur", il);
  5532. Kcur = ggml_rope_custom(
  5533. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5534. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5535. ext_factor, attn_factor, beta_fast, beta_slow
  5536. );
  5537. cb(Kcur, "Kcur", il);
  5538. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5539. model.layers[il].wo, NULL,
  5540. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5541. }
  5542. if (il == n_layer - 1) {
  5543. // skip computing output for unused tokens
  5544. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  5545. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  5546. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  5547. }
  5548. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5549. cb(ffn_inp, "ffn_inp", il);
  5550. // feed-forward network
  5551. {
  5552. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5553. model.layers[il].ffn_norm, NULL,
  5554. LLM_NORM_RMS, cb, il);
  5555. cb(cur, "ffn_norm", il);
  5556. cur = llm_build_ffn(ctx0, cur,
  5557. model.layers[il].ffn_up, NULL,
  5558. model.layers[il].ffn_gate, NULL,
  5559. model.layers[il].ffn_down, NULL,
  5560. NULL,
  5561. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5562. cb(cur, "ffn_out", il);
  5563. }
  5564. cur = ggml_add(ctx0, cur, ffn_inp);
  5565. cb(cur, "l_out", il);
  5566. // input for next layer
  5567. inpL = cur;
  5568. }
  5569. cur = inpL;
  5570. cur = llm_build_norm(ctx0, cur, hparams, model.output_norm, NULL, LLM_NORM_RMS, cb, -1);
  5571. cb(cur, "result_norm", -1);
  5572. // lm_head
  5573. cur = ggml_mul_mat(ctx0, model.output, cur);
  5574. cb(cur, "result_output", -1);
  5575. ggml_build_forward_expand(gf, cur);
  5576. return gf;
  5577. }
  5578. struct ggml_cgraph * build_falcon() {
  5579. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5580. const int64_t n_embd_head = hparams.n_embd_head_v;
  5581. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5582. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5583. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5584. struct ggml_tensor * cur;
  5585. struct ggml_tensor * inpL;
  5586. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5587. // inp_pos - contains the positions
  5588. struct ggml_tensor * inp_pos = build_inp_pos();
  5589. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5590. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5591. for (int il = 0; il < n_layer; ++il) {
  5592. struct ggml_tensor * attn_norm;
  5593. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  5594. model.layers[il].attn_norm,
  5595. model.layers[il].attn_norm_b,
  5596. LLM_NORM, cb, il);
  5597. cb(attn_norm, "attn_norm", il);
  5598. // self-attention
  5599. {
  5600. if (model.layers[il].attn_norm_2) {
  5601. // Falcon-40B
  5602. cur = llm_build_norm(ctx0, inpL, hparams,
  5603. model.layers[il].attn_norm_2,
  5604. model.layers[il].attn_norm_2_b,
  5605. LLM_NORM, cb, il);
  5606. cb(cur, "attn_norm_2", il);
  5607. } else {
  5608. cur = attn_norm;
  5609. }
  5610. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5611. cb(cur, "wqkv", il);
  5612. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5613. 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)));
  5614. 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)));
  5615. cb(Qcur, "Qcur", il);
  5616. cb(Kcur, "Kcur", il);
  5617. cb(Vcur, "Vcur", il);
  5618. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5619. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  5620. // using mode = 2 for neox mode
  5621. Qcur = ggml_rope_custom(
  5622. ctx0, Qcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5623. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5624. );
  5625. cb(Qcur, "Qcur", il);
  5626. Kcur = ggml_rope_custom(
  5627. ctx0, Kcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5628. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5629. );
  5630. cb(Kcur, "Kcur", il);
  5631. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5632. model.layers[il].wo, NULL,
  5633. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5634. }
  5635. if (il == n_layer - 1) {
  5636. // skip computing output for unused tokens
  5637. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  5638. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  5639. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  5640. attn_norm = ggml_get_rows(ctx0, attn_norm, inp_out_ids);
  5641. }
  5642. struct ggml_tensor * ffn_inp = cur;
  5643. // feed forward
  5644. {
  5645. cur = llm_build_ffn(ctx0, attn_norm, // !! use the attn norm, not the result
  5646. model.layers[il].ffn_up, NULL,
  5647. NULL, NULL,
  5648. model.layers[il].ffn_down, NULL,
  5649. NULL,
  5650. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5651. cb(cur, "ffn_out", il);
  5652. }
  5653. cur = ggml_add(ctx0, cur, ffn_inp);
  5654. cb(cur, "l_out", il);
  5655. cur = ggml_add(ctx0, cur, inpL);
  5656. cb(cur, "l_out", il);
  5657. // input for next layer
  5658. inpL = cur;
  5659. }
  5660. cur = inpL;
  5661. // norm
  5662. cur = llm_build_norm(ctx0, cur, hparams,
  5663. model.output_norm,
  5664. model.output_norm_b,
  5665. LLM_NORM, cb, -1);
  5666. cb(cur, "result_norm", -1);
  5667. cur = ggml_mul_mat(ctx0, model.output, cur);
  5668. cb(cur, "result_output", -1);
  5669. ggml_build_forward_expand(gf, cur);
  5670. return gf;
  5671. }
  5672. struct ggml_cgraph * build_grok() {
  5673. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5674. // mutable variable, needed during the last layer of the computation to skip unused tokens
  5675. int32_t n_tokens = this->n_tokens;
  5676. const int64_t n_embd_head = hparams.n_embd_head_v;
  5677. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5678. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5679. struct ggml_tensor * cur;
  5680. struct ggml_tensor * inpL;
  5681. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5682. // multiply by embedding_multiplier_scale of 78.38367176906169
  5683. inpL = ggml_scale(ctx0, inpL, 78.38367176906169f);
  5684. // inp_pos - contains the positions
  5685. struct ggml_tensor * inp_pos = build_inp_pos();
  5686. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5687. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5688. for (int il = 0; il < n_layer; ++il) {
  5689. struct ggml_tensor * inpSA = inpL;
  5690. // norm
  5691. cur = llm_build_norm(ctx0, inpL, hparams,
  5692. model.layers[il].attn_norm, NULL,
  5693. LLM_NORM_RMS, cb, il);
  5694. cb(cur, "attn_norm", il);
  5695. // self-attention
  5696. {
  5697. // compute Q and K and RoPE them
  5698. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5699. cb(Qcur, "Qcur", il);
  5700. if (model.layers[il].bq) {
  5701. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5702. cb(Qcur, "Qcur", il);
  5703. }
  5704. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5705. cb(Kcur, "Kcur", il);
  5706. if (model.layers[il].bk) {
  5707. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5708. cb(Kcur, "Kcur", il);
  5709. }
  5710. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5711. cb(Vcur, "Vcur", il);
  5712. if (model.layers[il].bv) {
  5713. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  5714. cb(Vcur, "Vcur", il);
  5715. }
  5716. Qcur = ggml_rope_custom(
  5717. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5718. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5719. ext_factor, attn_factor, beta_fast, beta_slow
  5720. );
  5721. cb(Qcur, "Qcur", il);
  5722. Kcur = ggml_rope_custom(
  5723. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5724. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5725. ext_factor, attn_factor, beta_fast, beta_slow
  5726. );
  5727. cb(Kcur, "Kcur", il);
  5728. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5729. model.layers[il].wo, model.layers[il].bo,
  5730. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  5731. }
  5732. if (il == n_layer - 1) {
  5733. // skip computing output for unused tokens
  5734. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  5735. n_tokens = n_outputs;
  5736. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  5737. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  5738. }
  5739. // Grok
  5740. // if attn_out_norm is present then apply it before adding the input
  5741. if (model.layers[il].attn_out_norm) {
  5742. cur = llm_build_norm(ctx0, cur, hparams,
  5743. model.layers[il].attn_out_norm, NULL,
  5744. LLM_NORM_RMS, cb, il);
  5745. cb(cur, "attn_out_norm", il);
  5746. }
  5747. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5748. cb(ffn_inp, "ffn_inp", il);
  5749. // feed-forward network
  5750. // MoE branch
  5751. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5752. model.layers[il].ffn_norm, NULL,
  5753. LLM_NORM_RMS, cb, il);
  5754. cb(cur, "ffn_norm", il);
  5755. ggml_tensor * logits = ggml_mul_mat(ctx0, model.layers[il].ffn_gate_inp, cur); // [n_tokens, num_experts]
  5756. cb(logits, "ffn_moe_logits", il);
  5757. ggml_tensor * probs = ggml_soft_max(ctx0, logits); // [n_tokens, num_experts]
  5758. cb(probs, "ffn_moe_probs", il);
  5759. // select experts
  5760. ggml_tensor * selected_experts = ggml_top_k(ctx0, probs, n_expert_used); // [n_tokens, num_experts_per_tok]
  5761. cb(selected_experts->src[0], "ffn_moe_argsort", il);
  5762. ggml_tensor * weights = ggml_get_rows(ctx0,
  5763. ggml_reshape_3d(ctx0, probs, 1, n_expert, n_tokens), selected_experts);
  5764. cb(weights, "ffn_moe_weights", il);
  5765. weights = ggml_reshape_2d(ctx0, weights, n_expert_used, n_tokens); // [n_tokens, num_experts_per_tok]
  5766. ggml_tensor * weights_sum = ggml_sum_rows(ctx0, weights);
  5767. cb(weights_sum, "ffn_moe_weights_sum", il);
  5768. weights = ggml_div(ctx0, weights, weights_sum); // [n_tokens, num_experts_per_tok]
  5769. cb(weights, "ffn_moe_weights_norm", il);
  5770. // compute expert outputs
  5771. ggml_tensor * moe_out = nullptr;
  5772. for (int i = 0; i < n_expert_used; ++i) {
  5773. ggml_tensor * cur_expert;
  5774. ggml_tensor * cur_up = ggml_mul_mat_id(ctx0, model.layers[il].ffn_up_exp, n_expert, selected_experts, i, cur);
  5775. cb(cur_up, "ffn_moe_up", il);
  5776. ggml_tensor * cur_gate = ggml_mul_mat_id(ctx0, model.layers[il].ffn_gate_exp, n_expert, selected_experts, i, cur);
  5777. cb(cur_gate, "ffn_moe_gate", il);
  5778. //GeLU
  5779. cur_gate = ggml_gelu(ctx0, cur_gate);
  5780. cb(cur_gate, "ffn_moe_gelu", il);
  5781. cur_expert = ggml_mul(ctx0, cur_up, cur_gate); // [n_tokens, n_embd]
  5782. cb(cur_expert, "ffn_moe_gate_par", il);
  5783. cur_expert = ggml_mul_mat_id(ctx0, model.layers[il].ffn_down_exp, n_expert, selected_experts, i, cur_expert); // [n_tokens, n_embd]
  5784. cb(cur_expert, "ffn_moe_down", il);
  5785. cur_expert = ggml_mul(ctx0, cur_expert,
  5786. ggml_view_2d(ctx0, weights, 1, n_tokens, weights->nb[1], i*weights->nb[0]));
  5787. cb(cur_expert, "ffn_moe_weighted", il);
  5788. if (i == 0) {
  5789. moe_out = cur_expert;
  5790. } else {
  5791. moe_out = ggml_add(ctx0, moe_out, cur_expert);
  5792. cb(moe_out, "ffn_moe_out", il);
  5793. }
  5794. }
  5795. cur = moe_out;
  5796. // Grok
  5797. // if layer_out_norm is present then apply it before adding the input
  5798. // Idea: maybe ffn_out_norm is a better name
  5799. if (model.layers[il].layer_out_norm) {
  5800. cur = llm_build_norm(ctx0, cur, hparams,
  5801. model.layers[il].layer_out_norm, NULL,
  5802. LLM_NORM_RMS, cb, il);
  5803. cb(cur, "layer_out_norm", il);
  5804. }
  5805. cur = ggml_add(ctx0, cur, ffn_inp);
  5806. cb(cur, "ffn_out", il);
  5807. ggml_tensor * layer_dir = lctx.cvec.tensor_for(il);
  5808. if (layer_dir != nullptr) {
  5809. cur = ggml_add(ctx0, cur, layer_dir);
  5810. }
  5811. cb(cur, "l_out", il);
  5812. // input for next layer
  5813. inpL = cur;
  5814. }
  5815. cur = inpL;
  5816. cur = llm_build_norm(ctx0, cur, hparams,
  5817. model.output_norm, NULL,
  5818. LLM_NORM_RMS, cb, -1);
  5819. cb(cur, "result_norm", -1);
  5820. // lm_head
  5821. cur = ggml_mul_mat(ctx0, model.output, cur);
  5822. // Grok
  5823. // multiply logits by output_multiplier_scale of 0.5773502691896257
  5824. cur = ggml_scale(ctx0, cur, 0.5773502691896257f);
  5825. cb(cur, "result_output", -1);
  5826. ggml_build_forward_expand(gf, cur);
  5827. return gf;
  5828. }
  5829. struct ggml_cgraph * build_starcoder() {
  5830. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5831. const int64_t n_embd_head = hparams.n_embd_head_v;
  5832. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5833. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5834. struct ggml_tensor * cur;
  5835. struct ggml_tensor * inpL;
  5836. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5837. // inp_pos - contains the positions
  5838. struct ggml_tensor * inp_pos = build_inp_pos();
  5839. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5840. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5841. struct ggml_tensor * pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  5842. cb(pos, "pos_embd", -1);
  5843. inpL = ggml_add(ctx0, inpL, pos);
  5844. cb(inpL, "inpL", -1);
  5845. for (int il = 0; il < n_layer; ++il) {
  5846. cur = llm_build_norm(ctx0, inpL, hparams,
  5847. model.layers[il].attn_norm,
  5848. model.layers[il].attn_norm_b,
  5849. LLM_NORM, cb, il);
  5850. cb(cur, "attn_norm", il);
  5851. // self-attention
  5852. {
  5853. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5854. cb(cur, "wqkv", il);
  5855. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5856. cb(cur, "bqkv", il);
  5857. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5858. 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)));
  5859. 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)));
  5860. cb(Qcur, "Qcur", il);
  5861. cb(Kcur, "Kcur", il);
  5862. cb(Vcur, "Vcur", il);
  5863. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5864. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5865. model.layers[il].wo, model.layers[il].bo,
  5866. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5867. }
  5868. if (il == n_layer - 1) {
  5869. // skip computing output for unused tokens
  5870. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  5871. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  5872. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  5873. }
  5874. // add the input
  5875. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5876. cb(ffn_inp, "ffn_inp", il);
  5877. // FF
  5878. {
  5879. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5880. model.layers[il].ffn_norm,
  5881. model.layers[il].ffn_norm_b,
  5882. LLM_NORM, cb, il);
  5883. cb(cur, "ffn_norm", il);
  5884. cur = llm_build_ffn(ctx0, cur,
  5885. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5886. NULL, NULL,
  5887. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5888. NULL,
  5889. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5890. cb(cur, "ffn_out", il);
  5891. }
  5892. inpL = ggml_add(ctx0, cur, ffn_inp);
  5893. cb(inpL, "l_out", il);
  5894. }
  5895. cur = llm_build_norm(ctx0, inpL, hparams,
  5896. model.output_norm,
  5897. model.output_norm_b,
  5898. LLM_NORM, cb, -1);
  5899. cb(cur, "result_norm", -1);
  5900. cur = ggml_mul_mat(ctx0, model.output, cur);
  5901. cb(cur, "result_output", -1);
  5902. ggml_build_forward_expand(gf, cur);
  5903. return gf;
  5904. }
  5905. struct ggml_cgraph * build_persimmon() {
  5906. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5907. const int64_t n_embd_head = hparams.n_embd_head_v;
  5908. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5909. GGML_ASSERT(n_embd_head/2 == hparams.n_rot);
  5910. struct ggml_tensor * cur;
  5911. struct ggml_tensor * inpL;
  5912. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5913. // inp_pos - contains the positions
  5914. struct ggml_tensor * inp_pos = build_inp_pos();
  5915. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5916. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5917. for (int il = 0; il < n_layer; ++il) {
  5918. struct ggml_tensor * residual = inpL;
  5919. cur = llm_build_norm(ctx0, inpL, hparams,
  5920. model.layers[il].attn_norm,
  5921. model.layers[il].attn_norm_b,
  5922. LLM_NORM, cb, il);
  5923. cb(cur, "attn_norm", il);
  5924. // self attention
  5925. {
  5926. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5927. cb(cur, "wqkv", il);
  5928. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5929. cb(cur, "bqkv", il);
  5930. // split qkv
  5931. GGML_ASSERT(n_head_kv == n_head);
  5932. struct ggml_tensor * tmpqkv = ggml_reshape_4d(ctx0, cur, n_embd_head, 3, n_head, n_tokens);
  5933. cb(tmpqkv, "tmpqkv", il);
  5934. struct ggml_tensor * tmpqkv_perm = ggml_cont(ctx0, ggml_permute(ctx0, tmpqkv, 0, 3, 1, 2));
  5935. cb(tmpqkv_perm, "tmpqkv", il);
  5936. struct ggml_tensor * tmpq = ggml_view_3d(
  5937. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  5938. ggml_element_size(tmpqkv_perm) * n_embd_head,
  5939. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  5940. 0
  5941. );
  5942. cb(tmpq, "tmpq", il);
  5943. struct ggml_tensor * tmpk = ggml_view_3d(
  5944. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  5945. ggml_element_size(tmpqkv_perm) * n_embd_head,
  5946. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  5947. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens
  5948. );
  5949. cb(tmpk, "tmpk", il);
  5950. // Q/K Layernorm
  5951. tmpq = llm_build_norm(ctx0, tmpq, hparams,
  5952. model.layers[il].attn_q_norm,
  5953. model.layers[il].attn_q_norm_b,
  5954. LLM_NORM, cb, il);
  5955. cb(tmpq, "tmpq", il);
  5956. tmpk = llm_build_norm(ctx0, tmpk, hparams,
  5957. model.layers[il].attn_k_norm,
  5958. model.layers[il].attn_k_norm_b,
  5959. LLM_NORM, cb, il);
  5960. cb(tmpk, "tmpk", il);
  5961. // RoPE the first n_rot of q/k, pass the other half, and concat.
  5962. struct ggml_tensor * qrot = ggml_view_3d(
  5963. ctx0, tmpq, n_rot, n_head, n_tokens,
  5964. ggml_element_size(tmpq) * n_embd_head,
  5965. ggml_element_size(tmpq) * n_embd_head * n_head,
  5966. 0
  5967. );
  5968. cb(qrot, "qrot", il);
  5969. struct ggml_tensor * krot = ggml_view_3d(
  5970. ctx0, tmpk, n_rot, n_head, n_tokens,
  5971. ggml_element_size(tmpk) * n_embd_head,
  5972. ggml_element_size(tmpk) * n_embd_head * n_head,
  5973. 0
  5974. );
  5975. cb(krot, "krot", il);
  5976. // get the second half of tmpq, e.g tmpq[n_rot:, :, :]
  5977. struct ggml_tensor * qpass = ggml_view_3d(
  5978. ctx0, tmpq, n_rot, n_head, n_tokens,
  5979. ggml_element_size(tmpq) * n_embd_head,
  5980. ggml_element_size(tmpq) * n_embd_head * n_head,
  5981. ggml_element_size(tmpq) * n_rot
  5982. );
  5983. cb(qpass, "qpass", il);
  5984. struct ggml_tensor * kpass = ggml_view_3d(
  5985. ctx0, tmpk, n_rot, n_head, n_tokens,
  5986. ggml_element_size(tmpk) * n_embd_head,
  5987. ggml_element_size(tmpk) * n_embd_head * n_head,
  5988. ggml_element_size(tmpk) * n_rot
  5989. );
  5990. cb(kpass, "kpass", il);
  5991. struct ggml_tensor * qrotated = ggml_rope_custom(
  5992. ctx0, qrot, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5993. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5994. );
  5995. cb(qrotated, "qrotated", il);
  5996. struct ggml_tensor * krotated = ggml_rope_custom(
  5997. ctx0, krot, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5998. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5999. );
  6000. cb(krotated, "krotated", il);
  6001. // ggml currently only supports concatenation on dim=2
  6002. // so we need to permute qrot, qpass, concat, then permute back.
  6003. qrotated = ggml_cont(ctx0, ggml_permute(ctx0, qrotated, 2, 1, 0, 3));
  6004. cb(qrotated, "qrotated", il);
  6005. krotated = ggml_cont(ctx0, ggml_permute(ctx0, krotated, 2, 1, 0, 3));
  6006. cb(krotated, "krotated", il);
  6007. qpass = ggml_cont(ctx0, ggml_permute(ctx0, qpass, 2, 1, 0, 3));
  6008. cb(qpass, "qpass", il);
  6009. kpass = ggml_cont(ctx0, ggml_permute(ctx0, kpass, 2, 1, 0, 3));
  6010. cb(kpass, "kpass", il);
  6011. struct ggml_tensor * Qcur = ggml_concat(ctx0, qrotated, qpass);
  6012. cb(Qcur, "Qcur", il);
  6013. struct ggml_tensor * Kcur = ggml_concat(ctx0, krotated, kpass);
  6014. cb(Kcur, "Kcur", il);
  6015. struct ggml_tensor * Q = ggml_cont(ctx0, ggml_permute(ctx0, Qcur, 2, 1, 0, 3));
  6016. cb(Q, "Q", il);
  6017. Kcur = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 2, 1, 0, 3));
  6018. cb(Kcur, "Kcur", il);
  6019. struct ggml_tensor * Vcur = ggml_view_3d(
  6020. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  6021. ggml_element_size(tmpqkv_perm) * n_embd_head,
  6022. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  6023. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens * 2
  6024. );
  6025. cb(Vcur, "Vcur", il);
  6026. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6027. model.layers[il].wo, model.layers[il].bo,
  6028. Kcur, Vcur, Q, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6029. }
  6030. if (il == n_layer - 1) {
  6031. // skip computing output for unused tokens
  6032. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6033. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6034. residual = ggml_get_rows(ctx0, residual, inp_out_ids);
  6035. }
  6036. struct ggml_tensor * ffn_inp = ggml_add(ctx0, residual, cur);
  6037. cb(ffn_inp, "ffn_inp", il);
  6038. // feed-forward network
  6039. {
  6040. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6041. model.layers[il].ffn_norm,
  6042. model.layers[il].ffn_norm_b,
  6043. LLM_NORM, cb, il);
  6044. cb(cur, "ffn_norm", il);
  6045. cur = llm_build_ffn(ctx0, cur,
  6046. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6047. NULL, NULL,
  6048. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6049. NULL,
  6050. LLM_FFN_RELU_SQR, LLM_FFN_SEQ, cb, il);
  6051. cb(cur, "ffn_out", il);
  6052. }
  6053. cur = ggml_add(ctx0, cur, ffn_inp);
  6054. cb(cur, "l_out", il);
  6055. inpL = cur;
  6056. }
  6057. cur = inpL;
  6058. cur = llm_build_norm(ctx0, cur, hparams,
  6059. model.output_norm,
  6060. model.output_norm_b,
  6061. LLM_NORM, cb, -1);
  6062. cb(cur, "result_norm", -1);
  6063. cur = ggml_mul_mat(ctx0, model.output, cur);
  6064. cb(cur, "result_output", -1);
  6065. ggml_build_forward_expand(gf, cur);
  6066. return gf;
  6067. }
  6068. struct ggml_cgraph * build_refact() {
  6069. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6070. const int64_t n_embd_head = hparams.n_embd_head_v;
  6071. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6072. struct ggml_tensor * cur;
  6073. struct ggml_tensor * inpL;
  6074. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6075. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6076. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6077. // positions of the tokens in the KV cache
  6078. struct ggml_tensor * KQ_pos = build_inp_KQ_pos();
  6079. for (int il = 0; il < n_layer; ++il) {
  6080. struct ggml_tensor * inpSA = inpL;
  6081. cur = llm_build_norm(ctx0, inpL, hparams,
  6082. model.layers[il].attn_norm, NULL,
  6083. LLM_NORM_RMS, cb, il);
  6084. cb(cur, "attn_norm", il);
  6085. // self-attention
  6086. {
  6087. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6088. cb(Qcur, "Qcur", il);
  6089. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6090. cb(Kcur, "Kcur", il);
  6091. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6092. cb(Vcur, "Vcur", il);
  6093. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  6094. cb(Kcur, "Kcur", il);
  6095. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6096. cb(Qcur, "Qcur", il);
  6097. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6098. model.layers[il].wo, NULL,
  6099. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6100. }
  6101. if (il == n_layer - 1) {
  6102. // skip computing output for unused tokens
  6103. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6104. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6105. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  6106. }
  6107. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6108. cb(ffn_inp, "ffn_inp", il);
  6109. // feed-forward network
  6110. {
  6111. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6112. model.layers[il].ffn_norm, NULL,
  6113. LLM_NORM_RMS, cb, il);
  6114. cb(cur, "ffn_norm", il);
  6115. cur = llm_build_ffn(ctx0, cur,
  6116. model.layers[il].ffn_up, NULL,
  6117. model.layers[il].ffn_gate, NULL,
  6118. model.layers[il].ffn_down, NULL,
  6119. NULL,
  6120. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6121. cb(cur, "ffn_out", il);
  6122. }
  6123. cur = ggml_add(ctx0, cur, ffn_inp);
  6124. cb(cur, "l_out", il);
  6125. // input for next layer
  6126. inpL = cur;
  6127. }
  6128. cur = inpL;
  6129. cur = llm_build_norm(ctx0, cur, hparams,
  6130. model.output_norm, NULL,
  6131. LLM_NORM_RMS, cb, -1);
  6132. cb(cur, "result_norm", -1);
  6133. // lm_head
  6134. cur = ggml_mul_mat(ctx0, model.output, cur);
  6135. cb(cur, "result_output", -1);
  6136. ggml_build_forward_expand(gf, cur);
  6137. return gf;
  6138. }
  6139. struct ggml_cgraph * build_bert() {
  6140. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6141. const int64_t n_embd_head = hparams.n_embd_head_v;
  6142. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  6143. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6144. struct ggml_tensor * cur;
  6145. struct ggml_tensor * inpL;
  6146. struct ggml_tensor * inp_pos = build_inp_pos();
  6147. struct ggml_tensor * inp_mean = build_inp_mean();
  6148. struct ggml_tensor * inp_cls = build_inp_cls();
  6149. // construct input embeddings (token, type, position)
  6150. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6151. // token types are hardcoded to zero ("Sentence A")
  6152. struct ggml_tensor * type_row0 = ggml_view_1d(ctx0, model.type_embd, n_embd, 0);
  6153. inpL = ggml_add(ctx0, inpL, type_row0);
  6154. if (model.arch == LLM_ARCH_BERT) {
  6155. inpL = ggml_add(ctx0, ggml_get_rows(ctx0, model.pos_embd, inp_pos), inpL);
  6156. }
  6157. cb(inpL, "inp_embd", -1);
  6158. // embed layer norm
  6159. inpL = llm_build_norm(ctx0, inpL, hparams, model.tok_norm, model.tok_norm_b, LLM_NORM, cb, -1);
  6160. cb(inpL, "inp_norm", -1);
  6161. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6162. struct ggml_tensor * KQ_mask = build_inp_KQ_mask(false);
  6163. // iterate layers
  6164. for (int il = 0; il < n_layer; ++il) {
  6165. struct ggml_tensor * cur = inpL;
  6166. struct ggml_tensor * Qcur;
  6167. struct ggml_tensor * Kcur;
  6168. struct ggml_tensor * Vcur;
  6169. // self-attention
  6170. if (model.arch == LLM_ARCH_BERT) {
  6171. Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, cur), model.layers[il].bq);
  6172. cb(Qcur, "Qcur", il);
  6173. Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, cur), model.layers[il].bk);
  6174. cb(Kcur, "Kcur", il);
  6175. Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, cur), model.layers[il].bv);
  6176. cb(Vcur, "Vcur", il);
  6177. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6178. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  6179. } else {
  6180. // compute Q and K and RoPE them
  6181. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6182. cb(cur, "wqkv", il);
  6183. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6184. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  6185. 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)));
  6186. cb(Qcur, "Qcur", il);
  6187. cb(Kcur, "Kcur", il);
  6188. cb(Vcur, "Vcur", il);
  6189. Qcur = ggml_rope_custom(
  6190. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6191. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6192. ext_factor, attn_factor, beta_fast, beta_slow
  6193. );
  6194. cb(Qcur, "Qcur", il);
  6195. Kcur = ggml_rope_custom(
  6196. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6197. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6198. ext_factor, attn_factor, beta_fast, beta_slow
  6199. );
  6200. cb(Kcur, "Kcur", il);
  6201. }
  6202. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  6203. struct ggml_tensor * k = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 0, 2, 1, 3));
  6204. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  6205. cb(kq, "kq", il);
  6206. kq = ggml_soft_max_ext(ctx0, kq, KQ_mask, nullptr, 1.0f/sqrtf(float(n_embd_head)), hparams.f_max_alibi_bias);
  6207. cb(kq, "kq_soft_max_ext", il);
  6208. struct ggml_tensor * v = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_reshape_2d(ctx0, Vcur, n_embd_gqa, n_tokens)));
  6209. cb(v, "v", il);
  6210. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, ggml_reshape_3d(ctx0, v, n_tokens, n_embd_head, n_head_kv), kq);
  6211. cb(kqv, "kqv", il);
  6212. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  6213. cb(kqv_merged, "kqv_merged", il);
  6214. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  6215. cb(cur, "kqv_merged_cont", il);
  6216. ggml_build_forward_expand(gf, cur);
  6217. cur = ggml_mul_mat(ctx0, model.layers[il].wo, cur);
  6218. if (model.layers[il].bo) {
  6219. cb(cur, "kqv_wo", il);
  6220. }
  6221. if (model.layers[il].bo) {
  6222. cur = ggml_add(ctx0, cur, model.layers[il].bo);
  6223. }
  6224. cb(cur, "kqv_out", il);
  6225. if (il == n_layer - 1 && pooling_type == LLAMA_POOLING_TYPE_NONE) {
  6226. // skip computing output for unused tokens
  6227. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6228. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6229. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  6230. }
  6231. // re-add the layer input
  6232. cur = ggml_add(ctx0, cur, inpL);
  6233. // attention layer norm
  6234. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].attn_out_norm, model.layers[il].attn_out_norm_b, LLM_NORM, cb, il);
  6235. struct ggml_tensor * ffn_inp = cur;
  6236. cb(ffn_inp, "ffn_inp", il);
  6237. // feed-forward network
  6238. if (model.arch == LLM_ARCH_BERT) {
  6239. cur = llm_build_ffn(ctx0, cur,
  6240. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6241. NULL, NULL,
  6242. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6243. NULL,
  6244. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6245. } else {
  6246. cur = llm_build_ffn(ctx0, cur,
  6247. model.layers[il].ffn_up, NULL,
  6248. model.layers[il].ffn_gate, NULL,
  6249. model.layers[il].ffn_down, NULL,
  6250. NULL,
  6251. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6252. }
  6253. cb(cur, "ffn_out", il);
  6254. // attentions bypass the intermediate layer
  6255. cur = ggml_add(ctx0, cur, ffn_inp);
  6256. // output layer norm
  6257. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].layer_out_norm, model.layers[il].layer_out_norm_b, LLM_NORM, cb, il);
  6258. // input for next layer
  6259. inpL = cur;
  6260. }
  6261. // final output
  6262. cur = inpL;
  6263. cb(cur, "result_embd", -1);
  6264. // pooling layer
  6265. switch (pooling_type) {
  6266. case LLAMA_POOLING_TYPE_NONE:
  6267. {
  6268. // nop
  6269. } break;
  6270. case LLAMA_POOLING_TYPE_MEAN:
  6271. {
  6272. cur = ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, cur)), inp_mean);
  6273. cb(cur, "result_embd_pooled", -1);
  6274. } break;
  6275. case LLAMA_POOLING_TYPE_CLS:
  6276. {
  6277. cur = ggml_get_rows(ctx0, cur, inp_cls);
  6278. cb(cur, "result_embd_pooled", -1);
  6279. } break;
  6280. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  6281. {
  6282. GGML_ASSERT(false && "Invalid pooling type");
  6283. } break;
  6284. }
  6285. ggml_build_forward_expand(gf, cur);
  6286. return gf;
  6287. }
  6288. struct ggml_cgraph * build_bloom() {
  6289. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6290. const int64_t n_embd_head = hparams.n_embd_head_v;
  6291. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  6292. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6293. struct ggml_tensor * cur;
  6294. struct ggml_tensor * inpL;
  6295. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6296. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6297. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6298. // positions of the tokens in the KV cache
  6299. struct ggml_tensor * KQ_pos = build_inp_KQ_pos();
  6300. inpL = llm_build_norm(ctx0, inpL, hparams,
  6301. model.tok_norm,
  6302. model.tok_norm_b,
  6303. LLM_NORM, cb, -1);
  6304. cb(inpL, "inp_norm", -1);
  6305. for (int il = 0; il < n_layer; ++il) {
  6306. cur = llm_build_norm(ctx0, inpL, hparams,
  6307. model.layers[il].attn_norm,
  6308. model.layers[il].attn_norm_b,
  6309. LLM_NORM, cb, il);
  6310. cb(cur, "attn_norm", il);
  6311. // self-attention
  6312. {
  6313. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6314. cb(cur, "wqkv", il);
  6315. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6316. cb(cur, "bqkv", il);
  6317. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6318. 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)));
  6319. 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)));
  6320. cb(Qcur, "Qcur", il);
  6321. cb(Kcur, "Kcur", il);
  6322. cb(Vcur, "Vcur", il);
  6323. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6324. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6325. model.layers[il].wo, model.layers[il].bo,
  6326. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6327. }
  6328. if (il == n_layer - 1) {
  6329. // skip computing output for unused tokens
  6330. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6331. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6332. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  6333. }
  6334. // Add the input
  6335. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  6336. cb(ffn_inp, "ffn_inp", il);
  6337. // FF
  6338. {
  6339. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6340. model.layers[il].ffn_norm,
  6341. model.layers[il].ffn_norm_b,
  6342. LLM_NORM, cb, il);
  6343. cb(cur, "ffn_norm", il);
  6344. cur = llm_build_ffn(ctx0, cur,
  6345. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6346. NULL, NULL,
  6347. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6348. NULL,
  6349. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6350. cb(cur, "ffn_out", il);
  6351. }
  6352. inpL = ggml_add(ctx0, cur, ffn_inp);
  6353. cb(inpL, "l_out", il);
  6354. }
  6355. cur = llm_build_norm(ctx0, inpL, hparams,
  6356. model.output_norm,
  6357. model.output_norm_b,
  6358. LLM_NORM, cb, -1);
  6359. cb(cur, "result_norm", -1);
  6360. cur = ggml_mul_mat(ctx0, model.output, cur);
  6361. cb(cur, "result_output", -1);
  6362. ggml_build_forward_expand(gf, cur);
  6363. return gf;
  6364. }
  6365. struct ggml_cgraph * build_mpt() {
  6366. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6367. const int64_t n_embd_head = hparams.n_embd_head_v;
  6368. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  6369. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6370. struct ggml_tensor * cur;
  6371. struct ggml_tensor * inpL;
  6372. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6373. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6374. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6375. // positions of the tokens in the KV cache
  6376. struct ggml_tensor * KQ_pos = build_inp_KQ_pos();
  6377. for (int il = 0; il < n_layer; ++il) {
  6378. struct ggml_tensor * attn_norm;
  6379. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  6380. model.layers[il].attn_norm,
  6381. model.layers[il].attn_norm_b,
  6382. LLM_NORM, cb, il);
  6383. cb(attn_norm, "attn_norm", il);
  6384. // self-attention
  6385. {
  6386. cur = attn_norm;
  6387. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6388. cb(cur, "wqkv", il);
  6389. if (model.layers[il].bqkv){
  6390. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6391. cb(cur, "bqkv", il);
  6392. }
  6393. if (hparams.f_clamp_kqv > 0.0f) {
  6394. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  6395. cb(cur, "wqkv_clamped", il);
  6396. }
  6397. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6398. 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)));
  6399. 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)));
  6400. cb(Qcur, "Qcur", il);
  6401. cb(Kcur, "Kcur", il);
  6402. cb(Vcur, "Vcur", il);
  6403. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6404. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6405. model.layers[il].wo, model.layers[il].bo,
  6406. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6407. }
  6408. if (il == n_layer - 1) {
  6409. // skip computing output for unused tokens
  6410. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6411. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6412. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  6413. }
  6414. // Add the input
  6415. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  6416. cb(ffn_inp, "ffn_inp", il);
  6417. // feed forward
  6418. {
  6419. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6420. model.layers[il].ffn_norm,
  6421. model.layers[il].ffn_norm_b,
  6422. LLM_NORM, cb, il);
  6423. cb(cur, "ffn_norm", il);
  6424. cur = llm_build_ffn(ctx0, cur,
  6425. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6426. NULL, NULL,
  6427. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6428. model.layers[il].ffn_act,
  6429. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6430. cb(cur, "ffn_out", il);
  6431. }
  6432. cur = ggml_add(ctx0, cur, ffn_inp);
  6433. cb(cur, "l_out", il);
  6434. // input for next layer
  6435. inpL = cur;
  6436. }
  6437. cur = inpL;
  6438. cur = llm_build_norm(ctx0, cur, hparams,
  6439. model.output_norm,
  6440. model.output_norm_b,
  6441. LLM_NORM, cb, -1);
  6442. cb(cur, "result_norm", -1);
  6443. cur = ggml_mul_mat(ctx0, model.output, cur);
  6444. cb(cur, "result_output", -1);
  6445. ggml_build_forward_expand(gf, cur);
  6446. return gf;
  6447. }
  6448. struct ggml_cgraph * build_stablelm() {
  6449. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  6450. const int64_t n_embd_head = hparams.n_embd_head_v;
  6451. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6452. struct ggml_tensor * cur;
  6453. struct ggml_tensor * inpL;
  6454. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6455. // inp_pos - contains the positions
  6456. struct ggml_tensor * inp_pos = build_inp_pos();
  6457. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6458. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6459. for (int il = 0; il < n_layer; ++il) {
  6460. struct ggml_tensor * inpSA = inpL;
  6461. // norm
  6462. cur = llm_build_norm(ctx0, inpL, hparams,
  6463. model.layers[il].attn_norm,
  6464. model.layers[il].attn_norm_b,
  6465. LLM_NORM, cb, il);
  6466. cb(cur, "attn_norm", il);
  6467. // self-attention
  6468. {
  6469. // compute Q and K and RoPE them
  6470. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6471. cb(Qcur, "Qcur", il);
  6472. if (model.layers[il].bq) {
  6473. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6474. cb(Qcur, "Qcur", il);
  6475. }
  6476. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6477. cb(Kcur, "Kcur", il);
  6478. if (model.layers[il].bk) {
  6479. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6480. cb(Kcur, "Kcur", il);
  6481. }
  6482. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6483. cb(Vcur, "Vcur", il);
  6484. if (model.layers[il].bv) {
  6485. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6486. cb(Vcur, "Vcur", il);
  6487. }
  6488. Qcur = ggml_rope_custom(
  6489. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6490. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6491. ext_factor, attn_factor, beta_fast, beta_slow
  6492. );
  6493. cb(Qcur, "Qcur", il);
  6494. Kcur = ggml_rope_custom(
  6495. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6496. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6497. ext_factor, attn_factor, beta_fast, beta_slow
  6498. );
  6499. cb(Kcur, "Kcur", il);
  6500. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6501. model.layers[il].wo, NULL,
  6502. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6503. }
  6504. if (il == n_layer - 1) {
  6505. // skip computing output for unused tokens
  6506. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6507. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6508. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  6509. }
  6510. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6511. cb(ffn_inp, "ffn_inp", il);
  6512. // feed-forward network
  6513. {
  6514. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6515. model.layers[il].ffn_norm,
  6516. model.layers[il].ffn_norm_b,
  6517. LLM_NORM, cb, il);
  6518. cb(cur, "ffn_norm", il);
  6519. cur = llm_build_ffn(ctx0, cur,
  6520. model.layers[il].ffn_up, NULL,
  6521. model.layers[il].ffn_gate, NULL,
  6522. model.layers[il].ffn_down, NULL,
  6523. NULL,
  6524. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6525. cb(cur, "ffn_out", il);
  6526. }
  6527. cur = ggml_add(ctx0, cur, ffn_inp);
  6528. cb(cur, "l_out", il);
  6529. // input for next layer
  6530. inpL = cur;
  6531. }
  6532. cur = inpL;
  6533. cur = llm_build_norm(ctx0, cur, hparams,
  6534. model.output_norm,
  6535. model.output_norm_b,
  6536. LLM_NORM, cb, -1);
  6537. cb(cur, "result_norm", -1);
  6538. // lm_head
  6539. cur = ggml_mul_mat(ctx0, model.output, cur);
  6540. cb(cur, "result_output", -1);
  6541. ggml_build_forward_expand(gf, cur);
  6542. return gf;
  6543. }
  6544. struct ggml_cgraph * build_qwen() {
  6545. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6546. const int64_t n_embd_head = hparams.n_embd_head_v;
  6547. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6548. struct ggml_tensor * cur;
  6549. struct ggml_tensor * inpL;
  6550. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6551. // inp_pos - contains the positions
  6552. struct ggml_tensor * inp_pos = build_inp_pos();
  6553. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6554. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6555. for (int il = 0; il < n_layer; ++il) {
  6556. struct ggml_tensor * inpSA = inpL;
  6557. cur = llm_build_norm(ctx0, inpL, hparams,
  6558. model.layers[il].attn_norm, NULL,
  6559. LLM_NORM_RMS, cb, il);
  6560. cb(cur, "attn_norm", il);
  6561. // self-attention
  6562. {
  6563. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6564. cb(cur, "wqkv", il);
  6565. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6566. cb(cur, "bqkv", il);
  6567. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6568. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  6569. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 2*sizeof(float)*(n_embd)));
  6570. cb(Qcur, "Qcur", il);
  6571. cb(Kcur, "Kcur", il);
  6572. cb(Vcur, "Vcur", il);
  6573. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6574. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  6575. // using mode = 2 for neox mode
  6576. Qcur = ggml_rope_custom(
  6577. ctx0, Qcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  6578. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  6579. );
  6580. cb(Qcur, "Qcur", il);
  6581. Kcur = ggml_rope_custom(
  6582. ctx0, Kcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  6583. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  6584. );
  6585. cb(Kcur, "Kcur", il);
  6586. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6587. model.layers[il].wo, NULL,
  6588. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6589. }
  6590. if (il == n_layer - 1) {
  6591. // skip computing output for unused tokens
  6592. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6593. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6594. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  6595. }
  6596. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6597. cb(ffn_inp, "ffn_inp", il);
  6598. // feed-forward forward
  6599. {
  6600. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6601. model.layers[il].ffn_norm, NULL,
  6602. LLM_NORM_RMS, cb, il);
  6603. cb(cur, "ffn_norm", il);
  6604. cur = llm_build_ffn(ctx0, cur,
  6605. model.layers[il].ffn_up, NULL,
  6606. model.layers[il].ffn_gate, NULL,
  6607. model.layers[il].ffn_down, NULL,
  6608. NULL,
  6609. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6610. cb(cur, "ffn_out", il);
  6611. }
  6612. cur = ggml_add(ctx0, cur, ffn_inp);
  6613. cb(cur, "l_out", il);
  6614. // input for next layer
  6615. inpL = cur;
  6616. }
  6617. cur = inpL;
  6618. cur = llm_build_norm(ctx0, cur, hparams,
  6619. model.output_norm, NULL,
  6620. LLM_NORM_RMS, cb, -1);
  6621. cb(cur, "result_norm", -1);
  6622. // lm_head
  6623. cur = ggml_mul_mat(ctx0, model.output, cur);
  6624. cb(cur, "result_output", -1);
  6625. ggml_build_forward_expand(gf, cur);
  6626. return gf;
  6627. }
  6628. struct ggml_cgraph * build_qwen2() {
  6629. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6630. const int64_t n_embd_head = hparams.n_embd_head_v;
  6631. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6632. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6633. struct ggml_tensor * cur;
  6634. struct ggml_tensor * inpL;
  6635. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6636. // inp_pos - contains the positions
  6637. struct ggml_tensor * inp_pos = build_inp_pos();
  6638. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6639. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6640. for (int il = 0; il < n_layer; ++il) {
  6641. struct ggml_tensor * inpSA = inpL;
  6642. // norm
  6643. cur = llm_build_norm(ctx0, inpL, hparams,
  6644. model.layers[il].attn_norm, NULL,
  6645. LLM_NORM_RMS, cb, il);
  6646. cb(cur, "attn_norm", il);
  6647. // self-attention
  6648. {
  6649. // compute Q and K and RoPE them
  6650. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6651. cb(Qcur, "Qcur", il);
  6652. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6653. cb(Qcur, "Qcur", il);
  6654. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6655. cb(Kcur, "Kcur", il);
  6656. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6657. cb(Kcur, "Kcur", il);
  6658. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6659. cb(Vcur, "Vcur", il);
  6660. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6661. cb(Vcur, "Vcur", il);
  6662. // these nodes are added to the graph together so that they are not reordered
  6663. // by doing so, the number of splits in the graph is reduced
  6664. ggml_build_forward_expand(gf, Qcur);
  6665. ggml_build_forward_expand(gf, Kcur);
  6666. ggml_build_forward_expand(gf, Vcur);
  6667. Qcur = ggml_rope_custom(
  6668. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6669. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6670. ext_factor, attn_factor, beta_fast, beta_slow
  6671. );
  6672. cb(Qcur, "Qcur", il);
  6673. Kcur = ggml_rope_custom(
  6674. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6675. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6676. ext_factor, attn_factor, beta_fast, beta_slow
  6677. );
  6678. cb(Kcur, "Kcur", il);
  6679. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6680. model.layers[il].wo, model.layers[il].bo,
  6681. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6682. }
  6683. if (il == n_layer - 1) {
  6684. // skip computing output for unused tokens
  6685. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6686. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6687. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  6688. }
  6689. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6690. cb(ffn_inp, "ffn_inp", il);
  6691. // feed-forward network
  6692. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6693. model.layers[il].ffn_norm, NULL,
  6694. LLM_NORM_RMS, cb, il);
  6695. cb(cur, "ffn_norm", il);
  6696. cur = llm_build_ffn(ctx0, cur,
  6697. model.layers[il].ffn_up, NULL,
  6698. model.layers[il].ffn_gate, NULL,
  6699. model.layers[il].ffn_down, NULL,
  6700. NULL,
  6701. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6702. cb(cur, "ffn_out", il);
  6703. cur = ggml_add(ctx0, cur, ffn_inp);
  6704. cb(cur, "l_out", il);
  6705. // input for next layer
  6706. inpL = cur;
  6707. }
  6708. cur = inpL;
  6709. cur = llm_build_norm(ctx0, cur, hparams,
  6710. model.output_norm, NULL,
  6711. LLM_NORM_RMS, cb, -1);
  6712. cb(cur, "result_norm", -1);
  6713. // lm_head
  6714. cur = ggml_mul_mat(ctx0, model.output, cur);
  6715. cb(cur, "result_output", -1);
  6716. ggml_build_forward_expand(gf, cur);
  6717. return gf;
  6718. }
  6719. struct ggml_cgraph * build_phi2() {
  6720. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6721. const int64_t n_embd_head = hparams.n_embd_head_v;
  6722. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  6723. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6724. struct ggml_tensor * cur;
  6725. struct ggml_tensor * attn_norm_output;
  6726. struct ggml_tensor * ffn_output;
  6727. struct ggml_tensor * inpL;
  6728. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6729. // inp_pos - contains the positions
  6730. struct ggml_tensor * inp_pos = build_inp_pos();
  6731. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6732. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6733. for (int il = 0; il < n_layer; ++il) {
  6734. attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  6735. model.layers[il].attn_norm,
  6736. model.layers[il].attn_norm_b,
  6737. LLM_NORM, cb, il);
  6738. cb(attn_norm_output, "attn_norm", il);
  6739. // self-attention
  6740. {
  6741. struct ggml_tensor * Qcur = nullptr;
  6742. struct ggml_tensor * Kcur = nullptr;
  6743. struct ggml_tensor * Vcur = nullptr;
  6744. if (model.layers[il].wqkv) {
  6745. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, attn_norm_output);
  6746. cb(cur, "wqkv", il);
  6747. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6748. cb(cur, "bqkv", il);
  6749. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6750. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  6751. 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)));
  6752. } else {
  6753. Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  6754. Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  6755. Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  6756. }
  6757. cb(Qcur, "Qcur", il);
  6758. cb(Kcur, "Kcur", il);
  6759. cb(Vcur, "Vcur", il);
  6760. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6761. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  6762. Qcur = ggml_rope_custom(
  6763. ctx0, Qcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  6764. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  6765. );
  6766. cb(Qcur, "Qcur", il);
  6767. // with phi2, we scale the Q to avoid precision issues
  6768. // ref: https://github.com/ml-explore/mlx-examples/blob/08e862336ade809bc37d1035f94b359e7d1a5152/phi2/phi2.py#L64-L66
  6769. Qcur = ggml_scale(ctx0, Qcur, 1.0f/sqrtf(float(n_embd_head)));
  6770. cb(Qcur, "Qcur", il);
  6771. Kcur = ggml_rope_custom(
  6772. ctx0, Kcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  6773. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  6774. );
  6775. cb(Kcur, "Kcur", il);
  6776. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6777. model.layers[il].wo, model.layers[il].bo,
  6778. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  6779. }
  6780. if (il == n_layer - 1) {
  6781. // skip computing output for unused tokens
  6782. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6783. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6784. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  6785. attn_norm_output = ggml_get_rows(ctx0, attn_norm_output, inp_out_ids);
  6786. }
  6787. // FF
  6788. {
  6789. ffn_output = llm_build_ffn(ctx0, attn_norm_output,
  6790. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6791. NULL, NULL,
  6792. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6793. NULL,
  6794. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6795. cb(ffn_output, "ffn_out", il);
  6796. }
  6797. cur = ggml_add(ctx0, cur, ffn_output);
  6798. cb(cur, "l_out", il);
  6799. cur = ggml_add(ctx0, cur, inpL);
  6800. cb(cur, "l_out", il);
  6801. inpL = cur;
  6802. }
  6803. cur = llm_build_norm(ctx0, inpL, hparams,
  6804. model.output_norm,
  6805. model.output_norm_b,
  6806. LLM_NORM, cb, -1);
  6807. cb(cur, "result_norm", -1);
  6808. cur = ggml_mul_mat(ctx0, model.output, cur);
  6809. cb(cur, "result_output_no_bias", -1);
  6810. cur = ggml_add(ctx0, cur, model.output_b);
  6811. cb(cur, "result_output", -1);
  6812. ggml_build_forward_expand(gf, cur);
  6813. return gf;
  6814. }
  6815. struct ggml_cgraph * build_plamo() {
  6816. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  6817. const int64_t n_embd_head = hparams.n_embd_head_v;
  6818. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6819. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6820. struct ggml_tensor * cur;
  6821. struct ggml_tensor * inpL;
  6822. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6823. // inp_pos - contains the positions
  6824. struct ggml_tensor * inp_pos = build_inp_pos();
  6825. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6826. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6827. for (int il = 0; il < n_layer; ++il) {
  6828. // norm
  6829. cur = llm_build_norm(ctx0, inpL, hparams,
  6830. model.layers[il].attn_norm, NULL,
  6831. LLM_NORM_RMS, cb, il);
  6832. cb(cur, "attn_norm", il);
  6833. struct ggml_tensor * attention_norm = cur;
  6834. // self-attention
  6835. {
  6836. // compute Q and K and RoPE them
  6837. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6838. cb(Qcur, "Qcur", il);
  6839. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6840. cb(Kcur, "Kcur", il);
  6841. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6842. cb(Vcur, "Vcur", il);
  6843. Qcur = ggml_rope_custom(
  6844. ctx0, ggml_reshape_3d(ctx0, Qcur, n_rot, n_head, n_tokens), inp_pos,
  6845. n_embd_head, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6846. ext_factor, attn_factor, beta_fast, beta_slow);
  6847. cb(Qcur, "Qcur", il);
  6848. Kcur = ggml_rope_custom(
  6849. ctx0, ggml_reshape_3d(ctx0, Kcur, n_rot, n_head_kv, n_tokens), inp_pos,
  6850. n_embd_head, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6851. ext_factor, attn_factor, beta_fast, beta_slow);
  6852. cb(Kcur, "Kcur", il);
  6853. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6854. model.layers[il].wo, NULL,
  6855. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6856. }
  6857. struct ggml_tensor * sa_out = cur;
  6858. cur = attention_norm;
  6859. if (il == n_layer - 1) {
  6860. // skip computing output for unused tokens
  6861. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6862. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6863. sa_out = ggml_get_rows(ctx0, sa_out, inp_out_ids);
  6864. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  6865. }
  6866. // feed-forward network
  6867. {
  6868. cur = llm_build_ffn(ctx0, cur,
  6869. model.layers[il].ffn_up, NULL,
  6870. model.layers[il].ffn_gate, NULL,
  6871. model.layers[il].ffn_down, NULL,
  6872. NULL,
  6873. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6874. cb(cur, "ffn_out", il);
  6875. }
  6876. cur = ggml_add(ctx0, cur, sa_out);
  6877. cb(cur, "l_out", il);
  6878. cur = ggml_add(ctx0, cur, inpL);
  6879. cb(cur, "l_out", il);
  6880. // input for next layer
  6881. inpL = cur;
  6882. }
  6883. cur = inpL;
  6884. cur = llm_build_norm(ctx0, cur, hparams,
  6885. model.output_norm, NULL,
  6886. LLM_NORM_RMS, cb, -1);
  6887. cb(cur, "result_norm", -1);
  6888. // lm_head
  6889. cur = ggml_mul_mat(ctx0, model.output, cur);
  6890. cb(cur, "result_output", -1);
  6891. ggml_build_forward_expand(gf, cur);
  6892. return gf;
  6893. }
  6894. struct ggml_cgraph * build_gpt2() {
  6895. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6896. const int64_t n_embd_head = hparams.n_embd_head_v;
  6897. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  6898. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6899. struct ggml_tensor * cur;
  6900. struct ggml_tensor * pos;
  6901. struct ggml_tensor * inpL;
  6902. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6903. // inp_pos - contains the positions
  6904. struct ggml_tensor * inp_pos = build_inp_pos();
  6905. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6906. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6907. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  6908. cb(pos, "pos_embd", -1);
  6909. inpL = ggml_add(ctx0, inpL, pos);
  6910. cb(inpL, "inpL", -1);
  6911. for (int il = 0; il < n_layer; ++il) {
  6912. cur = llm_build_norm(ctx0, inpL, hparams,
  6913. model.layers[il].attn_norm,
  6914. model.layers[il].attn_norm_b,
  6915. LLM_NORM, cb, il);
  6916. cb(cur, "attn_norm", il);
  6917. // self-attention
  6918. {
  6919. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6920. cb(cur, "wqkv", il);
  6921. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6922. cb(cur, "bqkv", il);
  6923. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6924. 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)));
  6925. 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)));
  6926. cb(Qcur, "Qcur", il);
  6927. cb(Kcur, "Kcur", il);
  6928. cb(Vcur, "Vcur", il);
  6929. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6930. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6931. model.layers[il].wo, model.layers[il].bo,
  6932. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6933. }
  6934. if (il == n_layer - 1) {
  6935. // skip computing output for unused tokens
  6936. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6937. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6938. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  6939. }
  6940. // add the input
  6941. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  6942. cb(ffn_inp, "ffn_inp", il);
  6943. // FF
  6944. {
  6945. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6946. model.layers[il].ffn_norm,
  6947. model.layers[il].ffn_norm_b,
  6948. LLM_NORM, cb, il);
  6949. cb(cur, "ffn_norm", il);
  6950. cur = llm_build_ffn(ctx0, cur,
  6951. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6952. NULL, NULL,
  6953. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6954. NULL,
  6955. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6956. cb(cur, "ffn_out", il);
  6957. }
  6958. inpL = ggml_add(ctx0, cur, ffn_inp);
  6959. cb(inpL, "l_out", il);
  6960. }
  6961. cur = llm_build_norm(ctx0, inpL, hparams,
  6962. model.output_norm,
  6963. model.output_norm_b,
  6964. LLM_NORM, cb, -1);
  6965. cb(cur, "result_norm", -1);
  6966. cur = ggml_mul_mat(ctx0, model.output, cur);
  6967. cb(cur, "result_output", -1);
  6968. ggml_build_forward_expand(gf, cur);
  6969. return gf;
  6970. }
  6971. struct ggml_cgraph * build_codeshell() {
  6972. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6973. const int64_t n_embd_head = hparams.n_embd_head_v;
  6974. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  6975. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6976. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6977. struct ggml_tensor * cur;
  6978. struct ggml_tensor * inpL;
  6979. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6980. // inp_pos - contains the positions
  6981. struct ggml_tensor * inp_pos = build_inp_pos();
  6982. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6983. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6984. for (int il = 0; il < n_layer; ++il) {
  6985. cur = llm_build_norm(ctx0, inpL, hparams,
  6986. model.layers[il].attn_norm,
  6987. model.layers[il].attn_norm_b,
  6988. LLM_NORM, cb, il);
  6989. cb(cur, "attn_norm", il);
  6990. // self-attention
  6991. {
  6992. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6993. cb(cur, "wqkv", il);
  6994. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6995. cb(cur, "bqkv", il);
  6996. struct ggml_tensor * tmpq = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6997. 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)));
  6998. 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)));
  6999. cb(tmpq, "tmpq", il);
  7000. cb(tmpk, "tmpk", il);
  7001. cb(Vcur, "Vcur", il);
  7002. struct ggml_tensor * Qcur = ggml_rope_custom(
  7003. ctx0, ggml_reshape_3d(ctx0, tmpq, n_embd_head, n_head, n_tokens), inp_pos,
  7004. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7005. ext_factor, attn_factor, beta_fast, beta_slow
  7006. );
  7007. cb(Qcur, "Qcur", il);
  7008. struct ggml_tensor * Kcur = ggml_rope_custom(
  7009. ctx0, ggml_reshape_3d(ctx0, tmpk, n_embd_head, n_head_kv, n_tokens), inp_pos,
  7010. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7011. ext_factor, attn_factor, beta_fast, beta_slow
  7012. );
  7013. cb(Kcur, "Kcur", il);
  7014. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  7015. model.layers[il].wo, model.layers[il].bo,
  7016. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7017. }
  7018. if (il == n_layer - 1) {
  7019. // skip computing output for unused tokens
  7020. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7021. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7022. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  7023. }
  7024. // add the input
  7025. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  7026. cb(ffn_inp, "ffn_inp", il);
  7027. // FF
  7028. {
  7029. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7030. model.layers[il].ffn_norm,
  7031. model.layers[il].ffn_norm_b,
  7032. LLM_NORM, cb, il);
  7033. cb(cur, "ffn_norm", il);
  7034. cur = llm_build_ffn(ctx0, cur,
  7035. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  7036. NULL, NULL,
  7037. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  7038. NULL,
  7039. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  7040. cb(cur, "ffn_out", il);
  7041. }
  7042. inpL = ggml_add(ctx0, cur, ffn_inp);
  7043. cb(inpL, "l_out", il);
  7044. }
  7045. cur = llm_build_norm(ctx0, inpL, hparams,
  7046. model.output_norm,
  7047. model.output_norm_b,
  7048. LLM_NORM, cb, -1);
  7049. cb(cur, "result_norm", -1);
  7050. cur = ggml_mul_mat(ctx0, model.output, cur);
  7051. cb(cur, "result_output", -1);
  7052. ggml_build_forward_expand(gf, cur);
  7053. return gf;
  7054. }
  7055. struct ggml_cgraph * build_orion() {
  7056. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7057. const int64_t n_embd_head = hparams.n_embd_head_v;
  7058. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7059. GGML_ASSERT(n_embd_head == hparams.n_rot);
  7060. struct ggml_tensor * cur;
  7061. struct ggml_tensor * inpL;
  7062. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7063. // inp_pos - contains the positions
  7064. struct ggml_tensor * inp_pos = build_inp_pos();
  7065. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7066. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7067. for (int il = 0; il < n_layer; ++il) {
  7068. struct ggml_tensor * inpSA = inpL;
  7069. // norm
  7070. cur = llm_build_norm(ctx0, inpL, hparams,
  7071. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  7072. LLM_NORM, cb, il);
  7073. cb(cur, "attn_norm", il);
  7074. // self-attention
  7075. {
  7076. // compute Q and K and RoPE them
  7077. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  7078. cb(Qcur, "Qcur", il);
  7079. // if (model.layers[il].bq) {
  7080. // Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  7081. // cb(Qcur, "Qcur", il);
  7082. // }
  7083. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  7084. cb(Kcur, "Kcur", il);
  7085. // if (model.layers[il].bk) {
  7086. // Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  7087. // cb(Kcur, "Kcur", il);
  7088. // }
  7089. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  7090. cb(Vcur, "Vcur", il);
  7091. // if (model.layers[il].bv) {
  7092. // Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  7093. // cb(Vcur, "Vcur", il);
  7094. // }
  7095. Qcur = ggml_rope_custom(
  7096. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  7097. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7098. ext_factor, attn_factor, beta_fast, beta_slow
  7099. );
  7100. cb(Qcur, "Qcur", il);
  7101. Kcur = ggml_rope_custom(
  7102. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  7103. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7104. ext_factor, attn_factor, beta_fast, beta_slow
  7105. );
  7106. cb(Kcur, "Kcur", il);
  7107. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  7108. model.layers[il].wo, NULL,
  7109. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7110. }
  7111. if (il == n_layer - 1) {
  7112. // skip computing output for unused tokens
  7113. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7114. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7115. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  7116. }
  7117. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  7118. cb(ffn_inp, "ffn_inp", il);
  7119. // feed-forward network
  7120. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7121. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  7122. LLM_NORM, cb, il);
  7123. cb(cur, "ffn_norm", il);
  7124. cur = llm_build_ffn(ctx0, cur,
  7125. model.layers[il].ffn_up, NULL,
  7126. model.layers[il].ffn_gate, NULL,
  7127. model.layers[il].ffn_down, NULL,
  7128. NULL,
  7129. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  7130. cb(cur, "ffn_out", il);
  7131. cur = ggml_add(ctx0, cur, ffn_inp);
  7132. cb(cur, "l_out", il);
  7133. // input for next layer
  7134. inpL = cur;
  7135. }
  7136. cur = inpL;
  7137. cur = llm_build_norm(ctx0, cur, hparams,
  7138. model.output_norm, model.output_norm_b,
  7139. LLM_NORM, cb, -1);
  7140. cb(cur, "result_norm", -1);
  7141. // lm_head
  7142. cur = ggml_mul_mat(ctx0, model.output, cur);
  7143. cb(cur, "result_output", -1);
  7144. ggml_build_forward_expand(gf, cur);
  7145. return gf;
  7146. }
  7147. struct ggml_cgraph * build_internlm2() {
  7148. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7149. const int64_t n_embd_head = hparams.n_embd_head_v;
  7150. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7151. GGML_ASSERT(n_embd_head == hparams.n_rot);
  7152. struct ggml_tensor * cur;
  7153. struct ggml_tensor * inpL;
  7154. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7155. // inp_pos - contains the positions
  7156. struct ggml_tensor * inp_pos = build_inp_pos();
  7157. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7158. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7159. for (int il = 0; il < n_layer; ++il) {
  7160. struct ggml_tensor * inpSA = inpL;
  7161. // norm
  7162. cur = llm_build_norm(ctx0, inpL, hparams,
  7163. model.layers[il].attn_norm, NULL,
  7164. LLM_NORM_RMS, cb, il);
  7165. cb(cur, "attn_norm", il);
  7166. // self-attention
  7167. {
  7168. // compute Q and K and RoPE them
  7169. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  7170. cb(Qcur, "Qcur", il);
  7171. if (model.layers[il].bq) {
  7172. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  7173. cb(Qcur, "Qcur", il);
  7174. }
  7175. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  7176. cb(Kcur, "Kcur", il);
  7177. if (model.layers[il].bk) {
  7178. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  7179. cb(Kcur, "Kcur", il);
  7180. }
  7181. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  7182. cb(Vcur, "Vcur", il);
  7183. if (model.layers[il].bv) {
  7184. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  7185. cb(Vcur, "Vcur", il);
  7186. }
  7187. Qcur = ggml_rope_custom(
  7188. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  7189. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7190. ext_factor, attn_factor, beta_fast, beta_slow
  7191. );
  7192. cb(Qcur, "Qcur", il);
  7193. Kcur = ggml_rope_custom(
  7194. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  7195. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7196. ext_factor, attn_factor, beta_fast, beta_slow
  7197. );
  7198. cb(Kcur, "Kcur", il);
  7199. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  7200. model.layers[il].wo, model.layers[il].bo,
  7201. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7202. }
  7203. if (il == n_layer - 1) {
  7204. // skip computing output for unused tokens
  7205. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7206. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7207. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  7208. }
  7209. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  7210. cb(ffn_inp, "ffn_inp", il);
  7211. // feed-forward network
  7212. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7213. model.layers[il].ffn_norm, NULL,
  7214. LLM_NORM_RMS, cb, il);
  7215. cb(cur, "ffn_norm", il);
  7216. cur = llm_build_ffn(ctx0, cur,
  7217. model.layers[il].ffn_up, NULL,
  7218. model.layers[il].ffn_gate, NULL,
  7219. model.layers[il].ffn_down, NULL,
  7220. NULL,
  7221. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  7222. cb(cur, "ffn_out", il);
  7223. cur = ggml_add(ctx0, cur, ffn_inp);
  7224. cb(cur, "l_out", il);
  7225. // input for next layer
  7226. inpL = cur;
  7227. }
  7228. cur = inpL;
  7229. cur = llm_build_norm(ctx0, cur, hparams,
  7230. model.output_norm, NULL,
  7231. LLM_NORM_RMS, cb, -1);
  7232. cb(cur, "result_norm", -1);
  7233. // lm_head
  7234. cur = ggml_mul_mat(ctx0, model.output, cur);
  7235. cb(cur, "result_output", -1);
  7236. ggml_build_forward_expand(gf, cur);
  7237. return gf;
  7238. }
  7239. // ref: https://arxiv.org/abs/2203.03466
  7240. // https://github.com/ggerganov/llama.cpp/issues/5276#issuecomment-1925774738
  7241. // based on the original build_llama() function
  7242. struct ggml_cgraph * build_minicpm() {
  7243. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7244. const int64_t n_embd_head = hparams.n_embd_head_v;
  7245. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7246. GGML_ASSERT(n_embd_head == hparams.n_rot);
  7247. const int64_t n_embd = hparams.n_embd;
  7248. //TODO: if the model varies, these parameters need to be read from the model
  7249. const int64_t n_embd_base = 256;
  7250. const float scale_embd = 12.0f;
  7251. const float scale_depth = 1.4f;
  7252. struct ggml_tensor * cur;
  7253. struct ggml_tensor * inpL;
  7254. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7255. // scale the input embeddings
  7256. inpL = ggml_scale(ctx0, inpL, scale_embd);
  7257. cb(inpL, "inp_scaled", -1);
  7258. // inp_pos - contains the positions
  7259. struct ggml_tensor * inp_pos = build_inp_pos();
  7260. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7261. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7262. for (int il = 0; il < n_layer; ++il) {
  7263. struct ggml_tensor * inpSA = inpL;
  7264. // norm
  7265. cur = llm_build_norm(ctx0, inpL, hparams,
  7266. model.layers[il].attn_norm, NULL,
  7267. LLM_NORM_RMS, cb, il);
  7268. cb(cur, "attn_norm", il);
  7269. // self-attention
  7270. {
  7271. // compute Q and K and RoPE them
  7272. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  7273. cb(Qcur, "Qcur", il);
  7274. if (model.layers[il].bq) {
  7275. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  7276. cb(Qcur, "Qcur", il);
  7277. }
  7278. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  7279. cb(Kcur, "Kcur", il);
  7280. if (model.layers[il].bk) {
  7281. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  7282. cb(Kcur, "Kcur", il);
  7283. }
  7284. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  7285. cb(Vcur, "Vcur", il);
  7286. if (model.layers[il].bv) {
  7287. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  7288. cb(Vcur, "Vcur", il);
  7289. }
  7290. Qcur = ggml_rope_custom(
  7291. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  7292. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7293. ext_factor, attn_factor, beta_fast, beta_slow
  7294. );
  7295. cb(Qcur, "Qcur", il);
  7296. Kcur = ggml_rope_custom(
  7297. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  7298. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7299. ext_factor, attn_factor, beta_fast, beta_slow
  7300. );
  7301. cb(Kcur, "Kcur", il);
  7302. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  7303. model.layers[il].wo, model.layers[il].bo,
  7304. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7305. }
  7306. if (il == n_layer - 1) {
  7307. // skip computing output for unused tokens
  7308. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7309. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7310. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  7311. }
  7312. // scale_res - scale the hidden states for residual connection
  7313. const float scale_res = scale_depth/sqrtf(float(n_layer));
  7314. cur = ggml_scale(ctx0, cur, scale_res);
  7315. cb(cur, "hidden_scaled", -1);
  7316. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  7317. cb(ffn_inp, "ffn_inp", il);
  7318. // feed-forward network
  7319. {
  7320. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7321. model.layers[il].ffn_norm, NULL,
  7322. LLM_NORM_RMS, cb, il);
  7323. cb(cur, "ffn_norm", il);
  7324. cur = llm_build_ffn(ctx0, cur,
  7325. model.layers[il].ffn_up, NULL,
  7326. model.layers[il].ffn_gate, NULL,
  7327. model.layers[il].ffn_down, NULL,
  7328. NULL,
  7329. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  7330. cb(cur, "ffn_out", il);
  7331. }
  7332. // scale the hidden states for residual connection
  7333. cur = ggml_scale(ctx0, cur, scale_res);
  7334. cb(cur, "hidden_scaled_ffn", -1);
  7335. cur = ggml_add(ctx0, cur, ffn_inp);
  7336. cb(cur, "l_out", il);
  7337. // input for next layer
  7338. inpL = cur;
  7339. }
  7340. cur = inpL;
  7341. cur = llm_build_norm(ctx0, cur, hparams,
  7342. model.output_norm, NULL,
  7343. LLM_NORM_RMS, cb, -1);
  7344. cb(cur, "result_norm", -1);
  7345. // lm_head scaling
  7346. const float scale_lmhead = float(n_embd_base)/float(n_embd);
  7347. cur = ggml_scale(ctx0, cur, scale_lmhead);
  7348. cb(cur, "lmhead_scaling", -1);
  7349. // lm_head
  7350. cur = ggml_mul_mat(ctx0, model.tok_embd, cur);
  7351. cb(cur, "result_output", -1);
  7352. ggml_build_forward_expand(gf, cur);
  7353. return gf;
  7354. }
  7355. struct ggml_cgraph * build_gemma() {
  7356. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7357. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  7358. struct ggml_tensor * cur;
  7359. struct ggml_tensor * inpL;
  7360. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7361. inpL = ggml_scale(ctx0, inpL, sqrtf(n_embd));
  7362. cb(inpL, "inp_scaled", -1);
  7363. // inp_pos - contains the positions
  7364. struct ggml_tensor * inp_pos = build_inp_pos();
  7365. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7366. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7367. for (int il = 0; il < n_layer; ++il) {
  7368. // norm
  7369. cur = llm_build_norm(ctx0, inpL, hparams,
  7370. model.layers[il].attn_norm, NULL,
  7371. LLM_NORM_RMS, 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. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  7379. cb(Kcur, "Kcur", il);
  7380. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  7381. cb(Vcur, "Vcur", il);
  7382. Qcur = ggml_rope_custom(
  7383. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head_k, n_head, n_tokens), inp_pos,
  7384. n_embd_head_k, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7385. ext_factor, attn_factor, beta_fast, beta_slow);
  7386. cb(Qcur, "Qcur", il);
  7387. Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head_k)));
  7388. cb(Qcur, "Qcur_scaled", il);
  7389. Kcur = ggml_rope_custom(
  7390. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head_k, n_head_kv, n_tokens), inp_pos,
  7391. n_embd_head_k, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7392. ext_factor, attn_factor, beta_fast, beta_slow);
  7393. cb(Kcur, "Kcur", il);
  7394. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  7395. model.layers[il].wo, NULL,
  7396. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  7397. }
  7398. if (il == n_layer - 1) {
  7399. // skip computing output for unused tokens
  7400. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7401. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7402. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  7403. }
  7404. struct ggml_tensor * sa_out = ggml_add(ctx0, cur, inpL);
  7405. cb(sa_out, "sa_out", il);
  7406. cur = llm_build_norm(ctx0, sa_out, hparams,
  7407. model.layers[il].ffn_norm, NULL,
  7408. LLM_NORM_RMS, cb, il);
  7409. cb(cur, "ffn_norm", il);
  7410. // feed-forward network
  7411. {
  7412. cur = llm_build_ffn(ctx0, cur,
  7413. model.layers[il].ffn_up, NULL,
  7414. model.layers[il].ffn_gate, NULL,
  7415. model.layers[il].ffn_down, NULL,
  7416. NULL,
  7417. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  7418. cb(cur, "ffn_out", il);
  7419. }
  7420. cur = ggml_add(ctx0, cur, sa_out);
  7421. cb(cur, "l_out", il);
  7422. // input for next layer
  7423. inpL = cur;
  7424. }
  7425. cur = inpL;
  7426. cur = llm_build_norm(ctx0, cur, hparams,
  7427. model.output_norm, NULL,
  7428. LLM_NORM_RMS, cb, -1);
  7429. cb(cur, "result_norm", -1);
  7430. // lm_head
  7431. cur = ggml_mul_mat(ctx0, model.output, cur);
  7432. cb(cur, "result_output", -1);
  7433. ggml_build_forward_expand(gf, cur);
  7434. return gf;
  7435. }
  7436. struct ggml_cgraph * build_starcoder2() {
  7437. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7438. const int64_t n_embd_head = hparams.n_embd_head_v;
  7439. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7440. GGML_ASSERT(n_embd_head == hparams.n_rot);
  7441. struct ggml_tensor * cur;
  7442. struct ggml_tensor * inpL;
  7443. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7444. // inp_pos - contains the positions
  7445. struct ggml_tensor * inp_pos = build_inp_pos();
  7446. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7447. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7448. for (int il = 0; il < n_layer; ++il) {
  7449. struct ggml_tensor * inpSA = inpL;
  7450. // norm
  7451. cur = llm_build_norm(ctx0, inpL, hparams,
  7452. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  7453. LLM_NORM, cb, il);
  7454. cb(cur, "attn_norm", il);
  7455. // self-attention
  7456. {
  7457. // compute Q and K and RoPE them
  7458. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  7459. cb(Qcur, "Qcur", il);
  7460. if (model.layers[il].bq) {
  7461. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  7462. cb(Qcur, "Qcur", il);
  7463. }
  7464. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  7465. cb(Kcur, "Kcur", il);
  7466. if (model.layers[il].bk) {
  7467. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  7468. cb(Kcur, "Kcur", il);
  7469. }
  7470. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  7471. cb(Vcur, "Vcur", il);
  7472. if (model.layers[il].bv) {
  7473. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  7474. cb(Vcur, "Vcur", il);
  7475. }
  7476. Qcur = ggml_rope_custom(
  7477. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  7478. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7479. ext_factor, attn_factor, beta_fast, beta_slow
  7480. );
  7481. cb(Qcur, "Qcur", il);
  7482. Kcur = ggml_rope_custom(
  7483. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  7484. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7485. ext_factor, attn_factor, beta_fast, beta_slow
  7486. );
  7487. cb(Kcur, "Kcur", il);
  7488. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  7489. model.layers[il].wo, model.layers[il].bo,
  7490. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7491. }
  7492. if (il == n_layer - 1) {
  7493. // skip computing output for unused tokens
  7494. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7495. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7496. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  7497. }
  7498. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  7499. cb(ffn_inp, "ffn_inp", il);
  7500. // feed-forward network
  7501. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7502. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  7503. LLM_NORM, cb, il);
  7504. cb(cur, "ffn_norm", il);
  7505. cur = llm_build_ffn(ctx0, cur,
  7506. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  7507. NULL, NULL,
  7508. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  7509. NULL,
  7510. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  7511. cb(cur, "ffn_out", il);
  7512. cur = ggml_add(ctx0, cur, ffn_inp);
  7513. cb(cur, "l_out", il);
  7514. // input for next layer
  7515. inpL = cur;
  7516. }
  7517. cur = inpL;
  7518. cur = llm_build_norm(ctx0, cur, hparams,
  7519. model.output_norm, model.output_norm_b,
  7520. LLM_NORM, cb, -1);
  7521. cb(cur, "result_norm", -1);
  7522. // lm_head
  7523. cur = ggml_mul_mat(ctx0, model.output, cur);
  7524. cb(cur, "result_output", -1);
  7525. ggml_build_forward_expand(gf, cur);
  7526. return gf;
  7527. }
  7528. struct ggml_cgraph * build_mamba() {
  7529. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7530. const int64_t d_model = n_embd;
  7531. const int64_t d_conv = hparams.ssm_d_conv;
  7532. const int64_t d_inner = hparams.ssm_d_inner;
  7533. GGML_ASSERT(2 * d_model == d_inner);
  7534. const int64_t d_state = hparams.ssm_d_state;
  7535. const int64_t dt_rank = hparams.ssm_dt_rank;
  7536. struct ggml_tensor * cur;
  7537. struct ggml_tensor * inpL;
  7538. // {n_embd, n_tokens}
  7539. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7540. struct ggml_tensor * state_mask = build_inp_s_mask();
  7541. struct ggml_tensor * state_seq = build_inp_s_seq();
  7542. for (int il = 0; il < n_layer; ++il) {
  7543. // (ab)using the KV cache to store the states
  7544. struct ggml_tensor * conv_states = ggml_reshape_2d(ctx0, kv_self.k_l[il], hparams.n_embd_k_s(), kv_self.size);
  7545. struct ggml_tensor * ssm_states = ggml_reshape_2d(ctx0, kv_self.v_l[il], hparams.n_embd_v_s(), kv_self.size);
  7546. // clear states of sequences which are starting at the beginning of this batch
  7547. {
  7548. conv_states = ggml_mul(ctx0,
  7549. ggml_view_2d(ctx0, conv_states, conv_states->ne[0], n_kv, conv_states->nb[1], kv_head*conv_states->nb[1]),
  7550. state_mask);
  7551. ssm_states = ggml_mul(ctx0,
  7552. ggml_view_2d(ctx0, ssm_states, ssm_states->ne[0], n_kv, ssm_states->nb[1], kv_head*ssm_states->nb[1]),
  7553. state_mask);
  7554. }
  7555. conv_states = ggml_reshape_3d(ctx0, conv_states, d_conv - 1, d_inner, n_kv);
  7556. ssm_states = ggml_reshape_3d(ctx0, ssm_states, d_state, d_inner, n_kv);
  7557. // norm
  7558. cur = llm_build_norm(ctx0, inpL, hparams,
  7559. model.layers[il].attn_norm, NULL,
  7560. LLM_NORM_RMS, cb, il);
  7561. cb(cur, "attn_norm", il);
  7562. // {n_embd, 2*d_inner} * {n_embd, n_tokens} => {2*d_inner, n_tokens}
  7563. struct ggml_tensor * xz = ggml_mul_mat(ctx0, model.layers[il].ssm_in, cur);
  7564. // split the above in two
  7565. // => {d_inner, n_tokens}
  7566. struct ggml_tensor * x = ggml_view_2d(ctx0, xz, d_inner, xz->ne[1], xz->nb[1], 0);
  7567. struct ggml_tensor * z = ggml_view_2d(ctx0, xz, d_inner, xz->ne[1], xz->nb[1], ggml_element_size(xz)*d_inner);
  7568. // conv
  7569. {
  7570. // Custom operator which is needed only to ease simultaneous sequence processing.
  7571. // For a single sequence, the equivalent is to concatenate the columns of conv_states and x,
  7572. // then make a self-overlapping view of that over d_conv columns at each stride in the 3rd dimension,
  7573. // then element-wise multiply that with the conv1d weigth,
  7574. // then sum the elements of each row,
  7575. // (the last two steps are a dot product over rows (also doable with mul_mat))
  7576. // then permute away the ne[0] dimension,
  7577. // and then you're left with the resulting x tensor.
  7578. // The new conv_states is the last (d_conv - 1) columns
  7579. // of the last 3rd dimensional "layer" of the self-overlapping view.
  7580. // For simultaneous sequences, it's more complicated.
  7581. struct ggml_tensor * x_conv = ggml_ssm_conv(ctx0, conv_states, x, model.layers[il].ssm_conv1d, state_seq);
  7582. // store last (d_conv - 1) columns of the conv_state part of x_conv back into the KV cache
  7583. ggml_build_forward_expand(gf,
  7584. ggml_cpy(ctx0,
  7585. 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)),
  7586. 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))));
  7587. // extract x from x_conv
  7588. x = ggml_view_2d(ctx0, x_conv, d_inner, n_tokens, d_inner*ggml_element_size(x_conv), 0);
  7589. // bias
  7590. x = ggml_add(ctx0, x, model.layers[il].ssm_conv1d_b);
  7591. x = ggml_silu(ctx0, x);
  7592. }
  7593. // ssm
  7594. {
  7595. // {d_inner, dt_rank + 2*d_state} * {d_inner, n_tokens} => {dt_rank + 2*d_state, n_tokens}
  7596. struct ggml_tensor * x_db = ggml_mul_mat(ctx0, model.layers[il].ssm_x, x);
  7597. // split
  7598. struct ggml_tensor * dt = ggml_view_2d(ctx0, x_db, dt_rank, n_tokens, x_db->nb[1], 0);
  7599. 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);
  7600. 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));
  7601. // {dt_rank, d_inner} * {dt_rank, n_tokens} => {d_inner, n_tokens}
  7602. dt = ggml_mul_mat(ctx0, model.layers[il].ssm_dt, dt);
  7603. dt = ggml_add(ctx0, dt, model.layers[il].ssm_dt_b);
  7604. // Custom operator to optimize the parallel associative scan
  7605. // as described in the Annex D of the Mamba paper.
  7606. // => {d_inner, n_tokens} and {d_state, d_inner, n_kv} combined,
  7607. // because only a single tensor can be returned.
  7608. struct ggml_tensor * y_ssm_states = ggml_ssm_scan(ctx0, ssm_states, x, dt, model.layers[il].ssm_a, B, C, state_seq);
  7609. // store last states (the second part of y_ssm_states)
  7610. ggml_build_forward_expand(gf,
  7611. ggml_cpy(ctx0,
  7612. ggml_view_1d(ctx0, y_ssm_states, d_state*d_inner*n_kv, d_inner*n_tokens*ggml_element_size(y_ssm_states)),
  7613. 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))));
  7614. struct ggml_tensor * y = ggml_view_2d(ctx0, y_ssm_states, d_inner, n_tokens, d_inner*ggml_element_size(y_ssm_states), 0);
  7615. if (il == n_layer - 1) {
  7616. // skip computing output for unused tokens
  7617. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7618. x = ggml_get_rows(ctx0, x, inp_out_ids);
  7619. y = ggml_get_rows(ctx0, y, inp_out_ids);
  7620. z = ggml_get_rows(ctx0, z, inp_out_ids);
  7621. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  7622. }
  7623. // {d_inner, n_tokens} * {d_inner} => {d_inner, n_tokens}
  7624. y = ggml_add(ctx0, y, ggml_mul(ctx0, x, model.layers[il].ssm_d));
  7625. y = ggml_mul(ctx0, y, ggml_silu(ctx0, z));
  7626. // {d_inner, n_embd} * {d_inner, n_tokens} => {n_embd, n_tokens}
  7627. cur = ggml_mul_mat(ctx0, model.layers[il].ssm_out, y);
  7628. }
  7629. // residual
  7630. cur = ggml_add(ctx0, cur, inpL);
  7631. cb(cur, "l_out", il);
  7632. // input for next layer
  7633. inpL = cur;
  7634. }
  7635. // final rmsnorm
  7636. cur = llm_build_norm(ctx0, inpL, hparams,
  7637. model.output_norm, NULL,
  7638. LLM_NORM_RMS, cb, -1);
  7639. cb(cur, "result_norm", -1);
  7640. // lm_head
  7641. cur = ggml_mul_mat(ctx0, model.output, cur);
  7642. cb(cur, "result_output", -1);
  7643. ggml_build_forward_expand(gf, cur);
  7644. return gf;
  7645. }
  7646. struct ggml_cgraph * build_command_r() {
  7647. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7648. const int64_t n_embd_head = hparams.n_embd_head_v;
  7649. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7650. const float f_logit_scale = hparams.f_logit_scale;
  7651. struct ggml_tensor * cur;
  7652. struct ggml_tensor * inpL;
  7653. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7654. // inp_pos - contains the positions
  7655. struct ggml_tensor * inp_pos = build_inp_pos();
  7656. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7657. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7658. for (int il = 0; il < n_layer; ++il) {
  7659. // norm
  7660. cur = llm_build_norm(ctx0, inpL, hparams,
  7661. model.layers[il].attn_norm, NULL,
  7662. LLM_NORM, cb, il);
  7663. cb(cur, "attn_norm", il);
  7664. struct ggml_tensor * ffn_inp = cur;
  7665. // self-attention
  7666. {
  7667. // compute Q and K and RoPE them
  7668. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  7669. cb(Qcur, "Qcur", il);
  7670. if (model.layers[il].bq) {
  7671. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  7672. cb(Qcur, "Qcur", il);
  7673. }
  7674. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  7675. cb(Kcur, "Kcur", il);
  7676. if (model.layers[il].bk) {
  7677. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  7678. cb(Kcur, "Kcur", il);
  7679. }
  7680. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  7681. cb(Vcur, "Vcur", il);
  7682. if (model.layers[il].bv) {
  7683. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  7684. cb(Vcur, "Vcur", il);
  7685. }
  7686. Qcur = ggml_rope_custom(
  7687. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  7688. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7689. ext_factor, attn_factor, beta_fast, beta_slow
  7690. );
  7691. cb(Qcur, "Qcur", il);
  7692. Kcur = ggml_rope_custom(
  7693. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  7694. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7695. ext_factor, attn_factor, beta_fast, beta_slow
  7696. );
  7697. cb(Kcur, "Kcur", il);
  7698. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  7699. model.layers[il].wo, model.layers[il].bo,
  7700. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7701. }
  7702. if (il == n_layer - 1) {
  7703. // skip computing output for unused tokens
  7704. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7705. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7706. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  7707. ffn_inp = ggml_get_rows(ctx0, ffn_inp, inp_out_ids);
  7708. }
  7709. struct ggml_tensor * attn_out = cur;
  7710. // feed-forward network
  7711. {
  7712. cur = llm_build_ffn(ctx0, ffn_inp,
  7713. model.layers[il].ffn_up, NULL,
  7714. model.layers[il].ffn_gate, NULL,
  7715. model.layers[il].ffn_down, NULL,
  7716. NULL,
  7717. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  7718. cb(cur, "ffn_out", il);
  7719. }
  7720. // add together residual + FFN + self-attention
  7721. cur = ggml_add(ctx0, cur, inpL);
  7722. cur = ggml_add(ctx0, cur, attn_out);
  7723. cb(cur, "l_out", il);
  7724. // input for next layer
  7725. inpL = cur;
  7726. }
  7727. cur = inpL;
  7728. cur = llm_build_norm(ctx0, cur, hparams,
  7729. model.output_norm, NULL,
  7730. LLM_NORM, cb, -1);
  7731. cb(cur, "result_norm", -1);
  7732. // lm_head
  7733. cur = ggml_mul_mat(ctx0, model.output, cur);
  7734. if (f_logit_scale) {
  7735. cur = ggml_scale(ctx0, cur, f_logit_scale);
  7736. }
  7737. cb(cur, "result_output", -1);
  7738. ggml_build_forward_expand(gf, cur);
  7739. return gf;
  7740. }
  7741. };
  7742. static struct ggml_cgraph * llama_build_graph_defrag(llama_context & lctx, const std::vector<uint32_t> & ids) {
  7743. llama_batch dummy;
  7744. dummy.n_tokens = 0;
  7745. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  7746. struct llm_build_context llm(lctx, dummy, cb, false);
  7747. llm.init();
  7748. struct ggml_cgraph * result = llm.build_defrag(ids);
  7749. llm.free();
  7750. return result;
  7751. }
  7752. static struct ggml_cgraph * llama_build_graph_k_shift(llama_context & lctx) {
  7753. llama_batch dummy;
  7754. dummy.n_tokens = 0;
  7755. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  7756. struct llm_build_context llm(lctx, dummy, cb, false);
  7757. llm.init();
  7758. struct ggml_cgraph * result = llm.build_k_shift();
  7759. llm.free();
  7760. return result;
  7761. }
  7762. static struct ggml_cgraph * llama_build_graph_s_copy(llama_context & lctx) {
  7763. llama_batch dummy;
  7764. dummy.n_tokens = 0;
  7765. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  7766. struct llm_build_context llm(lctx, dummy, cb, false);
  7767. llm.init();
  7768. struct ggml_cgraph * result = llm.build_s_copy();
  7769. llm.free();
  7770. return result;
  7771. }
  7772. static struct ggml_cgraph * llama_build_graph(
  7773. llama_context & lctx,
  7774. const llama_batch & batch,
  7775. bool worst_case) {
  7776. const auto & model = lctx.model;
  7777. // this callback allows us to apply custom logic to each tensor (e.g. ggml-alloc, offloading, etc.)
  7778. llm_build_cb cb = [&](struct ggml_tensor * cur, const char * name, int il) {
  7779. if (il >= 0) {
  7780. ggml_format_name(cur, "%s-%d", name, il);
  7781. } else {
  7782. ggml_set_name(cur, name);
  7783. }
  7784. if (!lctx.cparams.offload_kqv) {
  7785. if (strcmp(name, "kqv_merged_cont") == 0) {
  7786. // all nodes between the KV store and the attention output are run on the CPU
  7787. ggml_backend_sched_set_tensor_backend(lctx.sched, cur, lctx.backend_cpu);
  7788. }
  7789. }
  7790. // norm may be automatically assigned to the backend of the previous layer, increasing data transfer between backends
  7791. // FIXME: fix in ggml_backend_sched
  7792. const bool full_offload = lctx.model.n_gpu_layers > (int)lctx.model.hparams.n_layer;
  7793. if (batch.n_tokens < 32 || full_offload) {
  7794. if (il != -1 && strcmp(name, "norm") == 0) {
  7795. for (auto * backend : lctx.backends) {
  7796. if (ggml_backend_buft_supports_backend(lctx.model.buft_layer[il].buft, backend)) {
  7797. ggml_backend_sched_set_tensor_backend(lctx.sched, cur, backend);
  7798. break;
  7799. }
  7800. }
  7801. }
  7802. }
  7803. };
  7804. struct ggml_cgraph * result = NULL;
  7805. struct llm_build_context llm(lctx, batch, cb, worst_case);
  7806. llm.init();
  7807. switch (model.arch) {
  7808. case LLM_ARCH_LLAMA:
  7809. {
  7810. result = llm.build_llama();
  7811. } break;
  7812. case LLM_ARCH_BAICHUAN:
  7813. {
  7814. result = llm.build_baichuan();
  7815. } break;
  7816. case LLM_ARCH_FALCON:
  7817. {
  7818. result = llm.build_falcon();
  7819. } break;
  7820. case LLM_ARCH_GROK:
  7821. {
  7822. result = llm.build_grok();
  7823. } break;
  7824. case LLM_ARCH_STARCODER:
  7825. {
  7826. result = llm.build_starcoder();
  7827. } break;
  7828. case LLM_ARCH_PERSIMMON:
  7829. {
  7830. result = llm.build_persimmon();
  7831. } break;
  7832. case LLM_ARCH_REFACT:
  7833. {
  7834. result = llm.build_refact();
  7835. } break;
  7836. case LLM_ARCH_BERT:
  7837. case LLM_ARCH_NOMIC_BERT:
  7838. {
  7839. result = llm.build_bert();
  7840. } break;
  7841. case LLM_ARCH_BLOOM:
  7842. {
  7843. result = llm.build_bloom();
  7844. } break;
  7845. case LLM_ARCH_MPT:
  7846. {
  7847. result = llm.build_mpt();
  7848. } break;
  7849. case LLM_ARCH_STABLELM:
  7850. {
  7851. result = llm.build_stablelm();
  7852. } break;
  7853. case LLM_ARCH_QWEN:
  7854. {
  7855. result = llm.build_qwen();
  7856. } break;
  7857. case LLM_ARCH_QWEN2:
  7858. {
  7859. result = llm.build_qwen2();
  7860. } break;
  7861. case LLM_ARCH_PHI2:
  7862. {
  7863. result = llm.build_phi2();
  7864. } break;
  7865. case LLM_ARCH_PLAMO:
  7866. {
  7867. result = llm.build_plamo();
  7868. } break;
  7869. case LLM_ARCH_GPT2:
  7870. {
  7871. result = llm.build_gpt2();
  7872. } break;
  7873. case LLM_ARCH_CODESHELL:
  7874. {
  7875. result = llm.build_codeshell();
  7876. } break;
  7877. case LLM_ARCH_ORION:
  7878. {
  7879. result = llm.build_orion();
  7880. } break;
  7881. case LLM_ARCH_INTERNLM2:
  7882. {
  7883. result = llm.build_internlm2();
  7884. } break;
  7885. case LLM_ARCH_MINICPM:
  7886. {
  7887. result = llm.build_minicpm();
  7888. } break;
  7889. case LLM_ARCH_GEMMA:
  7890. {
  7891. result = llm.build_gemma();
  7892. } break;
  7893. case LLM_ARCH_STARCODER2:
  7894. {
  7895. result = llm.build_starcoder2();
  7896. } break;
  7897. case LLM_ARCH_MAMBA:
  7898. {
  7899. result = llm.build_mamba();
  7900. } break;
  7901. case LLM_ARCH_XVERSE:
  7902. {
  7903. result = llm.build_xverse();
  7904. } break;
  7905. case LLM_ARCH_COMMAND_R:
  7906. {
  7907. result = llm.build_command_r();
  7908. } break;
  7909. default:
  7910. GGML_ASSERT(false);
  7911. }
  7912. llm.free();
  7913. return result;
  7914. }
  7915. static void llama_set_k_shift(llama_context & lctx) {
  7916. const int64_t kv_size = lctx.kv_self.size;
  7917. assert(ggml_backend_buffer_is_host(lctx.inp_K_shift->buffer));
  7918. int32_t * data = (int32_t *) lctx.inp_K_shift->data;
  7919. for (int i = 0; i < kv_size; ++i) {
  7920. data[i] = lctx.kv_self.cells[i].delta;
  7921. }
  7922. }
  7923. static void llama_set_s_copy(llama_context & lctx) {
  7924. const int64_t kv_size = lctx.kv_self.size;
  7925. assert(ggml_backend_buffer_is_host(lctx.inp_s_copy->buffer));
  7926. int32_t * data = (int32_t *) lctx.inp_s_copy->data;
  7927. for (int i = 0; i < kv_size; ++i) {
  7928. data[i] = lctx.kv_self.cells[i].src;
  7929. }
  7930. }
  7931. static void llama_set_inputs(llama_context & lctx, const llama_batch & batch) {
  7932. //
  7933. // set input data
  7934. //
  7935. const auto & hparams = lctx.model.hparams;
  7936. const auto & cparams = lctx.cparams;
  7937. const auto & kv_self = lctx.kv_self;
  7938. if (batch.token) {
  7939. const int64_t n_tokens = batch.n_tokens;
  7940. ggml_backend_tensor_set(lctx.inp_tokens, batch.token, 0, n_tokens*ggml_element_size(lctx.inp_tokens));
  7941. }
  7942. if (batch.embd) {
  7943. const int64_t n_embd = hparams.n_embd;
  7944. const int64_t n_tokens = batch.n_tokens;
  7945. ggml_backend_tensor_set(lctx.inp_embd, batch.embd, 0, n_tokens*n_embd*ggml_element_size(lctx.inp_embd));
  7946. }
  7947. if (batch.pos && lctx.inp_pos) {
  7948. const int64_t n_tokens = batch.n_tokens;
  7949. ggml_backend_tensor_set(lctx.inp_pos, batch.pos, 0, n_tokens*ggml_element_size(lctx.inp_pos));
  7950. }
  7951. if (hparams.causal_attn || cparams.pooling_type == LLAMA_POOLING_TYPE_NONE) {
  7952. GGML_ASSERT(lctx.inp_out_ids && "every model that can must skip unused outputs");
  7953. const int64_t n_tokens = batch.n_tokens;
  7954. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_out_ids->buffer));
  7955. int32_t * data = (int32_t *) lctx.inp_out_ids->data;
  7956. if (lctx.n_outputs == n_tokens) {
  7957. for (int i = 0; i < n_tokens; ++i) {
  7958. data[i] = i;
  7959. }
  7960. } else if (batch.logits) {
  7961. int32_t n_outputs = 0;
  7962. for (int i = 0; i < n_tokens; ++i) {
  7963. if (batch.logits[i]) {
  7964. data[n_outputs++] = i;
  7965. }
  7966. }
  7967. // the graph needs to have been passed the correct number of outputs
  7968. GGML_ASSERT(lctx.n_outputs == n_outputs);
  7969. } else if (lctx.n_outputs == 1) {
  7970. // only keep last output
  7971. data[0] = n_tokens - 1;
  7972. } else {
  7973. GGML_ASSERT(lctx.n_outputs == 0);
  7974. }
  7975. }
  7976. GGML_ASSERT(
  7977. // (!a || b) is a logical implication (a -> b)
  7978. // !hparams.causal_attn -> !cparams.causal_attn
  7979. (hparams.causal_attn || !cparams.causal_attn) &&
  7980. "causal attention with embedding models is not supported"
  7981. );
  7982. if (lctx.inp_KQ_mask) {
  7983. // NOTE: hparams.causal_attn indicates the model is capable of generation and uses the kv cache.
  7984. if (cparams.causal_attn) {
  7985. const int64_t n_kv = kv_self.n;
  7986. const int64_t n_tokens = batch.n_tokens;
  7987. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  7988. float * data = (float *) lctx.inp_KQ_mask->data;
  7989. // For causal attention, use only the previous KV cells
  7990. // of the correct sequence for each token of the batch.
  7991. // It's assumed that if a token in the batch has multiple sequences, they are equivalent.
  7992. for (int h = 0; h < 1; ++h) {
  7993. for (int j = 0; j < n_tokens; ++j) {
  7994. const llama_pos pos = batch.pos[j];
  7995. const llama_seq_id seq_id = batch.seq_id[j][0];
  7996. for (int i = 0; i < n_kv; ++i) {
  7997. float f;
  7998. if (!lctx.kv_self.cells[i].has_seq_id(seq_id) || lctx.kv_self.cells[i].pos > pos) {
  7999. f = -INFINITY;
  8000. } else {
  8001. f = 0.0f;
  8002. }
  8003. data[h*(n_kv*n_tokens) + j*n_kv + i] = f;
  8004. }
  8005. }
  8006. }
  8007. } else {
  8008. // when using kv cache, the mask needs to match the kv cache size
  8009. const int64_t n_tokens = batch.n_tokens;
  8010. const int64_t n_stride = hparams.causal_attn ? kv_self.n : n_tokens;
  8011. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  8012. float * data = (float *) lctx.inp_KQ_mask->data;
  8013. for (int h = 0; h < 1; ++h) {
  8014. for (int j = 0; j < n_tokens; ++j) {
  8015. const llama_seq_id seq_id = batch.seq_id[j][0];
  8016. for (int i = 0; i < n_tokens; ++i) {
  8017. float f = -INFINITY;
  8018. for (int s = 0; s < batch.n_seq_id[i]; ++s) {
  8019. if (batch.seq_id[i][s] == seq_id) {
  8020. f = 0.0f;
  8021. break;
  8022. }
  8023. }
  8024. data[h*(n_tokens*n_tokens) + j*n_stride + i] = f;
  8025. }
  8026. for (int i = n_tokens; i < n_stride; ++i) {
  8027. data[h*(n_tokens*n_tokens) + j*n_stride + i] = -INFINITY;
  8028. }
  8029. }
  8030. }
  8031. }
  8032. }
  8033. if (hparams.need_kq_pos) {
  8034. const int64_t n_kv = kv_self.n;
  8035. GGML_ASSERT(lctx.inp_KQ_pos);
  8036. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_pos->buffer));
  8037. float * data = (float *) lctx.inp_KQ_pos->data;
  8038. for (int i = 0; i < n_kv; ++i) {
  8039. data[i] = float(lctx.kv_self.cells[i].pos);
  8040. }
  8041. }
  8042. if (cparams.pooling_type == LLAMA_POOLING_TYPE_MEAN) {
  8043. const int64_t n_tokens = batch.n_tokens;
  8044. GGML_ASSERT(lctx.inp_mean);
  8045. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_mean->buffer));
  8046. float * data = (float *) lctx.inp_mean->data;
  8047. memset(lctx.inp_mean->data, 0, n_tokens * n_tokens * ggml_element_size(lctx.inp_mean));
  8048. std::vector<uint64_t> sum(n_tokens, 0);
  8049. for (int i = 0; i < n_tokens; ++i) {
  8050. const llama_seq_id seq_id = batch.seq_id[i][0];
  8051. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == MEAN");
  8052. sum[seq_id] += 1;
  8053. }
  8054. std::vector<float> div(n_tokens, 0.0f);
  8055. for (int i = 0; i < n_tokens; ++i) {
  8056. const uint64_t s = sum[i];
  8057. if (s > 0) {
  8058. div[i] = 1.0f/float(s);
  8059. }
  8060. }
  8061. for (int i = 0; i < n_tokens; ++i) {
  8062. const llama_seq_id seq_id = batch.seq_id[i][0];
  8063. data[seq_id*n_tokens + i] = div[seq_id];
  8064. }
  8065. }
  8066. if (cparams.pooling_type == LLAMA_POOLING_TYPE_CLS) {
  8067. const int64_t n_tokens = batch.n_tokens;
  8068. GGML_ASSERT(lctx.inp_cls);
  8069. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_cls->buffer));
  8070. uint32_t * data = (uint32_t *) lctx.inp_cls->data;
  8071. memset(lctx.inp_cls->data, 0, n_tokens * ggml_element_size(lctx.inp_cls));
  8072. for (int i = 0; i < n_tokens; ++i) {
  8073. const llama_seq_id seq_id = batch.seq_id[i][0];
  8074. const llama_pos pos = batch.pos[i];
  8075. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == CLS");
  8076. if (pos == 0) {
  8077. data[seq_id] = i;
  8078. }
  8079. }
  8080. }
  8081. if (kv_self.recurrent) {
  8082. const int64_t n_kv = kv_self.n;
  8083. if (lctx.inp_s_mask) {
  8084. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_s_mask->buffer));
  8085. float * data = (float *) lctx.inp_s_mask->data;
  8086. // states which are not affected by the current batch are left untouched
  8087. for (int i = 0; i < n_kv; ++i) {
  8088. llama_seq_id seq_id = i + lctx.kv_self.head;
  8089. llama_kv_cell & kv_cell = lctx.kv_self.cells[seq_id];
  8090. bool has_self_seq = kv_cell.has_seq_id(seq_id);
  8091. data[i] = (float) has_self_seq;
  8092. // ensure current sequences will be kept
  8093. if (!has_self_seq && kv_cell.pos >= 0) {
  8094. kv_cell.seq_id.insert(seq_id);
  8095. }
  8096. }
  8097. }
  8098. // For Mamba (and other recurrent architectures),
  8099. // update the correct state(s)/sequence(s) for each token of the batch.
  8100. // Like with the KQ_mask, if a token in the batch has multiple sequences,
  8101. // they are assumed to be equivalent (not here, but in ggml_ssm_scan and ggml_ssm_conv).
  8102. if (lctx.inp_s_seq) {
  8103. const int64_t n_tokens = batch.n_tokens;
  8104. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_s_seq->buffer));
  8105. int32_t * data = (int32_t *) lctx.inp_s_seq->data;
  8106. for (int j = 0; j < n_tokens; ++j) {
  8107. const int32_t n_seq = batch.n_seq_id[j];
  8108. GGML_ASSERT(0 < n_seq); // a token should be part of at least 1 sequence
  8109. for (int i = 0; i < n_kv; ++i) {
  8110. if (i < n_seq) {
  8111. // for this type of model, the head is the minimum seq_id of the batch
  8112. data[j*n_kv + i] = batch.seq_id[j][i] - kv_self.head;
  8113. } else {
  8114. data[j*n_kv + i] = -1;
  8115. }
  8116. }
  8117. }
  8118. }
  8119. }
  8120. }
  8121. // Make sure enough space is available for outputs.
  8122. // Returns max number of outputs for which space was reserved.
  8123. static size_t llama_output_reserve(llama_context & lctx, size_t n_outputs) {
  8124. const auto & cparams = lctx.cparams;
  8125. const auto & hparams = lctx.model.hparams;
  8126. const size_t n_outputs_max = std::max(n_outputs, (size_t) cparams.n_seq_max);
  8127. const auto n_batch = cparams.n_batch;
  8128. const auto n_vocab = hparams.n_vocab;
  8129. const auto n_embd = hparams.n_embd;
  8130. // TODO: use a per-batch flag for logits presence instead
  8131. const bool has_logits = cparams.causal_attn;
  8132. const bool has_embd = cparams.embeddings && (hparams.causal_attn || cparams.pooling_type == LLAMA_POOLING_TYPE_NONE);
  8133. const size_t logits_size = has_logits ? n_vocab*n_outputs_max : 0;
  8134. const size_t embd_size = has_embd ? n_embd*n_outputs_max : 0;
  8135. if (lctx.output_ids.empty()) {
  8136. // init, never resized afterwards
  8137. lctx.output_ids.resize(n_batch);
  8138. }
  8139. const size_t prev_size = lctx.buf_output ? ggml_backend_buffer_get_size(lctx.buf_output) : 0;
  8140. const size_t new_size = (logits_size + embd_size) * sizeof(float);
  8141. // alloc only when more than the current capacity is required
  8142. // TODO: also consider shrinking the buffer
  8143. if (!lctx.buf_output || prev_size < new_size) {
  8144. if (lctx.buf_output) {
  8145. #ifndef NDEBUG
  8146. // This doesn't happen often, but may be annoying in some cases (like the HellaSwag benchmark)
  8147. 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);
  8148. #endif
  8149. ggml_backend_buffer_free(lctx.buf_output);
  8150. lctx.buf_output = nullptr;
  8151. lctx.logits = nullptr;
  8152. lctx.embd = nullptr;
  8153. }
  8154. lctx.buf_output = ggml_backend_buft_alloc_buffer(llama_default_buffer_type_cpu(true), new_size);
  8155. if (lctx.buf_output == nullptr) {
  8156. LLAMA_LOG_ERROR("%s: failed to allocate output buffer of size %.2f MiB\n", __func__, new_size / (1024.0 * 1024.0));
  8157. return 0;
  8158. }
  8159. }
  8160. float * output_base = (float *) ggml_backend_buffer_get_base(lctx.buf_output);
  8161. lctx.logits = has_logits ? output_base : nullptr;
  8162. lctx.embd = has_embd ? output_base + logits_size : nullptr;
  8163. lctx.output_size = n_outputs_max;
  8164. lctx.logits_size = logits_size;
  8165. lctx.embd_size = embd_size;
  8166. // set all ids as invalid (negative)
  8167. std::fill(lctx.output_ids.begin(), lctx.output_ids.end(), -1);
  8168. ggml_backend_buffer_clear(lctx.buf_output, 0);
  8169. lctx.n_outputs = 0;
  8170. return n_outputs_max;
  8171. }
  8172. static void llama_graph_compute(
  8173. llama_context & lctx,
  8174. ggml_cgraph * gf,
  8175. int n_threads) {
  8176. #ifdef GGML_USE_MPI
  8177. const int64_t n_layer = lctx.model.hparams.n_layer;
  8178. ggml_mpi_graph_compute_pre(lctx.ctx_mpi, gf, n_layer);
  8179. #endif
  8180. #ifdef GGML_USE_METAL
  8181. if (ggml_backend_is_metal(lctx.backend_metal)) {
  8182. ggml_backend_metal_set_n_cb(lctx.backend_metal, n_threads);
  8183. }
  8184. #endif
  8185. if (lctx.backend_cpu != nullptr) {
  8186. ggml_backend_cpu_set_n_threads(lctx.backend_cpu, n_threads);
  8187. ggml_backend_cpu_set_abort_callback(lctx.backend_cpu, lctx.abort_callback, lctx.abort_callback_data);
  8188. }
  8189. ggml_backend_sched_graph_compute_async(lctx.sched, gf);
  8190. // fprintf(stderr, "splits: %d\n", ggml_backend_sched_get_n_splits(lctx.sched));
  8191. #ifdef GGML_USE_MPI
  8192. ggml_mpi_graph_compute_post(lctx.ctx_mpi, gf, n_layer);
  8193. #endif
  8194. }
  8195. // decode a batch of tokens by evaluating the transformer
  8196. //
  8197. // - lctx: llama context
  8198. // - batch: batch to evaluate
  8199. //
  8200. // return 0 on success
  8201. // return positive int on warning
  8202. // return negative int on error
  8203. //
  8204. static int llama_decode_internal(
  8205. llama_context & lctx,
  8206. llama_batch batch_all) { // TODO: rename back to batch
  8207. const uint32_t n_tokens_all = batch_all.n_tokens;
  8208. if (n_tokens_all == 0) {
  8209. LLAMA_LOG_ERROR("%s: n_tokens == 0", __func__);
  8210. return -1;
  8211. }
  8212. const auto & model = lctx.model;
  8213. const auto & hparams = model.hparams;
  8214. const auto & cparams = lctx.cparams;
  8215. GGML_ASSERT((!batch_all.token && batch_all.embd) || (batch_all.token && !batch_all.embd)); // NOLINT
  8216. GGML_ASSERT(n_tokens_all <= cparams.n_batch);
  8217. GGML_ASSERT((cparams.causal_attn || cparams.n_ubatch >= n_tokens_all) && "non-causal attention requires n_ubatch >= n_tokens");
  8218. if (lctx.t_compute_start_us == 0) {
  8219. lctx.t_compute_start_us = ggml_time_us();
  8220. }
  8221. lctx.n_queued_tokens += n_tokens_all;
  8222. #ifdef GGML_USE_MPI
  8223. // TODO: needs fix after #3228
  8224. GGML_ASSERT(false && "not implemented");
  8225. //ggml_mpi_eval_init(lctx.ctx_mpi, &n_tokens, &n_past, &n_threads);
  8226. #endif
  8227. auto & kv_self = lctx.kv_self;
  8228. const int64_t n_embd = hparams.n_embd;
  8229. const int64_t n_vocab = hparams.n_vocab;
  8230. uint32_t n_outputs = 0;
  8231. uint32_t n_outputs_prev = 0;
  8232. const auto n_ubatch = cparams.n_ubatch;
  8233. std::vector<llama_pos> pos;
  8234. std::vector<int32_t> n_seq_id;
  8235. std::vector<llama_seq_id *> seq_id_arr;
  8236. std::vector<std::vector<llama_seq_id>> seq_id;
  8237. // count outputs
  8238. if (batch_all.logits) {
  8239. for (uint32_t i = 0; i < n_tokens_all; ++i) {
  8240. n_outputs += batch_all.logits[i] != 0;
  8241. }
  8242. } else if (lctx.logits_all || (cparams.embeddings && cparams.pooling_type != LLAMA_POOLING_TYPE_NONE)) {
  8243. n_outputs = n_tokens_all;
  8244. } else {
  8245. // keep last output only
  8246. n_outputs = 1;
  8247. }
  8248. // reserve output buffer
  8249. if (llama_output_reserve(lctx, n_outputs) < n_outputs) {
  8250. LLAMA_LOG_ERROR("%s: could not reserve space for batch with %u outputs\n", __func__, n_outputs);
  8251. return -2;
  8252. };
  8253. // set output mappings
  8254. if (batch_all.logits) {
  8255. int32_t i_logits = 0;
  8256. for (uint32_t i = 0; i < n_tokens_all; ++i) {
  8257. if (batch_all.logits[i]) {
  8258. lctx.output_ids[i] = i_logits++;
  8259. }
  8260. }
  8261. } else {
  8262. for (uint32_t i = 0; i < n_outputs; ++i) {
  8263. lctx.output_ids[i] = i;
  8264. }
  8265. }
  8266. for (uint32_t cur_token = 0; cur_token < n_tokens_all; cur_token += n_ubatch) {
  8267. const uint32_t n_tokens = std::min(n_ubatch, n_tokens_all - cur_token);
  8268. llama_batch u_batch = {
  8269. /* .n_tokens = */ (int32_t) n_tokens,
  8270. /* .token = */ batch_all.token ? batch_all.token + cur_token : nullptr,
  8271. /* .embd = */ batch_all.embd ? batch_all.embd + cur_token*n_embd : nullptr,
  8272. /* .pos = */ batch_all.pos ? batch_all.pos + cur_token : nullptr,
  8273. /* .n_seq_id = */ batch_all.n_seq_id ? batch_all.n_seq_id + cur_token : nullptr,
  8274. /* .seq_id = */ batch_all.seq_id ? batch_all.seq_id + cur_token : nullptr,
  8275. /* .logits = */ batch_all.logits ? batch_all.logits + cur_token : nullptr,
  8276. /* .all_pos_0 = */ batch_all.all_pos_0 + (llama_pos) cur_token*batch_all.all_pos_1,
  8277. /* .all_pos_1 = */ batch_all.all_pos_1,
  8278. /* .all_seq_id = */ batch_all.all_seq_id,
  8279. };
  8280. // count the outputs in this u_batch
  8281. {
  8282. int32_t n_outputs_new = 0;
  8283. if (u_batch.logits) {
  8284. for (uint32_t i = 0; i < n_tokens; i++) {
  8285. n_outputs_new += u_batch.logits[i] != 0;
  8286. }
  8287. } else if (n_outputs == n_tokens_all) {
  8288. n_outputs_new = n_tokens;
  8289. } else {
  8290. // keep last output only
  8291. if (cur_token + n_tokens >= n_tokens_all) {
  8292. n_outputs_new = 1;
  8293. }
  8294. }
  8295. // needs to happen before the graph is built
  8296. lctx.n_outputs = n_outputs_new;
  8297. }
  8298. int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  8299. GGML_ASSERT(n_threads > 0);
  8300. // helpers for smoother batch API transition
  8301. // after deprecating the llama_eval calls, these will be removed
  8302. if (u_batch.pos == nullptr) {
  8303. pos.resize(n_tokens);
  8304. for (uint32_t i = 0; i < n_tokens; i++) {
  8305. pos[i] = u_batch.all_pos_0 + i*u_batch.all_pos_1;
  8306. }
  8307. u_batch.pos = pos.data();
  8308. }
  8309. if (u_batch.seq_id == nullptr) {
  8310. n_seq_id.resize(n_tokens);
  8311. seq_id.resize(n_tokens);
  8312. seq_id_arr.resize(n_tokens);
  8313. for (uint32_t i = 0; i < n_tokens; i++) {
  8314. n_seq_id[i] = 1;
  8315. seq_id[i].resize(1);
  8316. seq_id[i][0] = u_batch.all_seq_id;
  8317. seq_id_arr[i] = seq_id[i].data();
  8318. }
  8319. u_batch.n_seq_id = n_seq_id.data();
  8320. u_batch.seq_id = seq_id_arr.data();
  8321. }
  8322. // non-causal masks do not use the KV cache
  8323. if (hparams.causal_attn) {
  8324. llama_kv_cache_update(&lctx);
  8325. // if we have enough unused cells before the current head ->
  8326. // better to start searching from the beginning of the cache, hoping to fill it
  8327. if (kv_self.head > kv_self.used + 2*n_tokens) {
  8328. kv_self.head = 0;
  8329. }
  8330. if (!llama_kv_cache_find_slot(kv_self, u_batch)) {
  8331. return 1;
  8332. }
  8333. if (!kv_self.recurrent) {
  8334. // a heuristic, to avoid attending the full cache if it is not yet utilized
  8335. // after enough generations, the benefit from this heuristic disappears
  8336. // if we start defragmenting the cache, the benefit from this will be more important
  8337. kv_self.n = std::min(kv_self.size, std::max(32u, GGML_PAD(llama_kv_cache_cell_max(kv_self), 32)));
  8338. //kv_self.n = llama_kv_cache_cell_max(kv_self);
  8339. }
  8340. }
  8341. //printf("kv_self.n = %5d, kv_self.used = %5d, kv_self.head = %5d\n", kv_self.n, kv_self.used, kv_self.head);
  8342. ggml_backend_sched_reset(lctx.sched);
  8343. ggml_backend_sched_set_eval_callback(lctx.sched, lctx.cparams.cb_eval, lctx.cparams.cb_eval_user_data);
  8344. ggml_cgraph * gf = llama_build_graph(lctx, u_batch, false);
  8345. // the output is always the last tensor in the graph
  8346. struct ggml_tensor * res = gf->nodes[gf->n_nodes - 1];
  8347. struct ggml_tensor * embd = gf->nodes[gf->n_nodes - 2];
  8348. if (lctx.n_outputs == 0) {
  8349. // no output
  8350. res = nullptr;
  8351. embd = nullptr;
  8352. } else if (!hparams.causal_attn) {
  8353. res = nullptr; // do not extract logits for embedding models such as BERT
  8354. // token or sequence embeddings
  8355. embd = gf->nodes[gf->n_nodes - 1];
  8356. GGML_ASSERT(strcmp(embd->name, "result_embd") == 0 || strcmp(embd->name, "result_embd_pooled") == 0);
  8357. } else if (cparams.embeddings) {
  8358. // the embeddings could be in the second to last tensor, or any of the previous tensors
  8359. int i_embd = gf->n_nodes - 2;
  8360. for (int i = 3; strcmp(embd->name, "result_norm") != 0; ++i) {
  8361. i_embd = gf->n_nodes - i;
  8362. if (i_embd < 0) { break; }
  8363. embd = gf->nodes[i_embd];
  8364. }
  8365. GGML_ASSERT(i_embd >= 0 && "missing result_norm tensor");
  8366. // TODO: use a per-batch flag to know when to skip logits while keeping embeddings
  8367. if (!cparams.causal_attn) {
  8368. res = nullptr; // do not extract logits when not needed
  8369. // skip computing logits
  8370. // TODO: is this safe?
  8371. gf->n_nodes = i_embd + 1;
  8372. }
  8373. } else {
  8374. embd = nullptr; // do not extract embeddings when not needed
  8375. GGML_ASSERT(strcmp(res->name, "result_output") == 0 && "missing result_output tensor");
  8376. }
  8377. // 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);
  8378. // for big prompts, if BLAS is enabled, it is better to use only one thread
  8379. // otherwise, the threads are spin-lock waiting for the BLAS calls and are degrading the performance
  8380. // TODO: this is mostly important for Apple Silicon where CBLAS is still performing very well
  8381. // we still need some threads to process all non-mul_mat ops, but not too much to avoid interfering
  8382. // with the BLAS calls. need a better solution
  8383. // MoE Special Case: This logic applies when hparams.n_expert == 0, i.e. the model is NOT an MoE model. When an MoE is
  8384. // being processed then Accelerate/BLAS will not be involved, so capping would limit performance.
  8385. if (n_tokens >= 32 && hparams.n_expert == 0 && ggml_cpu_has_blas() && !ggml_cpu_has_gpublas()) {
  8386. n_threads = std::min(4, n_threads);
  8387. }
  8388. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  8389. llama_set_inputs(lctx, u_batch);
  8390. llama_graph_compute(lctx, gf, n_threads);
  8391. // update the kv ring buffer
  8392. {
  8393. kv_self.head += n_tokens;
  8394. // Ensure kv cache head points to a valid index.
  8395. if (kv_self.head >= kv_self.size) {
  8396. kv_self.head = 0;
  8397. }
  8398. }
  8399. #ifdef GGML_PERF
  8400. // print timing information per ggml operation (for debugging purposes)
  8401. // requires GGML_PERF to be defined
  8402. ggml_graph_print(gf);
  8403. #endif
  8404. // plot the computation graph in dot format (for debugging purposes)
  8405. //if (n_past%100 == 0) {
  8406. // ggml_graph_dump_dot(gf, NULL, "llama.dot");
  8407. //}
  8408. // extract logits
  8409. if (res) {
  8410. ggml_backend_t backend_res = ggml_backend_sched_get_tensor_backend(lctx.sched, res);
  8411. GGML_ASSERT(backend_res != nullptr);
  8412. GGML_ASSERT(lctx.logits != nullptr);
  8413. float * logits_out = lctx.logits + n_outputs_prev*n_vocab;
  8414. const int32_t n_outputs_new = lctx.n_outputs;
  8415. if (n_outputs_new) {
  8416. GGML_ASSERT( n_outputs_prev + n_outputs_new <= n_outputs);
  8417. GGML_ASSERT((n_outputs_prev + n_outputs_new)*n_vocab <= (int64_t) lctx.logits_size);
  8418. ggml_backend_tensor_get_async(backend_res, res, logits_out, 0, n_outputs_new*n_vocab*sizeof(float));
  8419. }
  8420. }
  8421. // extract embeddings
  8422. if (embd) {
  8423. ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend(lctx.sched, embd);
  8424. GGML_ASSERT(backend_embd != nullptr);
  8425. switch (cparams.pooling_type) {
  8426. case LLAMA_POOLING_TYPE_NONE:
  8427. {
  8428. // extract token embeddings
  8429. GGML_ASSERT(lctx.embd != nullptr);
  8430. float * embd_out = lctx.embd + n_outputs_prev*n_embd;
  8431. const int32_t n_outputs_new = lctx.n_outputs;
  8432. if (n_outputs_new) {
  8433. GGML_ASSERT( n_outputs_prev + n_outputs_new <= n_outputs);
  8434. GGML_ASSERT((n_outputs_prev + n_outputs_new)*n_embd <= (int64_t) lctx.embd_size);
  8435. ggml_backend_tensor_get_async(backend_embd, embd, embd_out, 0, n_outputs_new*n_embd*sizeof(float));
  8436. }
  8437. } break;
  8438. case LLAMA_POOLING_TYPE_CLS:
  8439. case LLAMA_POOLING_TYPE_MEAN:
  8440. {
  8441. GGML_ASSERT(strcmp(embd->name, "result_embd_pooled") == 0);
  8442. // extract sequence embeddings
  8443. auto & embd_seq_out = lctx.embd_seq;
  8444. embd_seq_out.clear();
  8445. for (uint32_t i = 0; i < n_tokens; i++) {
  8446. const llama_seq_id seq_id = u_batch.seq_id[i][0];
  8447. if (embd_seq_out.find(seq_id) != embd_seq_out.end()) {
  8448. continue;
  8449. }
  8450. embd_seq_out[seq_id].resize(n_embd);
  8451. ggml_backend_tensor_get_async(backend_embd, embd, embd_seq_out[seq_id].data(), (n_embd*seq_id)*sizeof(float), n_embd*sizeof(float));
  8452. }
  8453. } break;
  8454. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  8455. {
  8456. GGML_ASSERT(false && "unknown pooling type");
  8457. } break;
  8458. }
  8459. }
  8460. n_outputs_prev += lctx.n_outputs;
  8461. }
  8462. // wait for the computation to finish (automatically done when obtaining the model output)
  8463. //llama_synchronize(&lctx);
  8464. // decide if we need to defrag the kv cache
  8465. if (cparams.causal_attn && cparams.defrag_thold >= 0.0f) {
  8466. const float fragmentation = kv_self.n >= 128 ? 1.0f - float(kv_self.used)/float(kv_self.n) : 0.0f;
  8467. // queue defragmentation for next llama_kv_cache_update
  8468. if (fragmentation > cparams.defrag_thold) {
  8469. //LLAMA_LOG_INFO("fragmentation: %.2f\n", fragmentation);
  8470. llama_kv_cache_defrag(kv_self);
  8471. }
  8472. }
  8473. return 0;
  8474. }
  8475. // find holes from the beginning of the KV cache and fill them by moving data from the end of the cache
  8476. static void llama_kv_cache_defrag_internal(struct llama_context & lctx) {
  8477. auto & kv_self = lctx.kv_self;
  8478. const auto & hparams = lctx.model.hparams;
  8479. const uint32_t n_layer = hparams.n_layer;
  8480. const uint32_t n_kv = llama_kv_cache_cell_max(kv_self);
  8481. const uint32_t n_used = kv_self.used;
  8482. assert(n_used <= n_kv);
  8483. //const int64_t t_start = ggml_time_us();
  8484. // number of cells moved
  8485. uint32_t n_moves = 0;
  8486. // each move requires 6*n_layer tensors (see build_defrag)
  8487. // - source view, destination view, copy operation
  8488. // - x2 for keys and values
  8489. const uint32_t max_moves = LLAMA_MAX_NODES/(6*n_layer);
  8490. // determine which KV cells to move where
  8491. //
  8492. // cell i moves to ids[i]
  8493. //
  8494. // if ids[i] == i || ids[i] == n_kv, then cell i is not moved
  8495. //
  8496. std::vector<uint32_t> ids(n_kv, n_kv);
  8497. for (uint32_t i0 = 0; i0 < n_used; ++i0) {
  8498. const auto & cell0 = kv_self.cells[i0];
  8499. if (!cell0.is_empty()) {
  8500. ids[i0] = i0;
  8501. continue;
  8502. }
  8503. // found a hole - fill it with data from the end of the cache
  8504. uint32_t nh = 1;
  8505. // determine the size of the hole
  8506. while (i0 + nh < n_used && kv_self.cells[i0 + nh].is_empty()) {
  8507. nh++;
  8508. }
  8509. uint32_t nf = 0;
  8510. uint32_t is = n_kv - 1;
  8511. // starting from the end, find nh non-empty cells
  8512. for (; is > i0; --is) {
  8513. const auto & cell1 = kv_self.cells[is];
  8514. if (cell1.is_empty() || ids[is] != n_kv) {
  8515. continue;
  8516. }
  8517. // non-empty cell which is not yet moved
  8518. nf++;
  8519. if (nf == nh) {
  8520. break;
  8521. }
  8522. }
  8523. // this can only happen if `n_used` is not accurate, which would be a bug
  8524. GGML_ASSERT(nf == nh && "KV defrag bug: nf != nh");
  8525. nf = 0;
  8526. uint32_t i1 = is;
  8527. // are we moving a continuous block of memory?
  8528. bool cont = false;
  8529. // should we stop searching for the next move?
  8530. bool stop = false;
  8531. // go back and move the nf cells to the hole
  8532. for (; i1 < n_kv; ++i1) {
  8533. auto & cell1 = kv_self.cells[i1];
  8534. if (cell1.is_empty() || ids[i1] != n_kv) {
  8535. if (n_moves == max_moves) {
  8536. stop = true;
  8537. break;
  8538. }
  8539. cont = false;
  8540. continue;
  8541. }
  8542. // this cell goes to (i0 + nf)
  8543. ids[i1] = i0 + nf;
  8544. // move the cell meta data
  8545. kv_self.cells[i0 + nf] = cell1;
  8546. // clear the old cell and move the head there
  8547. cell1 = llama_kv_cell();
  8548. kv_self.head = n_used;
  8549. if (!cont) {
  8550. n_moves++;
  8551. cont = true;
  8552. }
  8553. nf++;
  8554. if (nf == nh) {
  8555. break;
  8556. }
  8557. }
  8558. if (stop || n_moves == max_moves) {
  8559. break;
  8560. }
  8561. //LLAMA_LOG_INFO("(tmp log) KV defrag: move [%u, %u) to [%u, %u)\n", is, i1 + 1, i0, i0 + nh);
  8562. i0 += nh - 1;
  8563. }
  8564. if (n_moves == 0) {
  8565. return;
  8566. }
  8567. //LLAMA_LOG_INFO("(tmp log) KV defrag cell moves: %u\n", n_moves);
  8568. //LLAMA_LOG_INFO("expected gf nodes: %u\n", 6*n_moves*n_layer);
  8569. #if 0
  8570. // CPU defrag
  8571. //
  8572. // TODO: optimizations are possible:
  8573. // - multiple threads
  8574. // - avoid copying to the host memory when already there
  8575. //
  8576. // likely not worth the effort, as we have ggml_graph based defrag
  8577. //
  8578. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  8579. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  8580. const uint32_t kv_size = kv_self.size;
  8581. std::vector<uint8_t> buf_k;
  8582. std::vector<uint8_t> buf_v;
  8583. for (uint32_t il = 0; il < n_layer; ++il) {
  8584. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  8585. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_size);
  8586. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  8587. const size_t v_size = ggml_row_size (kv_self.v_l[il]->type, n_embd_v_gqa*kv_size);
  8588. buf_k.resize(k_size);
  8589. buf_v.resize(v_size);
  8590. ggml_backend_tensor_get(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  8591. ggml_backend_tensor_get(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  8592. // batch move [i, i+nm) to [id, id+nm)
  8593. // note: cells can move only to a lower index
  8594. for (uint32_t i = 0; i < n_kv; ++i) {
  8595. const uint32_t id = ids[i];
  8596. if (i == id || id == n_kv) {
  8597. continue;
  8598. }
  8599. uint32_t nm = 1;
  8600. while (i + nm < n_kv && ids[i + nm] == id + nm) {
  8601. nm++;
  8602. }
  8603. // move keys
  8604. {
  8605. const int64_t os = i*k_size_row;
  8606. const int64_t od = id*k_size_row;
  8607. memcpy(buf_k.data() + od, buf_k.data() + os, nm*k_size_row);
  8608. }
  8609. // move values (note: they are transposed)
  8610. {
  8611. const int64_t os = i;
  8612. const int64_t od = id;
  8613. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  8614. 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);
  8615. }
  8616. }
  8617. i += nm - 1;
  8618. }
  8619. ggml_backend_tensor_set(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  8620. ggml_backend_tensor_set(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  8621. }
  8622. #else
  8623. // ggml_graph defrag
  8624. ggml_backend_sched_reset(lctx.sched);
  8625. ggml_cgraph * gf = llama_build_graph_defrag(lctx, ids);
  8626. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  8627. #endif
  8628. //const int64_t t_end = ggml_time_us();
  8629. //LLAMA_LOG_INFO("(tmp log) KV defrag time: %.3f ms\n", (t_end - t_start)/1000.0);
  8630. }
  8631. static void llama_kv_cache_update_internal(struct llama_context & lctx) {
  8632. bool need_reserve = false;
  8633. // apply K-shift if needed
  8634. if (lctx.model.hparams.rope_type != LLAMA_ROPE_TYPE_NONE && lctx.kv_self.has_shift) {
  8635. {
  8636. ggml_backend_sched_reset(lctx.sched);
  8637. ggml_cgraph * gf = llama_build_graph_k_shift(lctx);
  8638. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  8639. llama_set_k_shift(lctx);
  8640. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  8641. need_reserve = true;
  8642. }
  8643. {
  8644. auto & kv_self = lctx.kv_self;
  8645. kv_self.has_shift = false;
  8646. for (uint32_t i = 0; i < kv_self.size; ++i) {
  8647. kv_self.cells[i].delta = 0;
  8648. }
  8649. }
  8650. }
  8651. if (lctx.kv_self.recurrent && lctx.kv_self.do_copy) {
  8652. {
  8653. ggml_backend_sched_reset(lctx.sched);
  8654. ggml_cgraph * gf = llama_build_graph_s_copy(lctx);
  8655. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  8656. llama_set_s_copy(lctx);
  8657. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  8658. need_reserve = true;
  8659. }
  8660. {
  8661. auto & kv_self = lctx.kv_self;
  8662. kv_self.do_copy = false;
  8663. for (uint32_t i = 0; i < kv_self.size; ++i) {
  8664. kv_self.cells[i].src = i;
  8665. }
  8666. }
  8667. }
  8668. // defragment the KV cache if needed
  8669. if (lctx.kv_self.do_defrag) {
  8670. llama_kv_cache_defrag_internal(lctx);
  8671. need_reserve = true;
  8672. lctx.kv_self.do_defrag = false;
  8673. }
  8674. // reserve a worst case graph again
  8675. if (need_reserve) {
  8676. // TODO: extract to a function
  8677. // build worst-case graph
  8678. int n_tokens = (int)std::min(lctx.cparams.n_ctx, lctx.cparams.n_ubatch);
  8679. int n_past = lctx.cparams.n_ctx - n_tokens;
  8680. 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
  8681. ggml_cgraph * gf = llama_build_graph(lctx, llama_batch_get_one(&token, n_tokens, n_past, 0), true);
  8682. // initialize scheduler with the worst-case graph
  8683. ggml_backend_sched_reset(lctx.sched);
  8684. if (!ggml_backend_sched_reserve(lctx.sched, gf)) {
  8685. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  8686. }
  8687. }
  8688. }
  8689. //
  8690. // tokenizer
  8691. //
  8692. static enum llama_vocab_type llama_vocab_get_type(const llama_vocab & vocab) {
  8693. return vocab.type;
  8694. }
  8695. static bool llama_is_normal_token(const llama_vocab & vocab, llama_token id) {
  8696. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  8697. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL;
  8698. }
  8699. static bool llama_is_unknown_token(const llama_vocab & vocab, llama_token id) {
  8700. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  8701. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_UNKNOWN;
  8702. }
  8703. static bool llama_is_control_token(const llama_vocab & vocab, llama_token id) {
  8704. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  8705. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_CONTROL;
  8706. }
  8707. static bool llama_is_byte_token(const llama_vocab & vocab, llama_token id) {
  8708. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  8709. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_BYTE;
  8710. }
  8711. static bool llama_is_user_defined_token(const llama_vocab& vocab, llama_token id) {
  8712. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  8713. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_USER_DEFINED;
  8714. }
  8715. static uint8_t llama_token_to_byte(const llama_vocab& vocab, llama_token id) {
  8716. GGML_ASSERT(llama_vocab_get_type(vocab) != LLAMA_VOCAB_TYPE_NONE);
  8717. GGML_ASSERT(llama_is_byte_token(vocab, id));
  8718. const auto& token_data = vocab.id_to_token.at(id);
  8719. switch (llama_vocab_get_type(vocab)) {
  8720. case LLAMA_VOCAB_TYPE_SPM: {
  8721. auto buf = token_data.text.substr(3, 2);
  8722. return strtol(buf.c_str(), NULL, 16);
  8723. }
  8724. case LLAMA_VOCAB_TYPE_BPE: {
  8725. GGML_ASSERT(false);
  8726. return unicode_utf8_to_byte(token_data.text);
  8727. }
  8728. case LLAMA_VOCAB_TYPE_WPM: {
  8729. GGML_ASSERT(false);
  8730. }
  8731. default:
  8732. GGML_ASSERT(false);
  8733. }
  8734. }
  8735. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch) {
  8736. GGML_ASSERT(llama_vocab_get_type(vocab) != LLAMA_VOCAB_TYPE_NONE);
  8737. static const char * hex = "0123456789ABCDEF";
  8738. switch (llama_vocab_get_type(vocab)) {
  8739. case LLAMA_VOCAB_TYPE_SPM: {
  8740. const char buf[7] = { '<', '0', 'x', hex[ch >> 4], hex[ch & 15], '>', 0 };
  8741. auto token = vocab.token_to_id.find(buf);
  8742. if (token != vocab.token_to_id.end()) {
  8743. return (*token).second;
  8744. }
  8745. // Try to fall back to just the byte as a string
  8746. const char buf2[2] = { (char)ch, 0 };
  8747. return vocab.token_to_id.at(buf2);
  8748. }
  8749. case LLAMA_VOCAB_TYPE_WPM:
  8750. case LLAMA_VOCAB_TYPE_BPE: {
  8751. return vocab.token_to_id.at(unicode_byte_to_utf8(ch));
  8752. }
  8753. default:
  8754. GGML_ASSERT(false);
  8755. }
  8756. }
  8757. static void llama_escape_whitespace(std::string & text) {
  8758. replace_all(text, " ", "\xe2\x96\x81");
  8759. }
  8760. static void llama_unescape_whitespace(std::string & word) {
  8761. replace_all(word, "\xe2\x96\x81", " ");
  8762. }
  8763. struct llm_symbol {
  8764. using index = int;
  8765. index prev;
  8766. index next;
  8767. const char * text;
  8768. size_t n;
  8769. };
  8770. static_assert(std::is_trivially_copyable<llm_symbol>::value, "llm_symbol is not trivially copyable");
  8771. // SPM tokenizer
  8772. // original implementation:
  8773. // https://github.com/ggerganov/llama.cpp/commit/074bea2eb1f1349a0118239c4152914aecaa1be4
  8774. struct llm_bigram_spm {
  8775. struct comparator {
  8776. bool operator()(llm_bigram_spm & l, llm_bigram_spm & r) {
  8777. return (l.score < r.score) || (l.score == r.score && l.left > r.left);
  8778. }
  8779. };
  8780. using queue_storage = std::vector<llm_bigram_spm>;
  8781. using queue = std::priority_queue<llm_bigram_spm, queue_storage, comparator>;
  8782. llm_symbol::index left;
  8783. llm_symbol::index right;
  8784. float score;
  8785. size_t size;
  8786. };
  8787. struct llm_tokenizer_spm {
  8788. llm_tokenizer_spm(const llama_vocab & vocab) : vocab(vocab) {}
  8789. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  8790. // split string into utf8 chars
  8791. int index = 0;
  8792. size_t offs = 0;
  8793. while (offs < text.size()) {
  8794. llm_symbol sym;
  8795. size_t len = utf8_len(text[offs]);
  8796. sym.text = text.c_str() + offs;
  8797. sym.n = std::min(len, text.size() - offs);
  8798. offs += sym.n;
  8799. sym.prev = index - 1;
  8800. sym.next = offs == text.size() ? -1 : index + 1;
  8801. index++;
  8802. symbols.emplace_back(sym);
  8803. }
  8804. // seed the work queue with all possible 2-character tokens.
  8805. for (size_t i = 1; i < symbols.size(); ++i) {
  8806. try_add_bigram(i - 1, i);
  8807. }
  8808. // keep substituting the highest frequency pairs for as long as we can.
  8809. while (!work_queue.empty()) {
  8810. auto bigram = work_queue.top();
  8811. work_queue.pop();
  8812. auto & left_sym = symbols[bigram.left];
  8813. auto & right_sym = symbols[bigram.right];
  8814. // if one of the symbols already got merged, skip it.
  8815. if (left_sym.n == 0 || right_sym.n == 0 ||
  8816. left_sym.n + right_sym.n != bigram.size) {
  8817. continue;
  8818. }
  8819. // merge the right sym into the left one
  8820. left_sym.n += right_sym.n;
  8821. right_sym.n = 0;
  8822. //LLAMA_LOG_INFO("left = '%*s' size = %zu\n", (int) left_sym.n, left_sym.text, bigram.size);
  8823. // remove the right sym from the chain
  8824. left_sym.next = right_sym.next;
  8825. if (right_sym.next >= 0) {
  8826. symbols[right_sym.next].prev = bigram.left;
  8827. }
  8828. // find more substitutions
  8829. try_add_bigram(left_sym.prev, bigram.left);
  8830. try_add_bigram(bigram.left, left_sym.next);
  8831. }
  8832. for (int i = 0; i != -1; i = symbols[i].next) {
  8833. auto & symbol = symbols[i];
  8834. resegment(symbol, output);
  8835. }
  8836. }
  8837. private:
  8838. void resegment(llm_symbol & symbol, std::vector<llama_vocab::id> & output) {
  8839. auto text = std::string(symbol.text, symbol.n);
  8840. auto token = vocab.token_to_id.find(text);
  8841. // Do we need to support is_unused?
  8842. if (token != vocab.token_to_id.end()) {
  8843. output.push_back((*token).second);
  8844. return;
  8845. }
  8846. const auto p = rev_merge.find(text);
  8847. if (p == rev_merge.end()) {
  8848. // output any symbols that did not form tokens as bytes.
  8849. output.reserve(output.size() + symbol.n);
  8850. for (int j = 0; j < (int)symbol.n; ++j) {
  8851. llama_vocab::id token_id = llama_byte_to_token(vocab, symbol.text[j]);
  8852. output.push_back(token_id);
  8853. }
  8854. return;
  8855. }
  8856. resegment(symbols[p->second.first], output);
  8857. resegment(symbols[p->second.second], output);
  8858. }
  8859. void try_add_bigram(int left, int right) {
  8860. if (left == -1 || right == -1) {
  8861. return;
  8862. }
  8863. const std::string text = std::string(symbols[left].text, symbols[left].n + symbols[right].n);
  8864. auto token = vocab.token_to_id.find(text);
  8865. if (token == vocab.token_to_id.end()) {
  8866. return;
  8867. }
  8868. if (static_cast<size_t>((*token).second) >= vocab.id_to_token.size()) {
  8869. return;
  8870. }
  8871. const auto & tok_data = vocab.id_to_token[(*token).second];
  8872. llm_bigram_spm bigram;
  8873. bigram.left = left;
  8874. bigram.right = right;
  8875. bigram.score = tok_data.score;
  8876. bigram.size = text.size();
  8877. work_queue.push(bigram);
  8878. // Do we need to support is_unused?
  8879. rev_merge[text] = std::make_pair(left, right);
  8880. }
  8881. const llama_vocab & vocab;
  8882. std::vector<llm_symbol> symbols;
  8883. llm_bigram_spm::queue work_queue;
  8884. std::map<std::string, std::pair<int, int>> rev_merge;
  8885. };
  8886. // BPE tokenizer
  8887. // adapted from https://github.com/cmp-nct/ggllm.cpp [MIT License]
  8888. // tried to simplify unicode stuff, so most likely does not work 100% correctly!
  8889. // TODO: there are a lot of common parts between spm and bpe tokenizers, should be refactored and reused
  8890. struct llm_bigram_bpe {
  8891. struct comparator {
  8892. bool operator()(const llm_bigram_bpe & l, const llm_bigram_bpe & r) const {
  8893. return l.rank > r.rank || (l.rank == r.rank && l.left > r.left);
  8894. }
  8895. };
  8896. using queue_storage = std::vector<llm_bigram_bpe>;
  8897. using queue = std::priority_queue<llm_bigram_bpe, queue_storage, comparator>;
  8898. llm_symbol::index left;
  8899. llm_symbol::index right;
  8900. std::string text;
  8901. int rank;
  8902. size_t size;
  8903. };
  8904. struct llm_tokenizer_bpe {
  8905. llm_tokenizer_bpe(const llama_vocab & vocab): vocab(vocab) {}
  8906. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  8907. int final_prev_index = -1;
  8908. auto word_collection = bpe_gpt2_preprocess(text);
  8909. symbols_final.clear();
  8910. for (auto & word : word_collection) {
  8911. work_queue = llm_bigram_bpe::queue();
  8912. symbols.clear();
  8913. int index = 0;
  8914. size_t offset = 0;
  8915. while (offset < word.size()) {
  8916. llm_symbol sym;
  8917. size_t char_len = std::min(word.size() - offset, (size_t) ::utf8_len(word[offset]));
  8918. sym.text = word.c_str() + offset;
  8919. sym.n = char_len;
  8920. offset += sym.n;
  8921. sym.prev = index - 1;
  8922. sym.next = offset == word.size() ? -1 : index + 1;
  8923. index++;
  8924. symbols.emplace_back(sym);
  8925. }
  8926. for (size_t i = 1; i < symbols.size(); ++i) {
  8927. add_new_bigram(i - 1, i);
  8928. }
  8929. // build token(s)
  8930. while (!work_queue.empty()) {
  8931. auto bigram = work_queue.top();
  8932. work_queue.pop();
  8933. auto & left_symbol = symbols[bigram.left];
  8934. auto & right_symbol = symbols[bigram.right];
  8935. if (left_symbol.n == 0 || right_symbol.n == 0) {
  8936. continue;
  8937. }
  8938. std::string left_token = std::string(left_symbol.text, left_symbol.n);
  8939. std::string right_token = std::string(right_symbol.text, right_symbol.n);
  8940. if (left_token + right_token != bigram.text) {
  8941. continue; // Skip this bigram if it's outdated
  8942. }
  8943. // merge the right sym into the left one
  8944. left_symbol.n += right_symbol.n;
  8945. right_symbol.n = 0;
  8946. // remove the right sym from the chain
  8947. left_symbol.next = right_symbol.next;
  8948. if (right_symbol.next >= 0) {
  8949. symbols[right_symbol.next].prev = bigram.left;
  8950. }
  8951. add_new_bigram(left_symbol.prev, bigram.left); // left side of current symbol
  8952. add_new_bigram(bigram.left, left_symbol.next); // right side of current symbol
  8953. }
  8954. // add the fnished tokens to the final list keeping correct order for next and prev
  8955. for (auto & sym : symbols) {
  8956. if (sym.n > 0) {
  8957. sym.prev = final_prev_index;
  8958. sym.next = -1;
  8959. if (final_prev_index != -1) {
  8960. symbols_final[final_prev_index].next = symbols_final.size();
  8961. }
  8962. symbols_final.emplace_back(sym);
  8963. final_prev_index = symbols_final.size() - 1;
  8964. }
  8965. }
  8966. }
  8967. symbols = symbols_final;
  8968. if (!symbols.empty()) {
  8969. for (int i = 0; i != -1; i = symbols[i].next) {
  8970. auto & symbol = symbols[i];
  8971. if (symbol.n == 0) {
  8972. continue;
  8973. }
  8974. const std::string str = std::string(symbol.text, symbol.n);
  8975. const auto token = vocab.token_to_id.find(str);
  8976. if (token == vocab.token_to_id.end()) {
  8977. for (auto j = str.begin(); j != str.end(); ++j) {
  8978. std::string byte_str(1, *j);
  8979. auto token_multibyte = vocab.token_to_id.find(byte_str);
  8980. if (token_multibyte == vocab.token_to_id.end()) {
  8981. throw std::runtime_error("ERROR: byte not found in vocab");
  8982. }
  8983. output.push_back((*token_multibyte).second);
  8984. }
  8985. } else {
  8986. output.push_back((*token).second);
  8987. }
  8988. }
  8989. }
  8990. }
  8991. private:
  8992. void add_new_bigram(int left, int right) {
  8993. if (left == -1 || right == -1) {
  8994. return;
  8995. }
  8996. std::string left_token = std::string(symbols[left].text, symbols[left].n);
  8997. std::string right_token = std::string(symbols[right].text, symbols[right].n);
  8998. int rank_found = -1;
  8999. rank_found = vocab.find_bpe_rank(left_token, right_token);
  9000. if (rank_found < 0) {
  9001. return;
  9002. }
  9003. llm_bigram_bpe bigram;
  9004. bigram.left = left;
  9005. bigram.right = right;
  9006. bigram.text = left_token + right_token;
  9007. bigram.size = left_token.size() + right_token.size();
  9008. bigram.rank = rank_found;
  9009. work_queue.push(bigram);
  9010. }
  9011. std::vector<std::string> bpe_gpt2_preprocess(const std::string & text) {
  9012. std::vector<std::string> bpe_words;
  9013. std::vector<std::string> bpe_encoded_words;
  9014. std::string token = "";
  9015. // GPT2 system regex: 's|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+
  9016. bool collecting_numeric = false;
  9017. bool collecting_letter = false;
  9018. bool collecting_special = false;
  9019. bool collecting_whitespace_lookahead = false;
  9020. bool collecting = false;
  9021. std::vector<std::string> text_utf;
  9022. text_utf.reserve(text.size());
  9023. bpe_words.reserve(text.size());
  9024. bpe_encoded_words.reserve(text.size());
  9025. const auto cpts = unicode_cpts_from_utf8(text);
  9026. for (size_t i = 0; i < cpts.size(); ++i)
  9027. text_utf.emplace_back(unicode_cpt_to_utf8(cpts[i]));
  9028. for (int i = 0; i < (int)text_utf.size(); i++) {
  9029. const std::string & utf_char = text_utf[i];
  9030. bool split_condition = false;
  9031. int bytes_remain = text_utf.size() - i;
  9032. // forward backward lookups
  9033. const std::string & utf_char_next = (i + 1 < (int)text_utf.size()) ? text_utf[i + 1] : "";
  9034. const std::string & utf_char_next_next = (i + 2 < (int)text_utf.size()) ? text_utf[i + 2] : "";
  9035. // handling contractions
  9036. if (!split_condition && bytes_remain >= 2) {
  9037. // 's|'t|'m|'d
  9038. if (utf_char == "\'" && (utf_char_next == "s" || utf_char_next == "t" || utf_char_next == "m" || utf_char_next == "d")) {
  9039. split_condition = true;
  9040. }
  9041. if (split_condition) {
  9042. if (token.size()) {
  9043. bpe_words.emplace_back(token); // push previous content as token
  9044. }
  9045. token = utf_char + utf_char_next;
  9046. bpe_words.emplace_back(token);
  9047. token = "";
  9048. i++;
  9049. continue;
  9050. }
  9051. }
  9052. if (!split_condition && bytes_remain >= 3) {
  9053. // 're|'ve|'ll
  9054. if (utf_char == "\'" && (
  9055. (utf_char_next == "r" && utf_char_next_next == "e") ||
  9056. (utf_char_next == "v" && utf_char_next_next == "e") ||
  9057. (utf_char_next == "l" && utf_char_next_next == "l"))
  9058. ) {
  9059. split_condition = true;
  9060. }
  9061. if (split_condition) {
  9062. // current token + next token can be defined
  9063. if (token.size()) {
  9064. bpe_words.emplace_back(token); // push previous content as token
  9065. }
  9066. token = utf_char + utf_char_next + utf_char_next_next;
  9067. bpe_words.emplace_back(token); // the contraction
  9068. token = "";
  9069. i += 2;
  9070. continue;
  9071. }
  9072. }
  9073. if (!split_condition && !collecting) {
  9074. if (unicode_cpt_type(utf_char) == CODEPOINT_TYPE_LETTER || (!token.size() && utf_char == " " && unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_LETTER)) {
  9075. collecting_letter = true;
  9076. collecting = true;
  9077. }
  9078. else if (unicode_cpt_type(utf_char) == CODEPOINT_TYPE_DIGIT || (!token.size() && utf_char == " " && unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  9079. collecting_numeric = true;
  9080. collecting = true;
  9081. }
  9082. else if (
  9083. ((unicode_cpt_type(utf_char) != CODEPOINT_TYPE_LETTER && unicode_cpt_type(utf_char) != CODEPOINT_TYPE_DIGIT) && (unicode_cpt_type(utf_char) != CODEPOINT_TYPE_WHITESPACE)) ||
  9084. (!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)
  9085. ) {
  9086. collecting_special = true;
  9087. collecting = true;
  9088. }
  9089. else if (unicode_cpt_type(utf_char) == CODEPOINT_TYPE_WHITESPACE && unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_WHITESPACE) {
  9090. collecting_whitespace_lookahead = true;
  9091. collecting = true;
  9092. }
  9093. else if (unicode_cpt_type(utf_char) == CODEPOINT_TYPE_WHITESPACE) {
  9094. split_condition = true;
  9095. }
  9096. }
  9097. else if (!split_condition && collecting) {
  9098. if (collecting_letter && unicode_cpt_type(utf_char) != CODEPOINT_TYPE_LETTER) {
  9099. split_condition = true;
  9100. }
  9101. else if (collecting_numeric && unicode_cpt_type(utf_char) != CODEPOINT_TYPE_DIGIT) {
  9102. split_condition = true;
  9103. }
  9104. 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)) {
  9105. split_condition = true;
  9106. }
  9107. else if (collecting_whitespace_lookahead && (unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_LETTER || unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  9108. split_condition = true;
  9109. }
  9110. }
  9111. if (utf_char_next == "") {
  9112. split_condition = true; // final
  9113. token += utf_char;
  9114. }
  9115. if (split_condition) {
  9116. if (token.size()) {
  9117. bpe_words.emplace_back(token);
  9118. }
  9119. token = utf_char;
  9120. collecting = false;
  9121. collecting_letter = false;
  9122. collecting_numeric = false;
  9123. collecting_special = false;
  9124. collecting_whitespace_lookahead = false;
  9125. }
  9126. else {
  9127. token += utf_char;
  9128. }
  9129. }
  9130. for (std::string & word : bpe_words) {
  9131. std::string encoded_token = "";
  9132. for (char & c : word) {
  9133. encoded_token += unicode_byte_to_utf8(c);
  9134. }
  9135. bpe_encoded_words.emplace_back(encoded_token);
  9136. }
  9137. return bpe_encoded_words;
  9138. }
  9139. const llama_vocab & vocab;
  9140. std::vector<llm_symbol> symbols;
  9141. std::vector<llm_symbol> symbols_final;
  9142. llm_bigram_bpe::queue work_queue;
  9143. };
  9144. struct llm_tokenizer_wpm {
  9145. llm_tokenizer_wpm(const llama_vocab & vocab): vocab(vocab) {}
  9146. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  9147. auto * token_map = &vocab.token_to_id;
  9148. // normalize and split by whitespace
  9149. std::vector<std::string> words = preprocess(text);
  9150. // bos token prepended already
  9151. // find the longest tokens that form the words
  9152. for (const std::string &word : words) {
  9153. // skip empty words
  9154. if (word.size() == 0) {
  9155. continue;
  9156. }
  9157. // prepend phantom space
  9158. std::string word1 = "\xe2\x96\x81" + word;
  9159. int n = word1.size();
  9160. // we're at the start of a new word
  9161. int i = 0;
  9162. bool match_any = false;
  9163. // move through character position in word
  9164. while (i < n) {
  9165. // loop through possible match length
  9166. bool match = false;
  9167. for (int j = n; j > i; j--) {
  9168. auto it = token_map->find(word1.substr(i, j - i));
  9169. if (it != token_map->end()) {
  9170. output.push_back(it->second);
  9171. match = true;
  9172. match_any = true;
  9173. i = j;
  9174. break;
  9175. }
  9176. }
  9177. // must be an unknown character
  9178. if (!match) {
  9179. i++;
  9180. }
  9181. }
  9182. // we didn't find any matches for this word
  9183. if (!match_any) {
  9184. output.push_back(vocab.special_unk_id);
  9185. }
  9186. }
  9187. // append eos token
  9188. output.push_back(vocab.special_eos_id);
  9189. }
  9190. std::vector<std::string> preprocess(const std::string & text) {
  9191. std::vector<uint32_t> cpts_nfd = unicode_cpts_normalize_nfd(unicode_cpts_from_utf8(text));
  9192. // strip accents, strip control, uniformize whitespace,
  9193. // to lowercase, pad chinese characters, pad punctuation
  9194. std::string new_str = "";
  9195. for (uint32_t code : cpts_nfd) {
  9196. int type = unicode_cpt_type(code);
  9197. if (type == CODEPOINT_TYPE_ACCENT_MARK || type == CODEPOINT_TYPE_CONTROL) {
  9198. continue;
  9199. }
  9200. code = unicode_tolower(code);
  9201. if (type == CODEPOINT_TYPE_WHITESPACE) {
  9202. code = ' ';
  9203. }
  9204. std::string s = unicode_cpt_to_utf8(code);
  9205. if (type == CODEPOINT_TYPE_PUNCTUATION || is_ascii_punct(code) || is_chinese_char(code)) {
  9206. new_str += " ";
  9207. new_str += s;
  9208. new_str += " ";
  9209. } else {
  9210. new_str += s;
  9211. }
  9212. }
  9213. // split by whitespace
  9214. uint64_t l = 0;
  9215. uint64_t r = 0;
  9216. std::vector<std::string> words;
  9217. while (r < new_str.size()) {
  9218. // if is whitespace
  9219. if (isspace(new_str[r], std::locale::classic())) {
  9220. if (r > l) words.push_back(new_str.substr(l, (r - l)));
  9221. l = r + 1;
  9222. r = l;
  9223. } else {
  9224. r += 1;
  9225. }
  9226. }
  9227. if (r > l) {
  9228. words.push_back(new_str.substr(l, (r - l)));
  9229. }
  9230. return words;
  9231. }
  9232. bool is_ascii_punct(uint32_t code) {
  9233. if (code > 0xFF) {
  9234. return false;
  9235. }
  9236. auto c = char(static_cast<unsigned char>(code));
  9237. return ispunct(c, std::locale::classic());
  9238. }
  9239. bool is_chinese_char(uint32_t cpt) {
  9240. if ((cpt >= 0x4E00 && cpt <= 0x9FFF) ||
  9241. (cpt >= 0x3400 && cpt <= 0x4DBF) ||
  9242. (cpt >= 0x20000 && cpt <= 0x2A6DF) ||
  9243. (cpt >= 0x2A700 && cpt <= 0x2B73F) ||
  9244. (cpt >= 0x2B740 && cpt <= 0x2B81F) ||
  9245. (cpt >= 0x2B920 && cpt <= 0x2CEAF) || // this should be 0x2B820 but in hf rust code it is 0x2B920
  9246. (cpt >= 0xF900 && cpt <= 0xFAFF) ||
  9247. (cpt >= 0x2F800 && cpt <= 0x2FA1F) ||
  9248. (cpt >= 0x3000 && cpt <= 0x303F) ||
  9249. (cpt >= 0xFF00 && cpt <= 0xFFEF)) {
  9250. return true; // NOLINT
  9251. }
  9252. return false;
  9253. }
  9254. const llama_vocab & vocab;
  9255. };
  9256. typedef enum FRAGMENT_BUFFER_VARIANT_TYPE {
  9257. FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN,
  9258. FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT
  9259. } FRAGMENT_BUFFER_VARIANT_TYPE;
  9260. struct fragment_buffer_variant {
  9261. fragment_buffer_variant(llama_vocab::id _token)
  9262. :
  9263. type(FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN),
  9264. token(_token),
  9265. raw_text(_dummy),
  9266. offset(0),
  9267. length(0) {}
  9268. fragment_buffer_variant(const std::string & _raw_text, int64_t _offset, int64_t _length)
  9269. :
  9270. type(FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT),
  9271. token((llama_vocab::id) - 1),
  9272. raw_text(_raw_text),
  9273. offset(_offset),
  9274. length(_length){
  9275. GGML_ASSERT(_offset >= 0);
  9276. GGML_ASSERT(_length >= 1);
  9277. GGML_ASSERT(offset + length <= raw_text.length());
  9278. }
  9279. const FRAGMENT_BUFFER_VARIANT_TYPE type;
  9280. const llama_vocab::id token;
  9281. const std::string _dummy;
  9282. const std::string & raw_text;
  9283. const uint64_t offset;
  9284. const uint64_t length;
  9285. };
  9286. // #define PRETOKENIZERDEBUG
  9287. static void tokenizer_st_partition(const llama_vocab & vocab, std::forward_list<fragment_buffer_variant> & buffer) {
  9288. // for each special token
  9289. for (const auto & st: vocab.special_tokens_cache) {
  9290. const auto & special_token = st.first;
  9291. const auto & special_id = st.second;
  9292. // for each text fragment
  9293. std::forward_list<fragment_buffer_variant>::iterator it = buffer.begin();
  9294. while (it != buffer.end()) {
  9295. auto & fragment = (*it);
  9296. // if a fragment is text ( not yet processed )
  9297. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  9298. auto * raw_text = &(fragment.raw_text);
  9299. auto raw_text_base_offset = fragment.offset;
  9300. auto raw_text_base_length = fragment.length;
  9301. // loop over the text
  9302. while (true) {
  9303. // find the first occurrence of a given special token in this fragment
  9304. // passing offset argument only limit the "search area" but match coordinates
  9305. // are still relative to the source full raw_text
  9306. auto match = raw_text->find(special_token, raw_text_base_offset);
  9307. // no occurrences found, stop processing this fragment for a given special token
  9308. if (match == std::string::npos) break;
  9309. // check if match is within bounds of offset <-> length
  9310. if (match + special_token.length() > raw_text_base_offset + raw_text_base_length) break;
  9311. #ifdef PRETOKENIZERDEBUG
  9312. 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());
  9313. #endif
  9314. auto source = std::distance(buffer.begin(), it);
  9315. // if match is further than base offset
  9316. // then we have some text to the left of it
  9317. if (match > raw_text_base_offset) {
  9318. // left
  9319. const int64_t left_reminder_offset = raw_text_base_offset + 0;
  9320. const int64_t left_reminder_length = match - raw_text_base_offset;
  9321. buffer.emplace_after(it, (*raw_text), left_reminder_offset, left_reminder_length);
  9322. #ifdef PRETOKENIZERDEBUG
  9323. 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());
  9324. #endif
  9325. it++;
  9326. }
  9327. // special token
  9328. buffer.emplace_after(it, special_id);
  9329. it++;
  9330. // right
  9331. if (match + special_token.length() < raw_text_base_offset + raw_text_base_length) {
  9332. const int64_t right_reminder_offset = match + special_token.length();
  9333. const int64_t right_reminder_length = raw_text_base_length - ((match - raw_text_base_offset) + special_token.length());
  9334. buffer.emplace_after(it, (*raw_text), right_reminder_offset, right_reminder_length);
  9335. #ifdef PRETOKENIZERDEBUG
  9336. 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());
  9337. #endif
  9338. it++;
  9339. if (source == 0) {
  9340. buffer.erase_after(buffer.before_begin());
  9341. } else {
  9342. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  9343. }
  9344. // repeat for the right side
  9345. raw_text_base_offset = right_reminder_offset;
  9346. raw_text_base_length = right_reminder_length;
  9347. #ifdef PRETOKENIZERDEBUG
  9348. 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());
  9349. #endif
  9350. } else {
  9351. if (source == 0) {
  9352. buffer.erase_after(buffer.before_begin());
  9353. } else {
  9354. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  9355. }
  9356. break;
  9357. }
  9358. }
  9359. }
  9360. it++;
  9361. }
  9362. }
  9363. }
  9364. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special) {
  9365. std::vector<llama_vocab::id> output;
  9366. // OG tokenizer behavior:
  9367. //
  9368. // tokenizer.encode('', add_bos=True) returns [1]
  9369. // tokenizer.encode('', add_bos=False) returns []
  9370. if (bos && vocab.special_bos_id != -1) {
  9371. output.push_back(vocab.special_bos_id);
  9372. }
  9373. if (raw_text.empty()) {
  9374. return output;
  9375. }
  9376. std::forward_list<fragment_buffer_variant> fragment_buffer;
  9377. fragment_buffer.emplace_front(raw_text, 0, raw_text.length());
  9378. if (special) tokenizer_st_partition(vocab, fragment_buffer);
  9379. switch (vocab.type) {
  9380. case LLAMA_VOCAB_TYPE_SPM:
  9381. {
  9382. for (const auto & fragment : fragment_buffer) {
  9383. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  9384. // without adding this leading whitespace, we do not get the same results as the original tokenizer
  9385. // TODO: It's likely possible to get rid of this string copy entirely
  9386. // by modifying llm_tokenizer_x to operate with string offsets like pre-tokenizer
  9387. // and passing 'add space prefix' as bool argument
  9388. //
  9389. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  9390. if (&fragment == &fragment_buffer.front()) {
  9391. if (vocab.add_space_prefix) {
  9392. raw_text = " " + raw_text; // prefix with space if the first token is not special
  9393. }
  9394. }
  9395. #ifdef PRETOKENIZERDEBUG
  9396. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  9397. #endif
  9398. llm_tokenizer_spm tokenizer(vocab);
  9399. llama_escape_whitespace(raw_text);
  9400. tokenizer.tokenize(raw_text, output);
  9401. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  9402. output.push_back(fragment.token);
  9403. }
  9404. }
  9405. } break;
  9406. case LLAMA_VOCAB_TYPE_BPE:
  9407. {
  9408. for (const auto & fragment : fragment_buffer) {
  9409. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  9410. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  9411. #ifdef PRETOKENIZERDEBUG
  9412. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  9413. #endif
  9414. llm_tokenizer_bpe tokenizer(vocab);
  9415. tokenizer.tokenize(raw_text, output);
  9416. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  9417. output.push_back(fragment.token);
  9418. }
  9419. }
  9420. } break;
  9421. case LLAMA_VOCAB_TYPE_WPM:
  9422. {
  9423. for (const auto & fragment : fragment_buffer) {
  9424. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  9425. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  9426. #ifdef PRETOKENIZERDEBUG
  9427. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  9428. #endif
  9429. llm_tokenizer_wpm tokenizer(vocab);
  9430. tokenizer.tokenize(raw_text, output);
  9431. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  9432. output.push_back(fragment.token);
  9433. }
  9434. }
  9435. } break;
  9436. case LLAMA_VOCAB_TYPE_NONE:
  9437. GGML_ASSERT(false);
  9438. }
  9439. return output;
  9440. }
  9441. //
  9442. // grammar - internal
  9443. //
  9444. struct llama_partial_utf8 {
  9445. uint32_t value; // bit value so far (unshifted)
  9446. int n_remain; // num bytes remaining; -1 indicates invalid sequence
  9447. };
  9448. struct llama_grammar {
  9449. const std::vector<std::vector<llama_grammar_element>> rules;
  9450. std::vector<std::vector<const llama_grammar_element *>> stacks;
  9451. // buffer for partially generated UTF-8 sequence from accepted tokens
  9452. llama_partial_utf8 partial_utf8;
  9453. };
  9454. struct llama_grammar_candidate {
  9455. size_t index;
  9456. const uint32_t * code_points;
  9457. llama_partial_utf8 partial_utf8;
  9458. };
  9459. // Decodes a UTF-8 string which may end in an incomplete sequence. Adds a terminating 0 for use as
  9460. // pointer. If an invalid sequence is encountered, returns `llama_partial_utf8.n_remain == -1`.
  9461. static std::pair<std::vector<uint32_t>, llama_partial_utf8> decode_utf8(
  9462. const std::string & src,
  9463. llama_partial_utf8 partial_start) {
  9464. static const int lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 3, 4 };
  9465. const char * pos = src.c_str();
  9466. std::vector<uint32_t> code_points;
  9467. // common english strings have the same number of codepoints and bytes. `+ 1` for the terminating 0.
  9468. code_points.reserve(src.size() + 1);
  9469. uint32_t value = partial_start.value;
  9470. int n_remain = partial_start.n_remain;
  9471. // continue previous decode, if applicable
  9472. while (*pos != 0 && n_remain > 0) {
  9473. uint8_t next_byte = static_cast<uint8_t>(*pos);
  9474. if ((next_byte >> 6) != 2) {
  9475. // invalid sequence, abort
  9476. code_points.push_back(0);
  9477. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, -1 });
  9478. }
  9479. value = (value << 6) + (next_byte & 0x3F);
  9480. ++pos;
  9481. --n_remain;
  9482. }
  9483. if (partial_start.n_remain > 0 && n_remain == 0) {
  9484. code_points.push_back(value);
  9485. }
  9486. // decode any subsequent utf-8 sequences, which may end in an incomplete one
  9487. while (*pos != 0) {
  9488. uint8_t first_byte = static_cast<uint8_t>(*pos);
  9489. uint8_t highbits = first_byte >> 4;
  9490. n_remain = lookup[highbits] - 1;
  9491. if (n_remain < 0) {
  9492. // invalid sequence, abort
  9493. code_points.clear();
  9494. code_points.push_back(0);
  9495. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, n_remain });
  9496. }
  9497. uint8_t mask = (1 << (7 - n_remain)) - 1;
  9498. value = first_byte & mask;
  9499. ++pos;
  9500. while (*pos != 0 && n_remain > 0) {
  9501. value = (value << 6) + (static_cast<uint8_t>(*pos) & 0x3F);
  9502. ++pos;
  9503. --n_remain;
  9504. }
  9505. if (n_remain == 0) {
  9506. code_points.push_back(value);
  9507. }
  9508. }
  9509. code_points.push_back(0);
  9510. return std::make_pair(std::move(code_points), llama_partial_utf8{ value, n_remain });
  9511. }
  9512. // returns true iff pos points to the end of one of the definitions of a rule
  9513. static bool llama_grammar_is_end_of_sequence(const llama_grammar_element * pos) {
  9514. switch (pos->type) {
  9515. case LLAMA_GRETYPE_END: return true; // NOLINT
  9516. case LLAMA_GRETYPE_ALT: return true; // NOLINT
  9517. default: return false;
  9518. }
  9519. }
  9520. // returns true iff chr satisfies the char range at pos (regular or inverse range)
  9521. // asserts that pos is pointing to a char range element
  9522. static std::pair<bool, const llama_grammar_element *> llama_grammar_match_char(
  9523. const llama_grammar_element * pos,
  9524. const uint32_t chr) {
  9525. bool found = false;
  9526. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  9527. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT); // NOLINT
  9528. do {
  9529. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  9530. // inclusive range, e.g. [a-z]
  9531. found = found || (pos->value <= chr && chr <= pos[1].value);
  9532. pos += 2;
  9533. } else {
  9534. // exact char match, e.g. [a] or "a"
  9535. found = found || pos->value == chr;
  9536. pos += 1;
  9537. }
  9538. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  9539. return std::make_pair(found == is_positive_char, pos);
  9540. }
  9541. // returns true iff some continuation of the given partial UTF-8 sequence could satisfy the char
  9542. // range at pos (regular or inverse range)
  9543. // asserts that pos is pointing to a char range element
  9544. static bool llama_grammar_match_partial_char(
  9545. const llama_grammar_element * pos,
  9546. const llama_partial_utf8 partial_utf8) {
  9547. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  9548. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT);
  9549. uint32_t partial_value = partial_utf8.value;
  9550. int n_remain = partial_utf8.n_remain;
  9551. // invalid sequence or 7-bit char split across 2 bytes (overlong)
  9552. if (n_remain < 0 || (n_remain == 1 && partial_value < 2)) {
  9553. return false;
  9554. }
  9555. // range of possible code points this partial UTF-8 sequence could complete to
  9556. uint32_t low = partial_value << (n_remain * 6);
  9557. uint32_t high = low | ((1 << (n_remain * 6)) - 1);
  9558. if (low == 0) {
  9559. if (n_remain == 2) {
  9560. low = 1 << 11;
  9561. } else if (n_remain == 3) {
  9562. low = 1 << 16;
  9563. }
  9564. }
  9565. do {
  9566. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  9567. // inclusive range, e.g. [a-z]
  9568. if (pos->value <= high && low <= pos[1].value) {
  9569. return is_positive_char;
  9570. }
  9571. pos += 2;
  9572. } else {
  9573. // exact char match, e.g. [a] or "a"
  9574. if (low <= pos->value && pos->value <= high) {
  9575. return is_positive_char;
  9576. }
  9577. pos += 1;
  9578. }
  9579. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  9580. return !is_positive_char;
  9581. }
  9582. // transforms a grammar pushdown stack into N possible stacks, all ending
  9583. // at a character range (terminal element)
  9584. static void llama_grammar_advance_stack(
  9585. const std::vector<std::vector<llama_grammar_element>> & rules,
  9586. const std::vector<const llama_grammar_element *> & stack,
  9587. std::vector<std::vector<const llama_grammar_element *>> & new_stacks) {
  9588. if (stack.empty()) {
  9589. new_stacks.emplace_back(stack);
  9590. return;
  9591. }
  9592. const llama_grammar_element * pos = stack.back();
  9593. switch (pos->type) {
  9594. case LLAMA_GRETYPE_RULE_REF: {
  9595. const size_t rule_id = static_cast<size_t>(pos->value);
  9596. const llama_grammar_element * subpos = rules[rule_id].data();
  9597. do {
  9598. // init new stack without the top (pos)
  9599. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  9600. if (!llama_grammar_is_end_of_sequence(pos + 1)) {
  9601. // if this rule ref is followed by another element, add that to stack
  9602. new_stack.push_back(pos + 1);
  9603. }
  9604. if (!llama_grammar_is_end_of_sequence(subpos)) {
  9605. // if alternate is nonempty, add to stack
  9606. new_stack.push_back(subpos);
  9607. }
  9608. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  9609. while (!llama_grammar_is_end_of_sequence(subpos)) {
  9610. // scan to end of alternate def
  9611. subpos++;
  9612. }
  9613. if (subpos->type == LLAMA_GRETYPE_ALT) {
  9614. // there's another alternate def of this rule to process
  9615. subpos++;
  9616. } else {
  9617. break;
  9618. }
  9619. } while (true);
  9620. break;
  9621. }
  9622. case LLAMA_GRETYPE_CHAR:
  9623. case LLAMA_GRETYPE_CHAR_NOT:
  9624. new_stacks.emplace_back(stack);
  9625. break;
  9626. default:
  9627. // end of alternate (LLAMA_GRETYPE_END, LLAMA_GRETYPE_ALT) or middle of char range
  9628. // (LLAMA_GRETYPE_CHAR_ALT, LLAMA_GRETYPE_CHAR_RNG_UPPER); stack should never be left on
  9629. // those
  9630. GGML_ASSERT(false);
  9631. }
  9632. }
  9633. // takes a set of possible pushdown stacks on a grammar, which are required to
  9634. // be positioned at a character range (see `llama_grammar_advance_stack`), and
  9635. // produces the N possible stacks if the given char is accepted at those
  9636. // positions
  9637. static std::vector<std::vector<const llama_grammar_element *>> llama_grammar_accept(
  9638. const std::vector<std::vector<llama_grammar_element>> & rules,
  9639. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  9640. const uint32_t chr) {
  9641. std::vector<std::vector<const llama_grammar_element *>> new_stacks;
  9642. for (const auto & stack : stacks) {
  9643. if (stack.empty()) {
  9644. continue;
  9645. }
  9646. auto match = llama_grammar_match_char(stack.back(), chr);
  9647. if (match.first) {
  9648. const llama_grammar_element * pos = match.second;
  9649. // update top of stack to next element, if any
  9650. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  9651. if (!llama_grammar_is_end_of_sequence(pos)) {
  9652. new_stack.push_back(pos);
  9653. }
  9654. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  9655. }
  9656. }
  9657. return new_stacks;
  9658. }
  9659. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  9660. const std::vector<std::vector<llama_grammar_element>> & rules,
  9661. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  9662. const std::vector<llama_grammar_candidate> & candidates);
  9663. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates_for_stack(
  9664. const std::vector<std::vector<llama_grammar_element>> & rules,
  9665. const std::vector<const llama_grammar_element *> & stack,
  9666. const std::vector<llama_grammar_candidate> & candidates) {
  9667. std::vector<llama_grammar_candidate> rejects;
  9668. if (stack.empty()) {
  9669. for (const auto & tok : candidates) {
  9670. if (*tok.code_points != 0 || tok.partial_utf8.n_remain != 0) {
  9671. rejects.push_back(tok);
  9672. }
  9673. }
  9674. return rejects;
  9675. }
  9676. const llama_grammar_element * stack_pos = stack.back();
  9677. std::vector<llama_grammar_candidate> next_candidates;
  9678. for (const auto & tok : candidates) {
  9679. if (*tok.code_points == 0) {
  9680. // reached end of full codepoints in token, reject iff it ended in a partial sequence
  9681. // that cannot satisfy this position in grammar
  9682. if (tok.partial_utf8.n_remain != 0 &&
  9683. !llama_grammar_match_partial_char(stack_pos, tok.partial_utf8)) {
  9684. rejects.push_back(tok);
  9685. }
  9686. } else if (llama_grammar_match_char(stack_pos, *tok.code_points).first) {
  9687. next_candidates.push_back({ tok.index, tok.code_points + 1, tok.partial_utf8 });
  9688. } else {
  9689. rejects.push_back(tok);
  9690. }
  9691. }
  9692. const auto * stack_pos_after = llama_grammar_match_char(stack_pos, 0).second;
  9693. // update top of stack to next element, if any
  9694. std::vector<const llama_grammar_element *> stack_after(stack.begin(), stack.end() - 1);
  9695. if (!llama_grammar_is_end_of_sequence(stack_pos_after)) {
  9696. stack_after.push_back(stack_pos_after);
  9697. }
  9698. std::vector<std::vector<const llama_grammar_element *>> next_stacks;
  9699. llama_grammar_advance_stack(rules, stack_after, next_stacks);
  9700. auto next_rejects = llama_grammar_reject_candidates(rules, next_stacks, next_candidates);
  9701. for (const auto & tok : next_rejects) {
  9702. rejects.push_back({ tok.index, tok.code_points - 1, tok.partial_utf8 });
  9703. }
  9704. return rejects;
  9705. }
  9706. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  9707. const std::vector<std::vector<llama_grammar_element>> & rules,
  9708. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  9709. const std::vector<llama_grammar_candidate> & candidates) {
  9710. GGML_ASSERT(!stacks.empty()); // REVIEW
  9711. if (candidates.empty()) {
  9712. return std::vector<llama_grammar_candidate>();
  9713. }
  9714. auto rejects = llama_grammar_reject_candidates_for_stack(rules, stacks.front(), candidates);
  9715. for (size_t i = 1, size = stacks.size(); i < size; ++i) {
  9716. rejects = llama_grammar_reject_candidates_for_stack(rules, stacks[i], rejects);
  9717. }
  9718. return rejects;
  9719. }
  9720. //
  9721. // grammar - external
  9722. //
  9723. struct llama_grammar * llama_grammar_init(
  9724. const llama_grammar_element ** rules,
  9725. size_t n_rules,
  9726. size_t start_rule_index) {
  9727. const llama_grammar_element * pos;
  9728. // copy rule definitions into vectors
  9729. std::vector<std::vector<llama_grammar_element>> vec_rules(n_rules);
  9730. for (size_t i = 0; i < n_rules; i++) {
  9731. for (pos = rules[i]; pos->type != LLAMA_GRETYPE_END; pos++) {
  9732. vec_rules[i].push_back(*pos);
  9733. }
  9734. vec_rules[i].push_back({LLAMA_GRETYPE_END, 0});
  9735. }
  9736. // loop over alternates of start rule to build initial stacks
  9737. std::vector<std::vector<const llama_grammar_element *>> stacks;
  9738. pos = vec_rules[start_rule_index].data();
  9739. do {
  9740. std::vector<const llama_grammar_element *> stack;
  9741. if (!llama_grammar_is_end_of_sequence(pos)) {
  9742. // if alternate is nonempty, add to stack
  9743. stack.push_back(pos);
  9744. }
  9745. llama_grammar_advance_stack(vec_rules, stack, stacks);
  9746. while (!llama_grammar_is_end_of_sequence(pos)) {
  9747. // scan to end of alternate def
  9748. pos++;
  9749. }
  9750. if (pos->type == LLAMA_GRETYPE_ALT) {
  9751. // there's another alternate def of this rule to process
  9752. pos++;
  9753. } else {
  9754. break;
  9755. }
  9756. } while (true);
  9757. return new llama_grammar{ std::move(vec_rules), std::move(stacks), {} };
  9758. }
  9759. void llama_grammar_free(struct llama_grammar * grammar) {
  9760. delete grammar;
  9761. }
  9762. struct llama_grammar * llama_grammar_copy(const struct llama_grammar * grammar) {
  9763. llama_grammar * result = new llama_grammar{ grammar->rules, grammar->stacks, grammar->partial_utf8 };
  9764. // redirect elements in stacks to point to new rules
  9765. for (size_t is = 0; is < result->stacks.size(); is++) {
  9766. for (size_t ie = 0; ie < result->stacks[is].size(); ie++) {
  9767. for (size_t ir0 = 0; ir0 < grammar->rules.size(); ir0++) {
  9768. for (size_t ir1 = 0; ir1 < grammar->rules[ir0].size(); ir1++) {
  9769. if (grammar->stacks[is][ie] == &grammar->rules[ir0][ir1]) {
  9770. result->stacks[is][ie] = &result->rules[ir0][ir1];
  9771. }
  9772. }
  9773. }
  9774. }
  9775. }
  9776. return result;
  9777. }
  9778. //
  9779. // sampling
  9780. //
  9781. void llama_set_rng_seed(struct llama_context * ctx, uint32_t seed) {
  9782. if (seed == LLAMA_DEFAULT_SEED) {
  9783. seed = time(NULL);
  9784. }
  9785. ctx->rng.seed(seed);
  9786. }
  9787. void llama_sample_softmax(struct llama_context * ctx, llama_token_data_array * candidates) {
  9788. GGML_ASSERT(candidates->size > 0);
  9789. const int64_t t_start_sample_us = ggml_time_us();
  9790. // Sort the logits in descending order
  9791. if (!candidates->sorted) {
  9792. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  9793. return a.logit > b.logit;
  9794. });
  9795. candidates->sorted = true;
  9796. }
  9797. float max_l = candidates->data[0].logit;
  9798. float cum_sum = 0.0f;
  9799. for (size_t i = 0; i < candidates->size; ++i) {
  9800. float p = expf(candidates->data[i].logit - max_l);
  9801. candidates->data[i].p = p;
  9802. cum_sum += p;
  9803. }
  9804. for (size_t i = 0; i < candidates->size; ++i) {
  9805. candidates->data[i].p /= cum_sum;
  9806. }
  9807. if (ctx) {
  9808. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9809. }
  9810. }
  9811. void llama_sample_top_k(struct llama_context * ctx, llama_token_data_array * candidates, int32_t k, size_t min_keep) {
  9812. // TODO: move bucket sort to separate function so that top_p/tail_free/typical/softmax first is equally fast
  9813. // if (k >= (int32_t)candidates->size) {
  9814. // return;
  9815. // }
  9816. const int64_t t_start_sample_us = ggml_time_us();
  9817. if (k <= 0) {
  9818. k = candidates->size;
  9819. }
  9820. k = std::max(k, (int) min_keep);
  9821. k = std::min(k, (int) candidates->size);
  9822. // Sort scores in descending order
  9823. if (!candidates->sorted) {
  9824. auto comp = [](const llama_token_data & a, const llama_token_data & b) {
  9825. return a.logit > b.logit;
  9826. };
  9827. if (k <= 128) {
  9828. std::partial_sort(candidates->data, candidates->data + k, candidates->data + candidates->size, comp);
  9829. } else {
  9830. constexpr int nbuckets = 128;
  9831. constexpr float bucket_low = -10.0f;
  9832. constexpr float bucket_high = 10.0f;
  9833. constexpr float bucket_scale = nbuckets/(bucket_high - bucket_low);
  9834. constexpr float bucker_inter = -bucket_low * bucket_scale;
  9835. std::vector<int> bucket_idx(candidates->size);
  9836. std::vector<int> histo(nbuckets, 0);
  9837. for (int i = 0; i < (int)candidates->size; ++i) {
  9838. const float val = candidates->data[i].logit;
  9839. int ib = int(bucket_scale * val + bucker_inter); //nbuckets * (val - bucket_low) / (bucket_high - bucket_low);
  9840. ib = std::max(0, std::min(nbuckets-1, ib));
  9841. bucket_idx[i] = ib;
  9842. ++histo[ib];
  9843. }
  9844. int nhave = 0;
  9845. int ib = nbuckets - 1;
  9846. for ( ; ib >= 0; --ib) {
  9847. nhave += histo[ib];
  9848. if (nhave >= k) break;
  9849. }
  9850. std::vector<llama_token_data> tmp_tokens(nhave);
  9851. auto ptr = tmp_tokens.data();
  9852. std::vector<llama_token_data*> bucket_ptrs;
  9853. bucket_ptrs.reserve(nbuckets - ib);
  9854. for (int j = nbuckets - 1; j >= ib; --j) {
  9855. bucket_ptrs.push_back(ptr);
  9856. ptr += histo[j];
  9857. }
  9858. for (int i = 0; i < (int)candidates->size; ++i) {
  9859. int j = bucket_idx[i];
  9860. if (j >= ib) {
  9861. *bucket_ptrs[nbuckets-1-j]++ = candidates->data[i];
  9862. }
  9863. }
  9864. ptr = tmp_tokens.data();
  9865. int ndone = 0;
  9866. for (int j = nbuckets-1; j > ib; --j) {
  9867. std::sort(ptr, ptr + histo[j], comp);
  9868. ptr += histo[j];
  9869. ndone += histo[j];
  9870. }
  9871. std::partial_sort(ptr, ptr + k - ndone, ptr + histo[ib], comp);
  9872. std::memcpy(candidates->data, tmp_tokens.data(), k*sizeof(llama_token_data));
  9873. }
  9874. candidates->sorted = true;
  9875. }
  9876. candidates->size = k;
  9877. if (ctx) {
  9878. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9879. }
  9880. }
  9881. void llama_sample_top_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  9882. if (p >= 1.0f) {
  9883. return;
  9884. }
  9885. llama_sample_softmax(ctx, candidates);
  9886. const int64_t t_start_sample_us = ggml_time_us();
  9887. // Compute the cumulative probabilities
  9888. float cum_sum = 0.0f;
  9889. size_t last_idx = candidates->size;
  9890. for (size_t i = 0; i < candidates->size; ++i) {
  9891. cum_sum += candidates->data[i].p;
  9892. // Check if the running sum is at least p or if we have kept at least min_keep tokens
  9893. // we set the last index to i+1 to indicate that the current iterate should be included in the set
  9894. if (cum_sum >= p && i + 1 >= min_keep) {
  9895. last_idx = i + 1;
  9896. break;
  9897. }
  9898. }
  9899. // Resize the output vector to keep only the top-p tokens
  9900. candidates->size = last_idx;
  9901. if (ctx) {
  9902. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9903. }
  9904. }
  9905. void llama_sample_min_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  9906. if (p <= 0.0f || !candidates->size) {
  9907. return;
  9908. }
  9909. const int64_t t_start_sample_us = ggml_time_us();
  9910. bool min_p_applied = false;
  9911. // if the candidates aren't sorted, try the unsorted implementation first
  9912. if (!candidates->sorted) {
  9913. std::vector<llama_token_data> filtered_tokens;
  9914. float max_logit = -FLT_MAX;
  9915. for (size_t i = 0; i < candidates->size; ++i) {
  9916. max_logit = std::max(max_logit, candidates->data[i].logit);
  9917. }
  9918. const float min_logit = max_logit + logf(p); // min logit for p_i >= p * p_max
  9919. for (size_t i = 0; i < candidates->size; ++i) {
  9920. if (candidates->data[i].logit >= min_logit) {
  9921. filtered_tokens.push_back(candidates->data[i]);
  9922. }
  9923. }
  9924. // if we have enough values the operation was a success
  9925. if (filtered_tokens.size() >= min_keep) {
  9926. memcpy(candidates->data, filtered_tokens.data(), filtered_tokens.size()*sizeof(llama_token_data));
  9927. candidates->size = filtered_tokens.size();
  9928. min_p_applied = true;
  9929. }
  9930. }
  9931. // if the candidates are sorted or the unsorted implementation failed, use this implementation
  9932. if (!min_p_applied) {
  9933. // Sort the logits in descending order
  9934. if (!candidates->sorted) {
  9935. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  9936. return a.logit > b.logit;
  9937. });
  9938. candidates->sorted = true;
  9939. }
  9940. const float min_logit = candidates->data[0].logit + logf(p); // min logit for p_i >= p * p_max
  9941. size_t i = 1; // first token always matches
  9942. for (; i < candidates->size; ++i) {
  9943. if (candidates->data[i].logit < min_logit && i >= min_keep) {
  9944. break; // prob too small
  9945. }
  9946. }
  9947. // Resize the output vector to keep only the matching tokens
  9948. candidates->size = i;
  9949. }
  9950. if (ctx) {
  9951. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9952. }
  9953. }
  9954. void llama_sample_tail_free(struct llama_context * ctx, llama_token_data_array * candidates, float z, size_t min_keep) {
  9955. if (z >= 1.0f || candidates->size <= 2) {
  9956. return;
  9957. }
  9958. llama_sample_softmax(nullptr, candidates);
  9959. const int64_t t_start_sample_us = ggml_time_us();
  9960. // Compute the first and second derivatives
  9961. std::vector<float> first_derivatives(candidates->size - 1);
  9962. std::vector<float> second_derivatives(candidates->size - 2);
  9963. for (size_t i = 0; i < first_derivatives.size(); ++i) {
  9964. first_derivatives[i] = candidates->data[i].p - candidates->data[i + 1].p;
  9965. }
  9966. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  9967. second_derivatives[i] = first_derivatives[i] - first_derivatives[i + 1];
  9968. }
  9969. // Calculate absolute value of second derivatives
  9970. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  9971. second_derivatives[i] = std::abs(second_derivatives[i]);
  9972. }
  9973. // Normalize the second derivatives
  9974. {
  9975. const float second_derivatives_sum = std::accumulate(second_derivatives.begin(), second_derivatives.end(), 0.0f);
  9976. if (second_derivatives_sum > 1e-6f) {
  9977. for (float & value : second_derivatives) {
  9978. value /= second_derivatives_sum;
  9979. }
  9980. } else {
  9981. for (float & value : second_derivatives) {
  9982. value = 1.0f / second_derivatives.size();
  9983. }
  9984. }
  9985. }
  9986. float cum_sum = 0.0f;
  9987. size_t last_idx = candidates->size;
  9988. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  9989. cum_sum += second_derivatives[i];
  9990. // Check if the running sum is greater than z or if we have kept at least min_keep tokens
  9991. if (cum_sum > z && i >= min_keep) {
  9992. last_idx = i;
  9993. break;
  9994. }
  9995. }
  9996. // Resize the output vector to keep only the tokens above the tail location
  9997. candidates->size = last_idx;
  9998. if (ctx) {
  9999. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10000. }
  10001. }
  10002. void llama_sample_typical(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  10003. // Reference implementation:
  10004. // https://github.com/huggingface/transformers/compare/main...cimeister:typical-sampling:typical-pr
  10005. if (p >= 1.0f) {
  10006. return;
  10007. }
  10008. // Compute the softmax of logits and calculate entropy
  10009. llama_sample_softmax(nullptr, candidates);
  10010. const int64_t t_start_sample_us = ggml_time_us();
  10011. float entropy = 0.0f;
  10012. for (size_t i = 0; i < candidates->size; ++i) {
  10013. entropy += -candidates->data[i].p * logf(candidates->data[i].p);
  10014. }
  10015. // Compute the absolute difference between negative log probability and entropy for each candidate
  10016. std::vector<float> shifted_scores;
  10017. for (size_t i = 0; i < candidates->size; ++i) {
  10018. float shifted_score = fabsf(-logf(candidates->data[i].p) - entropy);
  10019. shifted_scores.push_back(shifted_score);
  10020. }
  10021. // Sort tokens based on the shifted_scores and their corresponding indices
  10022. std::vector<size_t> indices(candidates->size);
  10023. std::iota(indices.begin(), indices.end(), 0);
  10024. std::sort(indices.begin(), indices.end(), [&](size_t a, size_t b) {
  10025. return shifted_scores[a] < shifted_scores[b];
  10026. });
  10027. // Compute the cumulative probabilities
  10028. float cum_sum = 0.0f;
  10029. size_t last_idx = indices.size();
  10030. for (size_t i = 0; i < indices.size(); ++i) {
  10031. size_t idx = indices[i];
  10032. cum_sum += candidates->data[idx].p;
  10033. // Check if the running sum is greater than typical or if we have kept at least min_keep tokens
  10034. if (cum_sum > p && i >= min_keep - 1) {
  10035. last_idx = i + 1;
  10036. break;
  10037. }
  10038. }
  10039. // Resize the output vector to keep only the locally typical tokens
  10040. std::vector<llama_token_data> new_candidates;
  10041. for (size_t i = 0; i < last_idx; ++i) {
  10042. size_t idx = indices[i];
  10043. new_candidates.push_back(candidates->data[idx]);
  10044. }
  10045. // Replace the data in candidates with the new_candidates data
  10046. std::copy(new_candidates.begin(), new_candidates.end(), candidates->data);
  10047. candidates->size = new_candidates.size();
  10048. candidates->sorted = false;
  10049. if (ctx) {
  10050. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10051. }
  10052. }
  10053. void llama_sample_entropy(struct llama_context * ctx, llama_token_data_array * candidates_p, float min_temp, float max_temp, float exponent_val) {
  10054. const int64_t t_start_sample_us = ggml_time_us();
  10055. // no need to do anything if there is only one (or zero) candidates
  10056. if(candidates_p->size <= 1) {
  10057. return;
  10058. }
  10059. // Calculate maximum possible entropy
  10060. float max_entropy = -logf(1.0f / candidates_p->size);
  10061. llama_sample_softmax(nullptr, candidates_p);
  10062. // Calculate entropy of the softmax probabilities
  10063. float entropy = 0.0f;
  10064. for (size_t i = 0; i < candidates_p->size; ++i) {
  10065. float prob = candidates_p->data[i].p;
  10066. if (prob > 0.0f) { // Ensure no log(0)
  10067. entropy -= prob * logf(prob);
  10068. }
  10069. }
  10070. // Normalize the entropy (max_entropy cannot be 0 here because we checked candidates_p->size != 1 above)
  10071. float normalized_entropy = entropy / max_entropy;
  10072. // Map the normalized entropy to the desired temperature range using the power function
  10073. float dyn_temp = min_temp + (max_temp - min_temp) * powf(normalized_entropy, exponent_val);
  10074. #ifdef DEBUG
  10075. LLAMA_LOG_INFO("Your text maxtemp value is: %f\n", max_temp);
  10076. LLAMA_LOG_INFO("Entropy: %f\n", entropy);
  10077. LLAMA_LOG_INFO("Max Possible Entropy: %f\n", max_entropy);
  10078. LLAMA_LOG_INFO("Normalized Entropy: %f\n", normalized_entropy);
  10079. LLAMA_LOG_INFO("Exponent: %f\n", exponent_val);
  10080. LLAMA_LOG_INFO("Dynamic Temperature (dyn_temp): %f\n", dyn_temp);
  10081. #endif
  10082. // Apply the dynamically calculated temperature scaling
  10083. for (size_t i = 0; i < candidates_p->size; ++i) {
  10084. candidates_p->data[i].logit /= dyn_temp;
  10085. }
  10086. // Re-compute softmax probabilities after scaling logits with dynamic temperature
  10087. double max_l_double = candidates_p->data[0].logit;
  10088. double cum_sum_double = 0.0;
  10089. for (size_t i = 0; i < candidates_p->size; ++i) {
  10090. double p = exp(candidates_p->data[i].logit - max_l_double);
  10091. candidates_p->data[i].p = p; // Store the scaled probability
  10092. cum_sum_double += p;
  10093. }
  10094. for (size_t i = 0; i < candidates_p->size; ++i) {
  10095. candidates_p->data[i].p /= cum_sum_double; // Re-normalize the probabilities
  10096. }
  10097. #ifdef DEBUG
  10098. // Print the updated top 25 probabilities after temperature scaling
  10099. LLAMA_LOG_INFO("\nUpdated Top 25 Probabilities After Dynamic Temperature Scaling (in percentages):\n");
  10100. for (size_t i = 0; i < 25 && i < candidates_p->size; ++i) {
  10101. LLAMA_LOG_INFO("Token %zu: %f%%\n", i + 1, candidates_p->data[i].p * 100.0f);
  10102. }
  10103. #endif
  10104. if (ctx) {
  10105. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10106. }
  10107. }
  10108. void llama_sample_temp(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  10109. const int64_t t_start_sample_us = ggml_time_us();
  10110. for (size_t i = 0; i < candidates_p->size; ++i) {
  10111. candidates_p->data[i].logit /= temp;
  10112. }
  10113. if (ctx) {
  10114. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10115. }
  10116. }
  10117. void llama_sample_repetition_penalties(
  10118. struct llama_context * ctx,
  10119. llama_token_data_array * candidates,
  10120. const llama_token * last_tokens,
  10121. size_t penalty_last_n,
  10122. float penalty_repeat,
  10123. float penalty_freq,
  10124. float penalty_present) {
  10125. if (penalty_last_n == 0 || (penalty_repeat == 1.0f && penalty_freq == 0.0f && penalty_present == 0.0f)) {
  10126. return;
  10127. }
  10128. const int64_t t_start_sample_us = ggml_time_us();
  10129. // Create a frequency map to count occurrences of each token in last_tokens
  10130. std::unordered_map<llama_token, int> token_count;
  10131. for (size_t i = 0; i < penalty_last_n; ++i) {
  10132. token_count[last_tokens[i]]++;
  10133. }
  10134. // Apply frequency and presence penalties to the candidates
  10135. for (size_t i = 0; i < candidates->size; ++i) {
  10136. const auto token_iter = token_count.find(candidates->data[i].id);
  10137. if (token_iter == token_count.end()) {
  10138. continue;
  10139. }
  10140. const int count = token_iter->second;
  10141. // 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.
  10142. // This is common fix for this problem, which is to multiply by the penalty instead of dividing.
  10143. if (candidates->data[i].logit <= 0) {
  10144. candidates->data[i].logit *= penalty_repeat;
  10145. } else {
  10146. candidates->data[i].logit /= penalty_repeat;
  10147. }
  10148. candidates->data[i].logit -= float(count) * penalty_freq + float(count > 0) * penalty_present;
  10149. }
  10150. candidates->sorted = false;
  10151. if (ctx) {
  10152. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10153. }
  10154. }
  10155. void llama_sample_grammar(struct llama_context * ctx, llama_token_data_array * candidates, const struct llama_grammar * grammar) {
  10156. GGML_ASSERT(ctx);
  10157. const int64_t t_start_sample_us = ggml_time_us();
  10158. bool allow_eos = false;
  10159. for (const auto & stack : grammar->stacks) {
  10160. if (stack.empty()) {
  10161. allow_eos = true;
  10162. break;
  10163. }
  10164. }
  10165. const llama_token eos = llama_token_eos(&ctx->model);
  10166. std::vector<std::pair<std::vector<uint32_t>, llama_partial_utf8>> candidates_decoded;
  10167. candidates_decoded.reserve(candidates->size);
  10168. std::vector<llama_grammar_candidate> candidates_grammar;
  10169. candidates_grammar.reserve(candidates->size);
  10170. for (size_t i = 0; i < candidates->size; ++i) {
  10171. const llama_token id = candidates->data[i].id;
  10172. const std::string piece = llama_token_to_piece(ctx, id);
  10173. if (id == eos) {
  10174. if (!allow_eos) {
  10175. candidates->data[i].logit = -INFINITY;
  10176. }
  10177. } else if (piece.empty() || piece[0] == 0) {
  10178. candidates->data[i].logit = -INFINITY;
  10179. } else {
  10180. candidates_decoded.push_back(decode_utf8(piece, grammar->partial_utf8));
  10181. candidates_grammar.push_back({ i, candidates_decoded.back().first.data(), candidates_decoded.back().second });
  10182. }
  10183. }
  10184. const auto rejects = llama_grammar_reject_candidates(grammar->rules, grammar->stacks, candidates_grammar);
  10185. for (const auto & reject : rejects) {
  10186. candidates->data[reject.index].logit = -INFINITY;
  10187. }
  10188. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10189. }
  10190. static void llama_log_softmax(float * array, size_t size) {
  10191. float max_l = *std::max_element(array, array + size);
  10192. float sum = 0.f;
  10193. for (size_t i = 0; i < size; ++i) {
  10194. float p = expf(array[i] - max_l);
  10195. sum += p;
  10196. array[i] = p;
  10197. }
  10198. for (size_t i = 0; i < size; ++i) {
  10199. array[i] = logf(array[i] / sum);
  10200. }
  10201. }
  10202. void llama_sample_apply_guidance(
  10203. struct llama_context * ctx,
  10204. float * logits,
  10205. float * logits_guidance,
  10206. float scale) {
  10207. GGML_ASSERT(ctx);
  10208. const auto t_start_sample_us = ggml_time_us();
  10209. const auto n_vocab = llama_n_vocab(llama_get_model(ctx));
  10210. llama_log_softmax(logits, n_vocab);
  10211. llama_log_softmax(logits_guidance, n_vocab);
  10212. for (int i = 0; i < n_vocab; ++i) {
  10213. auto & l = logits[i];
  10214. const auto & g = logits_guidance[i];
  10215. l = scale * (l - g) + g;
  10216. }
  10217. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10218. }
  10219. llama_token llama_sample_token_mirostat(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, int32_t m, float * mu) {
  10220. GGML_ASSERT(ctx);
  10221. auto N = float(llama_n_vocab(llama_get_model(ctx)));
  10222. int64_t t_start_sample_us;
  10223. t_start_sample_us = ggml_time_us();
  10224. llama_sample_softmax(nullptr, candidates);
  10225. // Estimate s_hat using the most probable m tokens
  10226. float s_hat = 0.0;
  10227. float sum_ti_bi = 0.0;
  10228. float sum_ti_sq = 0.0;
  10229. for (size_t i = 0; i < size_t(m - 1) && i < candidates->size - 1; ++i) {
  10230. float t_i = logf(float(i + 2) / float(i + 1));
  10231. float b_i = logf(candidates->data[i].p / candidates->data[i + 1].p);
  10232. sum_ti_bi += t_i * b_i;
  10233. sum_ti_sq += t_i * t_i;
  10234. }
  10235. s_hat = sum_ti_bi / sum_ti_sq;
  10236. // Compute k from the estimated s_hat and target surprise value
  10237. float epsilon_hat = s_hat - 1;
  10238. float k = powf((epsilon_hat * powf(2, *mu)) / (1 - powf(N, -epsilon_hat)), 1 / s_hat);
  10239. // Sample the next word X using top-k sampling
  10240. llama_sample_top_k(nullptr, candidates, int(k), 1);
  10241. if (ctx) {
  10242. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10243. }
  10244. llama_token X = llama_sample_token(ctx, candidates);
  10245. t_start_sample_us = ggml_time_us();
  10246. // Compute error as the difference between observed surprise and target surprise value
  10247. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  10248. return candidate.id == X;
  10249. }));
  10250. float observed_surprise = -log2f(candidates->data[X_idx].p);
  10251. float e = observed_surprise - tau;
  10252. // Update mu using the learning rate and error
  10253. *mu = *mu - eta * e;
  10254. if (ctx) {
  10255. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10256. }
  10257. return X;
  10258. }
  10259. llama_token llama_sample_token_mirostat_v2(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, float * mu) {
  10260. int64_t t_start_sample_us;
  10261. t_start_sample_us = ggml_time_us();
  10262. llama_sample_softmax(ctx, candidates);
  10263. // Truncate the words with surprise values greater than mu
  10264. candidates->size = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  10265. return -log2f(candidate.p) > *mu;
  10266. }));
  10267. if (candidates->size == 0) {
  10268. candidates->size = 1;
  10269. }
  10270. if (ctx) {
  10271. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10272. }
  10273. // Normalize the probabilities of the remaining words
  10274. llama_sample_softmax(ctx, candidates);
  10275. // Sample the next word X from the remaining words
  10276. llama_token X = llama_sample_token(ctx, candidates);
  10277. t_start_sample_us = ggml_time_us();
  10278. // Compute error as the difference between observed surprise and target surprise value
  10279. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  10280. return candidate.id == X;
  10281. }));
  10282. float observed_surprise = -log2f(candidates->data[X_idx].p);
  10283. float e = observed_surprise - tau;
  10284. // Update mu using the learning rate and error
  10285. *mu = *mu - eta * e;
  10286. if (ctx) {
  10287. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10288. }
  10289. return X;
  10290. }
  10291. llama_token llama_sample_token_greedy(struct llama_context * ctx, llama_token_data_array * candidates) {
  10292. const int64_t t_start_sample_us = ggml_time_us();
  10293. // Find max element
  10294. auto * max_iter = std::max_element(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  10295. return a.logit < b.logit;
  10296. });
  10297. llama_token result = max_iter->id;
  10298. if (ctx) {
  10299. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10300. ctx->n_sample++;
  10301. }
  10302. return result;
  10303. }
  10304. llama_token llama_sample_token(struct llama_context * ctx, llama_token_data_array * candidates) {
  10305. GGML_ASSERT(ctx);
  10306. const int64_t t_start_sample_us = ggml_time_us();
  10307. llama_sample_softmax(nullptr, candidates);
  10308. std::vector<float> probs;
  10309. probs.reserve(candidates->size);
  10310. for (size_t i = 0; i < candidates->size; ++i) {
  10311. probs.push_back(candidates->data[i].p);
  10312. }
  10313. std::discrete_distribution<> dist(probs.begin(), probs.end());
  10314. auto & rng = ctx->rng;
  10315. int idx = dist(rng);
  10316. llama_token result = candidates->data[idx].id;
  10317. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10318. ctx->n_sample++;
  10319. return result;
  10320. }
  10321. void llama_grammar_accept_token(struct llama_context * ctx, struct llama_grammar * grammar, llama_token token) {
  10322. const int64_t t_start_sample_us = ggml_time_us();
  10323. if (token == llama_token_eos(&ctx->model)) {
  10324. for (const auto & stack : grammar->stacks) {
  10325. if (stack.empty()) {
  10326. return;
  10327. }
  10328. }
  10329. GGML_ASSERT(false);
  10330. }
  10331. const std::string piece = llama_token_to_piece(ctx, token);
  10332. // Note terminating 0 in decoded string
  10333. const auto decoded = decode_utf8(piece, grammar->partial_utf8);
  10334. const auto & code_points = decoded.first;
  10335. for (auto it = code_points.begin(), end = code_points.end() - 1; it != end; ++it) {
  10336. grammar->stacks = llama_grammar_accept(grammar->rules, grammar->stacks, *it);
  10337. }
  10338. grammar->partial_utf8 = decoded.second;
  10339. GGML_ASSERT(!grammar->stacks.empty());
  10340. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10341. }
  10342. //
  10343. // Beam search
  10344. //
  10345. struct llama_beam {
  10346. std::vector<llama_token> tokens;
  10347. float p; // Cumulative beam probability (renormalized relative to all beams)
  10348. bool eob; // Initialize end-of-beam to false. Callback sets this to true.
  10349. // Sort beams by probability. In case of ties, prefer beams at eob.
  10350. bool operator<(const llama_beam & rhs) const {
  10351. return std::make_pair(p, eob) < std::make_pair(rhs.p, rhs.eob);
  10352. }
  10353. // Shift off first n tokens and discard them.
  10354. void shift_tokens(const size_t n) {
  10355. if (n) {
  10356. std::copy(tokens.begin() + n, tokens.end(), tokens.begin());
  10357. tokens.resize(tokens.size() - n);
  10358. }
  10359. }
  10360. llama_beam_view view() const { return {tokens.data(), tokens.size(), p, eob}; }
  10361. };
  10362. // A struct for calculating logit-related info.
  10363. struct llama_logit_info {
  10364. const float * const logits;
  10365. const int n_vocab;
  10366. const float max_l;
  10367. const float normalizer;
  10368. struct sum_exp {
  10369. float max_l;
  10370. float operator()(float sum, float l) const { return sum + std::exp(l - max_l); }
  10371. };
  10372. llama_logit_info(llama_context * ctx)
  10373. : logits(llama_get_logits(ctx))
  10374. , n_vocab(llama_n_vocab(llama_get_model(ctx)))
  10375. , max_l(*std::max_element(logits, logits + n_vocab))
  10376. , normalizer(1.0f / std::accumulate(logits, logits + n_vocab, 0.0f, sum_exp{max_l}))
  10377. { }
  10378. llama_token_data get_token_data(const llama_token token_id) const {
  10379. constexpr auto p = std::numeric_limits<float>::quiet_NaN(); // never used
  10380. return {token_id, logits[token_id], p};
  10381. }
  10382. // Return top k token_data by logit.
  10383. std::vector<llama_token_data> top_k(size_t k) {
  10384. std::vector<llama_token_data> min_heap; // min-heap by logit
  10385. const llama_token k_min = std::min(static_cast<llama_token>(k), n_vocab);
  10386. min_heap.reserve(k_min);
  10387. for (llama_token token_id = 0 ; token_id < k_min ; ++token_id) {
  10388. min_heap.push_back(get_token_data(token_id));
  10389. }
  10390. auto comp = [](const llama_token_data & a, const llama_token_data & b) { return a.logit > b.logit; };
  10391. std::make_heap(min_heap.begin(), min_heap.end(), comp);
  10392. for (llama_token token_id = k_min ; token_id < n_vocab ; ++token_id) {
  10393. if (min_heap.front().logit < logits[token_id]) {
  10394. std::pop_heap(min_heap.begin(), min_heap.end(), comp);
  10395. min_heap.back().id = token_id;
  10396. min_heap.back().logit = logits[token_id];
  10397. std::push_heap(min_heap.begin(), min_heap.end(), comp);
  10398. }
  10399. }
  10400. return min_heap;
  10401. }
  10402. float probability_from_logit(float logit) const {
  10403. return normalizer * std::exp(logit - max_l);
  10404. }
  10405. };
  10406. struct llama_beam_search_data {
  10407. llama_context * ctx;
  10408. size_t n_beams;
  10409. int n_past;
  10410. int n_predict;
  10411. std::vector<llama_beam> beams;
  10412. std::vector<llama_beam> next_beams;
  10413. // Re-calculated on each loop iteration
  10414. size_t common_prefix_length;
  10415. // Used to communicate to/from callback on beams state.
  10416. std::vector<llama_beam_view> beam_views;
  10417. llama_beam_search_data(llama_context * ctx, size_t n_beams, int n_past, int n_predict)
  10418. : ctx(ctx)
  10419. , n_beams(n_beams)
  10420. , n_past(n_past)
  10421. , n_predict(n_predict)
  10422. , beam_views(n_beams) {
  10423. beams.reserve(n_beams);
  10424. next_beams.reserve(n_beams);
  10425. }
  10426. // Collapse beams to a single beam given by index.
  10427. void collapse_beams(const size_t beam_idx) {
  10428. if (0u < beam_idx) {
  10429. std::swap(beams[0], beams[beam_idx]);
  10430. }
  10431. beams.resize(1);
  10432. }
  10433. // Min-heaps are used to efficiently collect the top-k elements (k=n_beams).
  10434. // The repetitive patterns below reflect the 2 stages of heaps:
  10435. // * Gather elements until the vector is full, then call std::make_heap() on it.
  10436. // * If the heap is full and a new element is found that should be included, pop the
  10437. // least element to the back(), replace it with the new, then push it into the heap.
  10438. void fill_next_beams_by_top_probabilities(llama_beam & beam) {
  10439. // Min-heaps use a greater-than comparator.
  10440. const auto comp = [](const llama_beam & a, const llama_beam & b) { return a.p > b.p; };
  10441. if (beam.eob) {
  10442. // beam is at end-of-sentence, so just copy it to next_beams if its probability is high enough.
  10443. if (next_beams.size() < n_beams) {
  10444. next_beams.push_back(std::move(beam));
  10445. if (next_beams.size() == n_beams) {
  10446. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  10447. }
  10448. } else if (next_beams.front().p < beam.p) {
  10449. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  10450. next_beams.back() = std::move(beam);
  10451. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  10452. }
  10453. } else {
  10454. // beam is not at end-of-sentence, so branch with next top_k tokens.
  10455. if (!beam.tokens.empty()) {
  10456. llama_decode(ctx, llama_batch_get_one(beam.tokens.data(), beam.tokens.size(), n_past, 0));
  10457. }
  10458. llama_logit_info logit_info(ctx);
  10459. std::vector<llama_token_data> next_tokens = logit_info.top_k(n_beams);
  10460. size_t i=0;
  10461. if (next_beams.size() < n_beams) {
  10462. for (; next_beams.size() < n_beams ; ++i) {
  10463. llama_beam next_beam = beam;
  10464. next_beam.tokens.push_back(next_tokens[i].id);
  10465. next_beam.p *= logit_info.probability_from_logit(next_tokens[i].logit);
  10466. next_beams.push_back(std::move(next_beam));
  10467. }
  10468. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  10469. } else {
  10470. for (; next_beams.front().p == 0.0f ; ++i) {
  10471. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  10472. next_beams.back() = beam;
  10473. next_beams.back().tokens.push_back(next_tokens[i].id);
  10474. next_beams.back().p *= logit_info.probability_from_logit(next_tokens[i].logit);
  10475. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  10476. }
  10477. }
  10478. for (; i < n_beams ; ++i) {
  10479. const float next_p = beam.p * logit_info.probability_from_logit(next_tokens[i].logit);
  10480. if (next_beams.front().p < next_p) {
  10481. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  10482. next_beams.back() = beam;
  10483. next_beams.back().tokens.push_back(next_tokens[i].id);
  10484. next_beams.back().p = next_p;
  10485. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  10486. }
  10487. }
  10488. }
  10489. }
  10490. // Find common_prefix_length based on beams.
  10491. // Requires beams is not empty.
  10492. size_t find_common_prefix_length() {
  10493. size_t common_prefix_length = beams[0].tokens.size();
  10494. for (size_t i = 1 ; i < beams.size() ; ++i) {
  10495. common_prefix_length = std::min(common_prefix_length, beams[i].tokens.size());
  10496. for (size_t j = 0 ; j < common_prefix_length ; ++j) {
  10497. if (beams[0].tokens[j] != beams[i].tokens[j]) {
  10498. common_prefix_length = j;
  10499. break;
  10500. }
  10501. }
  10502. }
  10503. return common_prefix_length;
  10504. }
  10505. // Construct beams_state to send back to caller via the callback function.
  10506. // Side effect: set common_prefix_length = find_common_prefix_length();
  10507. llama_beams_state get_beams_state(const bool last_call) {
  10508. for (size_t i = 0 ; i < beams.size() ; ++i) {
  10509. beam_views[i] = beams[i].view();
  10510. }
  10511. common_prefix_length = find_common_prefix_length();
  10512. return {beam_views.data(), beams.size(), common_prefix_length, last_call};
  10513. }
  10514. // Loop:
  10515. // * while i < n_predict, AND
  10516. // * any of the beams have not yet reached end-of-beam (eob), AND
  10517. // * the highest probability beam(s) (plural in case of ties) are not at end-of-sentence
  10518. // (since all other beam probabilities can only decrease)
  10519. void loop(const llama_beam_search_callback_fn_t callback, void * const callback_data) {
  10520. beams.push_back({{}, 1.0f, false}); // Start with one empty beam w/ probability = 1.0 and !eob.
  10521. const auto not_eob = [](const llama_beam & beam) { return !beam.eob; };
  10522. for (int i = 0 ; i < n_predict && std::any_of(beams.begin(),beams.end(),not_eob) &&
  10523. !beams[top_beam_index()].eob ; ++i) {
  10524. callback(callback_data, get_beams_state(false)); // Sets common_prefix_length
  10525. update_beams_from_beam_views(); // Update values (p,eob) that callback may have changed.
  10526. if (common_prefix_length) {
  10527. llama_decode(ctx, llama_batch_get_one(beams[0].tokens.data(), common_prefix_length, n_past, 0));
  10528. n_past += common_prefix_length;
  10529. }
  10530. // Zero-out next_beam probabilities to place them last in following min-heap.
  10531. std::for_each(next_beams.begin(), next_beams.end(), [](llama_beam & beam) { beam.p = 0.0f; });
  10532. for (llama_beam & beam : beams) {
  10533. beam.shift_tokens(common_prefix_length);
  10534. fill_next_beams_by_top_probabilities(beam);
  10535. }
  10536. // next_beams become the beams of next/final iteration. Swap them to re-use memory.
  10537. beams.swap(next_beams);
  10538. renormalize_beam_probabilities(beams);
  10539. }
  10540. collapse_beams(top_beam_index());
  10541. callback(callback_data, get_beams_state(true));
  10542. }
  10543. // As beams grow, the cumulative probabilities decrease.
  10544. // Renormalize them to avoid floating point underflow.
  10545. static void renormalize_beam_probabilities(std::vector<llama_beam> & beams) {
  10546. const auto sum_p = [](float sum, llama_beam & beam) { return sum + beam.p; };
  10547. const float inv_sum = 1.0f / std::accumulate(beams.begin(), beams.end(), 0.0f, sum_p);
  10548. std::for_each(beams.begin(), beams.end(), [=](llama_beam & beam) { beam.p *= inv_sum; });
  10549. }
  10550. // Assumes beams is non-empty. Uses llama_beam::operator<() for ordering.
  10551. size_t top_beam_index() {
  10552. return std::max_element(beams.begin(), beams.end()) - beams.begin();
  10553. }
  10554. // Copy (p,eob) for each beam which may have been changed by the callback.
  10555. void update_beams_from_beam_views() {
  10556. for (size_t i = 0 ; i < beams.size() ; ++i) {
  10557. beams[i].p = beam_views[i].p;
  10558. beams[i].eob = beam_views[i].eob;
  10559. }
  10560. }
  10561. };
  10562. void llama_beam_search(llama_context * ctx,
  10563. llama_beam_search_callback_fn_t callback, void * callback_data,
  10564. size_t n_beams, int n_past, int n_predict) {
  10565. assert(ctx);
  10566. const int64_t t_start_sample_us = ggml_time_us();
  10567. llama_beam_search_data beam_search_data(ctx, n_beams, n_past, n_predict);
  10568. beam_search_data.loop(callback, callback_data);
  10569. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10570. ctx->n_sample++;
  10571. }
  10572. //
  10573. // quantization
  10574. //
  10575. struct quantize_state_internal {
  10576. const llama_model & model;
  10577. const llama_model_quantize_params * params;
  10578. int n_attention_wv = 0;
  10579. int n_ffn_down = 0;
  10580. int n_ffn_gate = 0;
  10581. int n_ffn_up = 0;
  10582. int i_attention_wv = 0;
  10583. int i_ffn_down = 0;
  10584. int i_ffn_gate = 0;
  10585. int i_ffn_up = 0;
  10586. int n_k_quantized = 0;
  10587. int n_fallback = 0;
  10588. bool has_imatrix = false;
  10589. // used to figure out if a model shares tok_embd with the output weight
  10590. bool has_output = false;
  10591. quantize_state_internal(const llama_model & model, const llama_model_quantize_params * params)
  10592. : model(model)
  10593. , params(params)
  10594. {}
  10595. };
  10596. static void llama_tensor_dequantize_internal(
  10597. struct ggml_tensor * tensor, std::vector<no_init<float>> & output, std::vector<std::thread> & workers,
  10598. const size_t nelements, const int nthread
  10599. ) {
  10600. if (output.size() < nelements) {
  10601. output.resize(nelements);
  10602. }
  10603. float * f32_output = (float *) output.data();
  10604. ggml_type_traits_t qtype;
  10605. if (ggml_is_quantized(tensor->type)) {
  10606. qtype = ggml_internal_get_type_traits(tensor->type);
  10607. if (qtype.to_float == NULL) {
  10608. throw std::runtime_error(format("type %s unsupported for integer quantization: no dequantization available", ggml_type_name(tensor->type)));
  10609. }
  10610. } else if (tensor->type != GGML_TYPE_F16) {
  10611. throw std::runtime_error(format("cannot dequantize/convert tensor type %s", ggml_type_name(tensor->type)));
  10612. }
  10613. if (nthread < 2) {
  10614. if (tensor->type == GGML_TYPE_F16) {
  10615. ggml_fp16_to_fp32_row((ggml_fp16_t *)tensor->data, f32_output, nelements);
  10616. } else if (ggml_is_quantized(tensor->type)) {
  10617. qtype.to_float(tensor->data, f32_output, nelements);
  10618. } else {
  10619. GGML_ASSERT(false); // unreachable
  10620. }
  10621. return;
  10622. }
  10623. size_t block_size = tensor->type == GGML_TYPE_F16 ? 1 : (size_t)ggml_blck_size(tensor->type);
  10624. size_t block_size_bytes = ggml_type_size(tensor->type);
  10625. GGML_ASSERT(nelements % block_size == 0);
  10626. size_t nblocks = nelements / block_size;
  10627. size_t blocks_per_thread = nblocks / nthread;
  10628. size_t spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count
  10629. size_t in_buff_offs = 0;
  10630. size_t out_buff_offs = 0;
  10631. for (int tnum = 0; tnum < nthread; tnum++) {
  10632. size_t thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread
  10633. size_t thr_elems = thr_blocks * block_size; // number of elements for this thread
  10634. size_t thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread
  10635. auto compute = [qtype] (ggml_type typ, uint8_t * inbuf, float * outbuf, int nels) {
  10636. if (typ == GGML_TYPE_F16) {
  10637. ggml_fp16_to_fp32_row((ggml_fp16_t *)inbuf, outbuf, nels);
  10638. } else {
  10639. qtype.to_float(inbuf, outbuf, nels);
  10640. }
  10641. };
  10642. workers.emplace_back(compute, tensor->type, (uint8_t *) tensor->data + in_buff_offs, f32_output + out_buff_offs, thr_elems);
  10643. in_buff_offs += thr_block_bytes;
  10644. out_buff_offs += thr_elems;
  10645. }
  10646. for (auto & w : workers) { w.join(); }
  10647. workers.clear();
  10648. }
  10649. static ggml_type llama_tensor_get_type(quantize_state_internal & qs, ggml_type new_type, const ggml_tensor * tensor, llama_ftype ftype) {
  10650. const std::string name = ggml_get_name(tensor);
  10651. // TODO: avoid hardcoded tensor names - use the TN_* constants
  10652. const llm_arch arch = qs.model.arch;
  10653. const auto tn = LLM_TN(arch);
  10654. auto use_more_bits = [](int i_layer, int num_layers) -> bool {
  10655. return i_layer < num_layers/8 || i_layer >= 7*num_layers/8 || (i_layer - num_layers/8)%3 == 2;
  10656. };
  10657. const int n_expert = std::max(1, (int)qs.model.hparams.n_expert);
  10658. auto layer_info = [n_expert] (int i_layer, int n_layer, const char * name) {
  10659. if (n_expert > 1) {
  10660. // Believe it or not, "experts" in the FFN of Mixtral-8x7B are not consecutive, but iccasionally randomly
  10661. // sprinkled in the model. Hence, simply dividing i_ffn_down by n_expert does not work
  10662. // for getting the current layer as I initially thought, and we need to resort to parsing the
  10663. // tensor name.
  10664. n_layer /= n_expert;
  10665. if (sscanf(name, "blk.%d.", &i_layer) != 1) {
  10666. throw std::runtime_error(format("Failed to determine layer for tensor %s", name));
  10667. }
  10668. if (i_layer < 0 || i_layer >= n_layer) {
  10669. throw std::runtime_error(format("Bad layer %d for tensor %s. Must be in [0, %d)", i_layer, name, n_layer));
  10670. }
  10671. }
  10672. return std::make_pair(i_layer, n_layer);
  10673. };
  10674. // for arches that share the same tensor between the token embeddings and the output, we quantize the token embeddings
  10675. // with the quantization of the output tensor
  10676. if (name == tn(LLM_TENSOR_OUTPUT, "weight") || (!qs.has_output && name == tn(LLM_TENSOR_TOKEN_EMBD, "weight"))) {
  10677. if (qs.params->output_tensor_type < GGML_TYPE_COUNT) {
  10678. new_type = qs.params->output_tensor_type;
  10679. } else {
  10680. int nx = tensor->ne[0];
  10681. if (arch == LLM_ARCH_FALCON || nx % QK_K != 0) {
  10682. new_type = GGML_TYPE_Q8_0;
  10683. }
  10684. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  10685. ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ||
  10686. ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  10687. new_type = GGML_TYPE_Q5_K;
  10688. }
  10689. else if (new_type != GGML_TYPE_Q8_0) {
  10690. new_type = GGML_TYPE_Q6_K;
  10691. }
  10692. }
  10693. } else if (name == "token_embd.weight") {
  10694. if (qs.params->token_embedding_type < GGML_TYPE_COUNT) {
  10695. new_type = qs.params->token_embedding_type;
  10696. } else {
  10697. if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS ||
  10698. ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  10699. new_type = GGML_TYPE_Q2_K;
  10700. }
  10701. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) {
  10702. new_type = GGML_TYPE_IQ3_S;
  10703. }
  10704. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  10705. new_type = GGML_TYPE_IQ3_S;
  10706. }
  10707. }
  10708. } else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S ||
  10709. ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  10710. if (name.find("attn_v.weight") != std::string::npos) {
  10711. if (qs.model.hparams.n_gqa() >= 4 || qs.model.hparams.n_expert >= 4) new_type = GGML_TYPE_Q4_K;
  10712. else new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  10713. ++qs.i_attention_wv;
  10714. }
  10715. else if (qs.model.hparams.n_expert == 8 && name.find("attn_k.weight") != std::string::npos) {
  10716. new_type = GGML_TYPE_Q4_K;
  10717. }
  10718. else if (name.find("ffn_down") != std::string::npos) {
  10719. if (qs.i_ffn_down < qs.n_ffn_down/8) {
  10720. new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  10721. }
  10722. ++qs.i_ffn_down;
  10723. }
  10724. else if (name.find("attn_output.weight") != std::string::npos) {
  10725. if (qs.model.hparams.n_expert == 8) {
  10726. new_type = GGML_TYPE_Q5_K;
  10727. } else {
  10728. if (ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) new_type = GGML_TYPE_IQ2_XXS;
  10729. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) new_type = GGML_TYPE_IQ3_S;
  10730. }
  10731. }
  10732. } else if (name.find("attn_v.weight") != std::string::npos) {
  10733. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) {
  10734. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  10735. }
  10736. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && qs.model.hparams.n_gqa() >= 4) {
  10737. new_type = GGML_TYPE_Q4_K;
  10738. }
  10739. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  10740. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : !qs.has_imatrix ? GGML_TYPE_IQ3_S : GGML_TYPE_IQ3_XXS;
  10741. }
  10742. else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S) && qs.model.hparams.n_gqa() >= 4) {
  10743. new_type = GGML_TYPE_Q4_K;
  10744. }
  10745. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  10746. new_type = GGML_TYPE_Q4_K;
  10747. }
  10748. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  10749. new_type = qs.i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  10750. }
  10751. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  10752. else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && qs.model.hparams.n_gqa() >= 4) {
  10753. new_type = GGML_TYPE_Q5_K;
  10754. }
  10755. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
  10756. use_more_bits(qs.i_attention_wv, qs.n_attention_wv)) new_type = GGML_TYPE_Q6_K;
  10757. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && qs.i_attention_wv < 4) new_type = GGML_TYPE_Q5_K;
  10758. else if (QK_K == 64 && (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S) &&
  10759. (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;
  10760. if (qs.model.type == MODEL_70B) {
  10761. // In the 70B model we have 8 heads sharing the same attn_v weights. As a result, the attn_v.weight tensor is
  10762. // 8x smaller compared to attn_q.weight. Hence, we can get a nice boost in quantization accuracy with
  10763. // nearly negligible increase in model size by quantizing this tensor with more bits:
  10764. if (new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K) new_type = GGML_TYPE_Q5_K;
  10765. }
  10766. if (qs.model.hparams.n_expert == 8) {
  10767. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  10768. // TODO: explore better strategies
  10769. new_type = GGML_TYPE_Q8_0;
  10770. }
  10771. ++qs.i_attention_wv;
  10772. } else if (name.find("attn_k.weight") != std::string::npos) {
  10773. if (qs.model.hparams.n_expert == 8) {
  10774. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  10775. // TODO: explore better strategies
  10776. new_type = GGML_TYPE_Q8_0;
  10777. }
  10778. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  10779. new_type = GGML_TYPE_IQ3_XXS;
  10780. }
  10781. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  10782. new_type = GGML_TYPE_IQ2_S;
  10783. }
  10784. } else if (name.find("attn_q.weight") != std::string::npos) {
  10785. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  10786. new_type = GGML_TYPE_IQ3_XXS;
  10787. }
  10788. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  10789. new_type = GGML_TYPE_IQ2_S;
  10790. }
  10791. } else if (name.find("ffn_down") != std::string::npos) {
  10792. auto info = layer_info(qs.i_ffn_down, qs.n_ffn_down, name.c_str());
  10793. int i_layer = info.first, n_layer = info.second;
  10794. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  10795. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S) {
  10796. if (i_layer < n_layer/8) new_type = GGML_TYPE_Q4_K;
  10797. }
  10798. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS && !qs.has_imatrix) {
  10799. new_type = i_layer < n_layer/8 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  10800. }
  10801. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  10802. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q5_K
  10803. : arch != LLM_ARCH_FALCON || use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q4_K
  10804. : GGML_TYPE_Q3_K;
  10805. }
  10806. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M && (i_layer < n_layer/8 ||
  10807. (qs.model.hparams.n_expert == 8 && use_more_bits(i_layer, n_layer)))) {
  10808. new_type = GGML_TYPE_Q4_K;
  10809. }
  10810. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) {
  10811. new_type = arch == LLM_ARCH_FALCON ? GGML_TYPE_Q4_K : GGML_TYPE_Q5_K;
  10812. }
  10813. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  10814. if (arch == LLM_ARCH_FALCON) {
  10815. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q6_K :
  10816. use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  10817. } else {
  10818. if (use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  10819. }
  10820. }
  10821. else if (i_layer < n_layer/8 && (ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && !qs.has_imatrix) {
  10822. new_type = GGML_TYPE_Q5_K;
  10823. }
  10824. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M && use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  10825. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && arch != LLM_ARCH_FALCON && i_layer < n_layer/8) {
  10826. new_type = GGML_TYPE_Q5_K;
  10827. }
  10828. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_0 || ftype == LLAMA_FTYPE_MOSTLY_Q5_0)
  10829. && qs.has_imatrix && i_layer < n_layer/8) {
  10830. // Guard against craziness in the first few ffn_down layers that can happen even with imatrix for Q4_0/Q5_0.
  10831. // We only do it when an imatrix is provided because a) we want to make sure that one can always get the
  10832. // same quantization as before imatrix stuff, and b) Q4_1/Q5_1 do go crazy on ffn_down without an imatrix.
  10833. new_type = ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ? GGML_TYPE_Q4_1 : GGML_TYPE_Q5_1;
  10834. }
  10835. ++qs.i_ffn_down;
  10836. } else if (name.find("attn_output.weight") != std::string::npos) {
  10837. if (arch != LLM_ARCH_FALCON) {
  10838. if (qs.model.hparams.n_expert == 8) {
  10839. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  10840. ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL ||
  10841. ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S ||
  10842. ftype == LLAMA_FTYPE_MOSTLY_IQ3_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) {
  10843. new_type = GGML_TYPE_Q5_K;
  10844. }
  10845. } else {
  10846. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K ) new_type = GGML_TYPE_Q3_K;
  10847. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) new_type = GGML_TYPE_IQ3_S;
  10848. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M ) new_type = GGML_TYPE_Q4_K;
  10849. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L ) new_type = GGML_TYPE_Q5_K;
  10850. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M ) new_type = GGML_TYPE_Q4_K;
  10851. }
  10852. } else {
  10853. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  10854. }
  10855. }
  10856. else if (name.find("attn_qkv.weight") != std::string::npos) {
  10857. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L || ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  10858. new_type = GGML_TYPE_Q4_K;
  10859. }
  10860. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) new_type = GGML_TYPE_Q5_K;
  10861. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) new_type = GGML_TYPE_Q6_K;
  10862. }
  10863. else if (name.find("ffn_gate") != std::string::npos) {
  10864. auto info = layer_info(qs.i_ffn_gate, qs.n_ffn_gate, name.c_str());
  10865. int i_layer = info.first, n_layer = info.second;
  10866. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  10867. new_type = GGML_TYPE_IQ3_XXS;
  10868. }
  10869. ++qs.i_ffn_gate;
  10870. }
  10871. else if (name.find("ffn_up") != std::string::npos) {
  10872. auto info = layer_info(qs.i_ffn_up, qs.n_ffn_up, name.c_str());
  10873. int i_layer = info.first, n_layer = info.second;
  10874. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  10875. new_type = GGML_TYPE_IQ3_XXS;
  10876. }
  10877. ++qs.i_ffn_up;
  10878. }
  10879. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  10880. //}
  10881. // IK: let's remove this, else Q2_K is almost the same as Q3_K_S
  10882. //else if (name.find("ffn_gate") != std::string::npos || name.find("ffn_up") != std::string::npos) {
  10883. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  10884. //}
  10885. // This can be used to reduce the size of the Q5_K_S model.
  10886. // The associated PPL increase is fully in line with the size reduction
  10887. //else {
  10888. // if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_S) new_type = GGML_TYPE_Q4_K;
  10889. //}
  10890. bool convert_incompatible_tensor = false;
  10891. if (new_type == GGML_TYPE_Q2_K || new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K ||
  10892. new_type == GGML_TYPE_Q5_K || new_type == GGML_TYPE_Q6_K || new_type == GGML_TYPE_IQ4_XS ||
  10893. new_type == GGML_TYPE_IQ2_XS || new_type == GGML_TYPE_IQ2_XXS || new_type == GGML_TYPE_IQ2_S ||
  10894. new_type == GGML_TYPE_IQ3_XXS || new_type == GGML_TYPE_IQ1_S || new_type == GGML_TYPE_IQ3_S ||
  10895. new_type == GGML_TYPE_IQ1_M) {
  10896. int nx = tensor->ne[0];
  10897. int ny = tensor->ne[1];
  10898. if (nx % QK_K != 0) {
  10899. 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));
  10900. convert_incompatible_tensor = true;
  10901. } else {
  10902. ++qs.n_k_quantized;
  10903. }
  10904. }
  10905. if (convert_incompatible_tensor) {
  10906. switch (new_type) {
  10907. case GGML_TYPE_IQ2_XXS:
  10908. case GGML_TYPE_IQ2_XS:
  10909. case GGML_TYPE_IQ2_S:
  10910. case GGML_TYPE_IQ3_XXS:
  10911. case GGML_TYPE_IQ3_S:
  10912. case GGML_TYPE_IQ1_S:
  10913. case GGML_TYPE_IQ1_M:
  10914. case GGML_TYPE_Q2_K:
  10915. case GGML_TYPE_Q3_K:
  10916. case GGML_TYPE_IQ4_XS: new_type = GGML_TYPE_IQ4_NL; break;
  10917. case GGML_TYPE_Q4_K: new_type = GGML_TYPE_Q5_0; break;
  10918. case GGML_TYPE_Q5_K: new_type = GGML_TYPE_Q5_1; break;
  10919. case GGML_TYPE_Q6_K: new_type = GGML_TYPE_Q8_0; break;
  10920. default: throw std::runtime_error("\nUnsupported tensor size encountered\n");
  10921. }
  10922. LLAMA_LOG_WARN(" - using fallback quantization %s\n", ggml_type_name(new_type));
  10923. ++qs.n_fallback;
  10924. }
  10925. return new_type;
  10926. }
  10927. static size_t llama_tensor_quantize_internal(enum ggml_type new_type, const float * f32_data, void * new_data, const int chunk_size, int nrows, int n_per_row, const float * imatrix, std::vector<std::thread> & workers, const int nthread) {
  10928. std::mutex mutex;
  10929. int counter = 0;
  10930. size_t new_size = 0;
  10931. if (nthread < 2) {
  10932. // single-thread
  10933. return ggml_quantize_chunk(new_type, f32_data, new_data, 0, nrows, n_per_row, imatrix);
  10934. }
  10935. auto compute = [&mutex, &counter, &new_size, new_type, f32_data, new_data, chunk_size,
  10936. nrows, n_per_row, imatrix]() {
  10937. const int nrows_per_chunk = chunk_size / n_per_row;
  10938. size_t local_size = 0;
  10939. while (true) {
  10940. std::unique_lock<std::mutex> lock(mutex);
  10941. int first_row = counter; counter += nrows_per_chunk;
  10942. if (first_row >= nrows) {
  10943. if (local_size > 0) {
  10944. new_size += local_size;
  10945. }
  10946. break;
  10947. }
  10948. lock.unlock();
  10949. const int this_nrow = std::min(nrows - first_row, nrows_per_chunk);
  10950. local_size += ggml_quantize_chunk(new_type, f32_data, new_data, first_row * n_per_row, this_nrow, n_per_row, imatrix);
  10951. }
  10952. };
  10953. for (int it = 0; it < nthread - 1; ++it) {
  10954. workers.emplace_back(compute);
  10955. }
  10956. compute();
  10957. for (auto & w : workers) { w.join(); }
  10958. workers.clear();
  10959. return new_size;
  10960. }
  10961. static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) {
  10962. ggml_type default_type;
  10963. llama_ftype ftype = params->ftype;
  10964. switch (params->ftype) {
  10965. case LLAMA_FTYPE_MOSTLY_Q4_0: default_type = GGML_TYPE_Q4_0; break;
  10966. case LLAMA_FTYPE_MOSTLY_Q4_1: default_type = GGML_TYPE_Q4_1; break;
  10967. case LLAMA_FTYPE_MOSTLY_Q5_0: default_type = GGML_TYPE_Q5_0; break;
  10968. case LLAMA_FTYPE_MOSTLY_Q5_1: default_type = GGML_TYPE_Q5_1; break;
  10969. case LLAMA_FTYPE_MOSTLY_Q8_0: default_type = GGML_TYPE_Q8_0; break;
  10970. case LLAMA_FTYPE_MOSTLY_F16: default_type = GGML_TYPE_F16; break;
  10971. case LLAMA_FTYPE_ALL_F32: default_type = GGML_TYPE_F32; break;
  10972. // K-quants
  10973. case LLAMA_FTYPE_MOSTLY_Q2_K_S:
  10974. case LLAMA_FTYPE_MOSTLY_Q2_K: default_type = GGML_TYPE_Q2_K; break;
  10975. case LLAMA_FTYPE_MOSTLY_IQ3_XS: default_type = GGML_TYPE_IQ3_S; break;
  10976. case LLAMA_FTYPE_MOSTLY_Q3_K_S:
  10977. case LLAMA_FTYPE_MOSTLY_Q3_K_M:
  10978. case LLAMA_FTYPE_MOSTLY_Q3_K_L: default_type = GGML_TYPE_Q3_K; break;
  10979. case LLAMA_FTYPE_MOSTLY_Q4_K_S:
  10980. case LLAMA_FTYPE_MOSTLY_Q4_K_M: default_type = GGML_TYPE_Q4_K; break;
  10981. case LLAMA_FTYPE_MOSTLY_Q5_K_S:
  10982. case LLAMA_FTYPE_MOSTLY_Q5_K_M: default_type = GGML_TYPE_Q5_K; break;
  10983. case LLAMA_FTYPE_MOSTLY_Q6_K: default_type = GGML_TYPE_Q6_K; break;
  10984. case LLAMA_FTYPE_MOSTLY_IQ2_XXS: default_type = GGML_TYPE_IQ2_XXS; break;
  10985. case LLAMA_FTYPE_MOSTLY_IQ2_XS: default_type = GGML_TYPE_IQ2_XS; break;
  10986. case LLAMA_FTYPE_MOSTLY_IQ2_S: default_type = GGML_TYPE_IQ2_XS; break;
  10987. case LLAMA_FTYPE_MOSTLY_IQ2_M: default_type = GGML_TYPE_IQ2_S; break;
  10988. case LLAMA_FTYPE_MOSTLY_IQ3_XXS: default_type = GGML_TYPE_IQ3_XXS; break;
  10989. case LLAMA_FTYPE_MOSTLY_IQ1_S: default_type = GGML_TYPE_IQ1_S; break;
  10990. case LLAMA_FTYPE_MOSTLY_IQ1_M: default_type = GGML_TYPE_IQ1_M; break;
  10991. case LLAMA_FTYPE_MOSTLY_IQ4_NL: default_type = GGML_TYPE_IQ4_NL; break;
  10992. case LLAMA_FTYPE_MOSTLY_IQ4_XS: default_type = GGML_TYPE_IQ4_XS; break;
  10993. case LLAMA_FTYPE_MOSTLY_IQ3_S: default_type = GGML_TYPE_IQ3_S; break;
  10994. case LLAMA_FTYPE_MOSTLY_IQ3_M: default_type = GGML_TYPE_IQ3_S; break;
  10995. default: throw std::runtime_error(format("invalid output file type %d\n", ftype));
  10996. }
  10997. int nthread = params->nthread;
  10998. if (nthread <= 0) {
  10999. nthread = std::thread::hardware_concurrency();
  11000. }
  11001. // mmap consistently increases speed Linux, and also increases speed on Windows with
  11002. // hot cache. It may cause a slowdown on macOS, possibly related to free memory.
  11003. #if defined(__linux__) || defined(_WIN32)
  11004. constexpr bool use_mmap = true;
  11005. #else
  11006. constexpr bool use_mmap = false;
  11007. #endif
  11008. llama_model_kv_override * kv_overrides = nullptr;
  11009. if (params->kv_overrides) {
  11010. auto v = (std::vector<llama_model_kv_override>*)params->kv_overrides;
  11011. kv_overrides = v->data();
  11012. }
  11013. llama_model_loader ml(fname_inp, use_mmap, kv_overrides);
  11014. ml.init_mappings(false); // no prefetching?
  11015. llama_model model;
  11016. llm_load_arch(ml, model);
  11017. llm_load_hparams(ml, model);
  11018. struct quantize_state_internal qs(model, params);
  11019. if (params->only_copy) {
  11020. ftype = model.ftype;
  11021. }
  11022. const std::unordered_map<std::string, std::vector<float>> * imatrix_data = nullptr;
  11023. if (params->imatrix) {
  11024. imatrix_data = static_cast<const std::unordered_map<std::string, std::vector<float>>*>(params->imatrix);
  11025. if (imatrix_data) {
  11026. LLAMA_LOG_INFO("================================ Have weights data with %d entries\n",int(imatrix_data->size()));
  11027. qs.has_imatrix = true;
  11028. }
  11029. }
  11030. const size_t align = GGUF_DEFAULT_ALIGNMENT;
  11031. struct gguf_context * ctx_out = gguf_init_empty();
  11032. // copy the KV pairs from the input file
  11033. gguf_set_kv (ctx_out, ml.meta);
  11034. gguf_set_val_u32(ctx_out, "general.quantization_version", GGML_QNT_VERSION);
  11035. gguf_set_val_u32(ctx_out, "general.file_type", ftype);
  11036. if (params->kv_overrides) {
  11037. const std::vector<llama_model_kv_override> & overrides = *(const std::vector<llama_model_kv_override> *)params->kv_overrides;
  11038. for (auto & o : overrides) {
  11039. if (o.key[0] == 0) break;
  11040. if (o.tag == LLAMA_KV_OVERRIDE_TYPE_FLOAT) {
  11041. gguf_set_val_f32(ctx_out, o.key, o.float_value);
  11042. } else if (o.tag == LLAMA_KV_OVERRIDE_TYPE_INT) {
  11043. gguf_set_val_i32(ctx_out, o.key, o.int_value);
  11044. } else if (o.tag == LLAMA_KV_OVERRIDE_TYPE_BOOL) {
  11045. gguf_set_val_bool(ctx_out, o.key, o.bool_value);
  11046. } else {
  11047. LLAMA_LOG_WARN("%s: unknown KV override type for key %s\n", __func__, o.key);
  11048. }
  11049. }
  11050. }
  11051. for (int i = 0; i < ml.n_tensors; ++i) {
  11052. const struct ggml_tensor * meta = ml.get_tensor_meta(i);
  11053. const std::string name = ggml_get_name(meta);
  11054. // TODO: avoid hardcoded tensor names - use the TN_* constants
  11055. if (name.find("attn_v.weight") != std::string::npos || name.find("attn_qkv.weight") != std::string::npos) {
  11056. ++qs.n_attention_wv;
  11057. } else if (name.find("ffn_down") != std::string::npos) {
  11058. ++qs.n_ffn_down;
  11059. } else if (name.find("ffn_gate") != std::string::npos) {
  11060. ++qs.n_ffn_gate;
  11061. } else if (name.find("ffn_up") != std::string::npos) {
  11062. ++qs.n_ffn_up;
  11063. } else if (name == LLM_TN(model.arch)(LLM_TENSOR_OUTPUT, "weight")) {
  11064. qs.has_output = true;
  11065. }
  11066. }
  11067. if (qs.n_attention_wv != qs.n_ffn_down || (uint32_t) qs.n_attention_wv != model.hparams.n_layer) {
  11068. LLAMA_LOG_WARN("%s ============ Strange model: n_attention_wv = %d, n_ffn_down = %d, hparams.n_layer = %d\n",
  11069. __func__, qs.n_attention_wv, qs.n_ffn_down, model.hparams.n_layer);
  11070. }
  11071. size_t total_size_org = 0;
  11072. size_t total_size_new = 0;
  11073. std::vector<std::thread> workers;
  11074. workers.reserve(nthread);
  11075. int idx = 0;
  11076. std::vector<no_init<uint8_t>> read_data;
  11077. std::vector<no_init<uint8_t>> work;
  11078. std::vector<no_init<float>> f32_conv_buf;
  11079. // populate the original tensors so we get an initial meta data
  11080. for (int i = 0; i < ml.n_tensors; ++i) {
  11081. const struct ggml_tensor * meta = ml.get_tensor_meta(i);
  11082. gguf_add_tensor(ctx_out, meta);
  11083. }
  11084. std::ofstream fout(fname_out, std::ios::binary);
  11085. fout.exceptions(std::ofstream::failbit); // fail fast on write errors
  11086. const size_t meta_size = gguf_get_meta_size(ctx_out);
  11087. LLAMA_LOG_INFO("%s: meta size = %zu bytes\n", __func__, meta_size);
  11088. // placeholder for the meta data
  11089. ::zeros(fout, meta_size);
  11090. for (int i = 0; i < ml.n_tensors; ++i) {
  11091. struct ggml_tensor * tensor = ml.get_tensor_meta(i);
  11092. const std::string name = ggml_get_name(tensor);
  11093. if (!ml.use_mmap) {
  11094. if (read_data.size() < ggml_nbytes(tensor)) {
  11095. read_data.resize(ggml_nbytes(tensor));
  11096. }
  11097. tensor->data = read_data.data();
  11098. }
  11099. ml.load_data_for(tensor);
  11100. LLAMA_LOG_INFO("[%4d/%4d] %36s - [%s], type = %6s, ",
  11101. ++idx, ml.n_tensors,
  11102. ggml_get_name(tensor),
  11103. llama_format_tensor_shape(tensor).c_str(),
  11104. ggml_type_name(tensor->type));
  11105. // This used to be a regex, but <regex> has an extreme cost to compile times.
  11106. bool quantize = name.rfind("weight") == name.size() - 6; // ends with 'weight'?
  11107. // quantize only 2D tensors
  11108. quantize &= (ggml_n_dims(tensor) == 2);
  11109. quantize &= params->quantize_output_tensor || name != "output.weight";
  11110. quantize &= !params->only_copy;
  11111. // do not quantize expert gating tensors
  11112. // NOTE: can't use LLM_TN here because the layer number is not known
  11113. quantize &= name.find("ffn_gate_inp.weight") == std::string::npos;
  11114. // do not quantize positional embeddings and token types (BERT)
  11115. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_POS_EMBD, "weight");
  11116. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_TOKEN_TYPES, "weight");
  11117. // do not quantize Mamba's small yet 2D weights
  11118. // NOTE: can't use LLM_TN here because the layer number is not known
  11119. quantize &= name.find("ssm_conv1d.weight") == std::string::npos;
  11120. quantize &= name.find("ssm_x.weight") == std::string::npos;
  11121. quantize &= name.find("ssm_dt.weight") == std::string::npos;
  11122. enum ggml_type new_type;
  11123. void * new_data;
  11124. size_t new_size;
  11125. if (quantize) {
  11126. new_type = default_type;
  11127. // get more optimal quantization type based on the tensor shape, layer, etc.
  11128. if (!params->pure && ggml_is_quantized(default_type)) {
  11129. new_type = llama_tensor_get_type(qs, new_type, tensor, ftype);
  11130. }
  11131. else if (params->token_embedding_type < GGML_TYPE_COUNT && strcmp(tensor->name, "token_embd.weight") == 0) {
  11132. new_type = params->token_embedding_type;
  11133. }
  11134. else if (params->output_tensor_type < GGML_TYPE_COUNT && strcmp(tensor->name, "output.weight") == 0) {
  11135. new_type = params->output_tensor_type;
  11136. }
  11137. // If we've decided to quantize to the same type the tensor is already
  11138. // in then there's nothing to do.
  11139. quantize = tensor->type != new_type;
  11140. }
  11141. if (!quantize) {
  11142. new_type = tensor->type;
  11143. new_data = tensor->data;
  11144. new_size = ggml_nbytes(tensor);
  11145. LLAMA_LOG_INFO("size = %8.3f MB\n", ggml_nbytes(tensor)/1024.0/1024.0);
  11146. } else {
  11147. const size_t nelements = ggml_nelements(tensor);
  11148. const float * imatrix = nullptr;
  11149. if (imatrix_data) {
  11150. auto it = imatrix_data->find(tensor->name);
  11151. if (it == imatrix_data->end()) {
  11152. LLAMA_LOG_INFO("\n====== %s: did not find weights for %s\n", __func__, tensor->name);
  11153. } else {
  11154. if (it->second.size() == (size_t)tensor->ne[0]) {
  11155. imatrix = it->second.data();
  11156. } else {
  11157. LLAMA_LOG_INFO("\n====== %s: imatrix size %d is different from tensor size %d for %s\n", __func__,
  11158. int(it->second.size()), int(tensor->ne[0]), tensor->name);
  11159. }
  11160. }
  11161. }
  11162. if ((new_type == GGML_TYPE_IQ2_XXS ||
  11163. new_type == GGML_TYPE_IQ2_XS ||
  11164. new_type == GGML_TYPE_IQ2_S ||
  11165. new_type == GGML_TYPE_IQ1_S ||
  11166. (new_type == GGML_TYPE_IQ1_M && strcmp(tensor->name, "token_embd.weight") && strcmp(tensor->name, "output.weight")) ||
  11167. (new_type == GGML_TYPE_Q2_K && params->ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && strcmp(tensor->name, "token_embd.weight") != 0)) && !imatrix) {
  11168. LLAMA_LOG_ERROR("\n\n============================================================\n");
  11169. LLAMA_LOG_ERROR("Missing importance matrix for tensor %s in a very low-bit quantization\n", tensor->name);
  11170. LLAMA_LOG_ERROR("The result will be garbage, so bailing out\n");
  11171. LLAMA_LOG_ERROR("============================================================\n\n");
  11172. throw std::runtime_error(format("Missing importance matrix for tensor %s in a very low-bit quantization", tensor->name));
  11173. }
  11174. float * f32_data;
  11175. if (tensor->type == GGML_TYPE_F32) {
  11176. f32_data = (float *) tensor->data;
  11177. } else if (ggml_is_quantized(tensor->type) && !params->allow_requantize) {
  11178. throw std::runtime_error(format("requantizing from type %s is disabled", ggml_type_name(tensor->type)));
  11179. } else {
  11180. llama_tensor_dequantize_internal(tensor, f32_conv_buf, workers, nelements, nthread);
  11181. f32_data = (float *) f32_conv_buf.data();
  11182. }
  11183. LLAMA_LOG_INFO("converting to %s .. ", ggml_type_name(new_type));
  11184. fflush(stdout);
  11185. if (work.size() < nelements * 4) {
  11186. work.resize(nelements * 4); // upper bound on size
  11187. }
  11188. new_data = work.data();
  11189. const int n_per_row = tensor->ne[0];
  11190. const int nrows = nelements / n_per_row;
  11191. static const int min_chunk_size = 32 * 512;
  11192. const int chunk_size = n_per_row >= min_chunk_size ? n_per_row : n_per_row * ((min_chunk_size + n_per_row - 1)/n_per_row);
  11193. const int nchunk = (nelements + chunk_size - 1)/chunk_size;
  11194. const int nthread_use = nthread > 1 ? std::max(1, std::min(nthread, nchunk)) : 1;
  11195. new_size = llama_tensor_quantize_internal(new_type, f32_data, new_data, chunk_size, nrows, n_per_row, imatrix, workers, nthread_use);
  11196. LLAMA_LOG_INFO("size = %8.2f MiB -> %8.2f MiB\n", ggml_nbytes(tensor)/1024.0/1024.0, new_size/1024.0/1024.0);
  11197. }
  11198. total_size_org += ggml_nbytes(tensor);
  11199. total_size_new += new_size;
  11200. // update the gguf meta data as we go
  11201. gguf_set_tensor_type(ctx_out, name.c_str(), new_type);
  11202. gguf_set_tensor_data(ctx_out, name.c_str(), new_data, new_size);
  11203. // write tensor data + padding
  11204. fout.write((const char *) new_data, new_size);
  11205. zeros(fout, GGML_PAD(new_size, align) - new_size);
  11206. }
  11207. // go back to beginning of file and write the updated meta data
  11208. {
  11209. fout.seekp(0);
  11210. std::vector<uint8_t> data(gguf_get_meta_size(ctx_out));
  11211. gguf_get_meta_data(ctx_out, data.data());
  11212. fout.write((const char *) data.data(), data.size());
  11213. }
  11214. fout.close();
  11215. gguf_free(ctx_out);
  11216. LLAMA_LOG_INFO("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  11217. LLAMA_LOG_INFO("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  11218. if (qs.n_fallback > 0) {
  11219. LLAMA_LOG_WARN("%s: WARNING: %d of %d tensor(s) required fallback quantization\n",
  11220. __func__, qs.n_fallback, qs.n_k_quantized + qs.n_fallback);
  11221. }
  11222. }
  11223. static int llama_apply_lora_from_file_internal(
  11224. const struct llama_model & model, const char * path_lora, float scale, const char * path_base_model, int n_threads
  11225. ) {
  11226. LLAMA_LOG_INFO("%s: applying lora adapter from '%s' - please wait ...\n", __func__, path_lora);
  11227. const int64_t t_start_lora_us = ggml_time_us();
  11228. llama_file fin(path_lora, "rb");
  11229. // verify magic and version
  11230. {
  11231. uint32_t magic = fin.read_u32();
  11232. if (magic != LLAMA_FILE_MAGIC_GGLA) {
  11233. LLAMA_LOG_ERROR("%s: bad file magic\n", __func__);
  11234. return 1;
  11235. }
  11236. uint32_t format_version = fin.read_u32();
  11237. if (format_version != 1) {
  11238. LLAMA_LOG_ERROR("%s: unsupported file version\n", __func__ );
  11239. return 1;
  11240. }
  11241. }
  11242. int32_t lora_r = fin.read_u32();
  11243. int32_t lora_alpha = fin.read_u32();
  11244. float scaling = scale * (float)lora_alpha / (float)lora_r;
  11245. LLAMA_LOG_INFO("%s: r = %d, alpha = %d, scaling = %.2f\n", __func__, lora_r, lora_alpha, scaling);
  11246. // load base model
  11247. std::unique_ptr<llama_model_loader> ml;
  11248. if (path_base_model) {
  11249. LLAMA_LOG_INFO("%s: loading base model from '%s'\n", __func__, path_base_model);
  11250. ml.reset(new llama_model_loader(path_base_model, /*use_mmap*/ true, /*kv_overrides*/ nullptr));
  11251. ml->init_mappings(/*prefetch*/ false); // no prefetching
  11252. }
  11253. struct tensor_meta {
  11254. std::string name;
  11255. ggml_type type;
  11256. int32_t ne[2];
  11257. size_t offset;
  11258. };
  11259. std::map<std::string, tensor_meta> tensor_meta_map;
  11260. // load all tensor meta
  11261. while (true) {
  11262. if (fin.tell() == fin.size) {
  11263. // eof
  11264. break;
  11265. }
  11266. int32_t n_dims;
  11267. int32_t name_len;
  11268. int32_t ftype;
  11269. fin.read_raw(&n_dims, sizeof(n_dims));
  11270. fin.read_raw(&name_len, sizeof(name_len));
  11271. fin.read_raw(&ftype, sizeof(ftype));
  11272. if (n_dims != 1 && n_dims != 2) {
  11273. LLAMA_LOG_ERROR("%s: unsupported tensor dimension %d\n", __func__, n_dims);
  11274. return 1;
  11275. }
  11276. int32_t ne[2] = { 1, 1 };
  11277. for (int i = 0; i < n_dims; ++i) {
  11278. fin.read_raw(&ne[i], sizeof(ne[i]));
  11279. }
  11280. std::string name;
  11281. {
  11282. GGML_ASSERT(name_len < GGML_MAX_NAME);
  11283. char buf[GGML_MAX_NAME];
  11284. fin.read_raw(buf, name_len);
  11285. name = std::string(buf, name_len);
  11286. }
  11287. // check for lora suffix
  11288. std::string lora_suffix;
  11289. if (name.length() > 6) {
  11290. lora_suffix = name.substr(name.length() - 6);
  11291. }
  11292. if (lora_suffix != ".loraA" && lora_suffix != ".loraB") {
  11293. LLAMA_LOG_ERROR("%s: error: '%s' is not a lora tensor\n", __func__, name.c_str());
  11294. return 1;
  11295. }
  11296. // tensor type
  11297. ggml_type wtype;
  11298. switch (ftype) {
  11299. case 0: wtype = GGML_TYPE_F32; break;
  11300. case 1: wtype = GGML_TYPE_F16; break;
  11301. default:
  11302. {
  11303. LLAMA_LOG_ERROR("%s: invalid tensor data type '%d'\n",
  11304. __func__, ftype);
  11305. return 1;
  11306. }
  11307. }
  11308. // data offset
  11309. size_t offset = fin.tell();
  11310. offset = (offset + 31) & -32;
  11311. // skip tensor data
  11312. fin.seek(offset + ggml_row_size(wtype, ne[0]) * ne[1], SEEK_SET);
  11313. tensor_meta_map.emplace(name, tensor_meta{ name, wtype, { ne[0], ne[1] }, offset });
  11314. }
  11315. bool warned = false;
  11316. int n_tensors = 0;
  11317. // apply
  11318. ggml_backend_t backend_cpu = ggml_backend_cpu_init();
  11319. if (backend_cpu == nullptr) {
  11320. LLAMA_LOG_ERROR("%s: error: failed to initialize cpu backend\n", __func__);
  11321. return 1;
  11322. }
  11323. ggml_backend_cpu_set_n_threads(backend_cpu, n_threads);
  11324. std::vector<no_init<uint8_t>> read_buf;
  11325. for (const auto & it : model.tensors_by_name) {
  11326. const std::string & base_name = it.first;
  11327. ggml_tensor * model_t = it.second;
  11328. if (tensor_meta_map.find(base_name + ".loraA") == tensor_meta_map.end() ||
  11329. tensor_meta_map.find(base_name + ".loraB") == tensor_meta_map.end()) {
  11330. continue;
  11331. }
  11332. tensor_meta & metaA = tensor_meta_map.at(base_name + ".loraA");
  11333. tensor_meta & metaB = tensor_meta_map.at(base_name + ".loraB");
  11334. ggml_init_params lora_init_params = {
  11335. /* .mem_size */ ggml_tensor_overhead()*128 + ggml_graph_overhead(),
  11336. /* .mem_buffer */ nullptr,
  11337. /* .no_alloc */ true,
  11338. };
  11339. ggml_context * lora_ctx = ggml_init(lora_init_params);
  11340. if (lora_ctx == nullptr) {
  11341. LLAMA_LOG_ERROR("%s: error: failed to initialize lora context\n", __func__);
  11342. ggml_backend_free(backend_cpu);
  11343. return 1;
  11344. }
  11345. // create tensors
  11346. ggml_tensor * loraA = ggml_new_tensor_2d(lora_ctx, metaA.type, metaA.ne[0], metaA.ne[1]);
  11347. ggml_tensor * loraB = ggml_new_tensor_2d(lora_ctx, metaB.type, metaB.ne[0], metaB.ne[1]);
  11348. ggml_set_name(loraA, metaA.name.c_str());
  11349. ggml_set_name(loraB, metaB.name.c_str());
  11350. ggml_tensor * base_t;
  11351. if (ml) {
  11352. if (!ml->get_tensor_meta(base_name.c_str())) {
  11353. LLAMA_LOG_ERROR("%s: error: tensor '%s' not found in base model\n", __func__, base_name.c_str());
  11354. return 1;
  11355. }
  11356. base_t = ggml_dup_tensor(lora_ctx, ml->get_tensor_meta(base_name.c_str()));
  11357. } else {
  11358. base_t = ggml_dup_tensor(lora_ctx, model_t);
  11359. }
  11360. ggml_set_name(base_t, base_name.c_str());
  11361. // allocate in backend buffer
  11362. ggml_backend_buffer_t lora_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  11363. if (lora_buf == nullptr) {
  11364. LLAMA_LOG_ERROR("%s: error: failed to allocate lora tensors\n", __func__);
  11365. return 1;
  11366. }
  11367. // load tensor data
  11368. auto load_tensor = [&read_buf, &fin](const tensor_meta & tensor_meta, ggml_tensor * tensor) {
  11369. read_buf.resize(ggml_nbytes(tensor));
  11370. fin.seek(tensor_meta.offset, SEEK_SET);
  11371. fin.read_raw(read_buf.data(), ggml_nbytes(tensor));
  11372. ggml_backend_tensor_set(tensor, read_buf.data(), 0, read_buf.size());
  11373. };
  11374. load_tensor(metaA, loraA);
  11375. load_tensor(metaB, loraB);
  11376. // load base model tensor data
  11377. if (ml) {
  11378. ml->load_data_for(base_t);
  11379. } else {
  11380. ggml_backend_tensor_copy(model_t, base_t);
  11381. }
  11382. if (ggml_is_quantized(base_t->type) && !warned) {
  11383. LLAMA_LOG_WARN("%s: warning: using a lora adapter with a quantized model may result in poor quality, "
  11384. "use a f16 or f32 base model with --lora-base\n", __func__);
  11385. warned = true;
  11386. }
  11387. if (base_t->ne[0] != loraA->ne[1] || base_t->ne[1] != loraB->ne[1]) {
  11388. LLAMA_LOG_ERROR("%s: incompatible tensor dimensions (%" PRId64 " and %" PRId64 ");"
  11389. " are you sure that this adapter is for this model?\n", __func__, base_t->ne[0], loraA->ne[1]);
  11390. ggml_free(lora_ctx);
  11391. ggml_backend_buffer_free(lora_buf);
  11392. ggml_backend_free(backend_cpu);
  11393. return 1;
  11394. }
  11395. auto build_lora_graph = [&]() {
  11396. // w = w + BA*s
  11397. ggml_tensor * BA = ggml_mul_mat(lora_ctx, loraA, loraB);
  11398. ggml_set_name(BA, "BA");
  11399. if (scaling != 1.0f) {
  11400. BA = ggml_scale(lora_ctx, BA, scaling);
  11401. ggml_set_name(BA, "BA_scaled");
  11402. }
  11403. ggml_tensor * r;
  11404. r = ggml_add_inplace(lora_ctx, base_t, BA);
  11405. ggml_set_name(r, "r_add");
  11406. if (base_t->type != model_t->type) {
  11407. // convert the result to the model type
  11408. r = ggml_cast(lora_ctx, r, model_t->type);
  11409. ggml_set_name(r, "r_cast");
  11410. }
  11411. return r;
  11412. };
  11413. ggml_cgraph * gf = ggml_new_graph(lora_ctx);
  11414. ggml_tensor * r = build_lora_graph();
  11415. ggml_build_forward_expand(gf, r);
  11416. ggml_backend_buffer_t graph_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  11417. if (graph_buf == nullptr) {
  11418. LLAMA_LOG_ERROR("%s: error: failed to allocate graph tensors\n", __func__);
  11419. ggml_free(lora_ctx);
  11420. ggml_backend_buffer_free(lora_buf);
  11421. ggml_backend_free(backend_cpu);
  11422. return 1;
  11423. }
  11424. ggml_backend_graph_compute(backend_cpu, gf);
  11425. ggml_backend_tensor_set(model_t, r->data, 0, ggml_nbytes(r));
  11426. #if 0
  11427. // TODO: use scheduler with fallback to CPU for less copies between CPU and GPU
  11428. //ggml_backend_sched_t sched = ggml_backend_sched_new(backends.data(), backends.size(), GGML_DEFAULT_GRAPH_SIZE);
  11429. // sched compute
  11430. ggml_build_forward_expand(gf, build_graph());
  11431. ggml_backend_sched_init_measure(sched, gf);
  11432. // create the graph again, since the previous one was destroyed by the measure
  11433. ggml_graph_clear(gf);
  11434. ggml_build_forward_expand(gf, build_graph());
  11435. ggml_backend_sched_graph_compute(sched, gf);
  11436. ggml_backend_sched_free(sched);
  11437. #endif
  11438. ggml_backend_buffer_free(lora_buf);
  11439. ggml_backend_buffer_free(graph_buf);
  11440. ggml_free(lora_ctx);
  11441. n_tensors++;
  11442. if (n_tensors % 4 == 0) {
  11443. LLAMA_LOG_INFO(".");
  11444. }
  11445. }
  11446. ggml_backend_free(backend_cpu);
  11447. const int64_t t_lora_us = ggml_time_us() - t_start_lora_us;
  11448. LLAMA_LOG_INFO(" done (%.2f ms)\n", t_lora_us / 1000.0);
  11449. return 0;
  11450. }
  11451. //
  11452. // interface implementation
  11453. //
  11454. struct llama_model_params llama_model_default_params() {
  11455. struct llama_model_params result = {
  11456. /*.n_gpu_layers =*/ 0,
  11457. /*.split_mode =*/ LLAMA_SPLIT_MODE_LAYER,
  11458. /*.main_gpu =*/ 0,
  11459. /*.tensor_split =*/ nullptr,
  11460. /*.progress_callback =*/ nullptr,
  11461. /*.progress_callback_user_data =*/ nullptr,
  11462. /*.kv_overrides =*/ nullptr,
  11463. /*.vocab_only =*/ false,
  11464. /*.use_mmap =*/ true,
  11465. /*.use_mlock =*/ false,
  11466. };
  11467. #ifdef GGML_USE_METAL
  11468. // note: we usually have plenty of VRAM, so by default offload all layers to the GPU
  11469. result.n_gpu_layers = 999;
  11470. #endif
  11471. return result;
  11472. }
  11473. struct llama_context_params llama_context_default_params() {
  11474. struct llama_context_params result = {
  11475. /*.seed =*/ LLAMA_DEFAULT_SEED,
  11476. /*.n_ctx =*/ 512,
  11477. /*.n_batch =*/ 2048,
  11478. /*.n_ubatch =*/ 512,
  11479. /*.n_seq_max =*/ 1,
  11480. /*.n_threads =*/ GGML_DEFAULT_N_THREADS, // TODO: better default
  11481. /*.n_threads_batch =*/ GGML_DEFAULT_N_THREADS,
  11482. /*.rope_scaling_type =*/ LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED,
  11483. /*.pooling_type =*/ LLAMA_POOLING_TYPE_UNSPECIFIED,
  11484. /*.rope_freq_base =*/ 0.0f,
  11485. /*.rope_freq_scale =*/ 0.0f,
  11486. /*.yarn_ext_factor =*/ -1.0f,
  11487. /*.yarn_attn_factor =*/ 1.0f,
  11488. /*.yarn_beta_fast =*/ 32.0f,
  11489. /*.yarn_beta_slow =*/ 1.0f,
  11490. /*.yarn_orig_ctx =*/ 0,
  11491. /*.defrag_thold =*/ -1.0f,
  11492. /*.cb_eval =*/ nullptr,
  11493. /*.cb_eval_user_data =*/ nullptr,
  11494. /*.type_k =*/ GGML_TYPE_F16,
  11495. /*.type_v =*/ GGML_TYPE_F16,
  11496. /*.logits_all =*/ false,
  11497. /*.embeddings =*/ false,
  11498. /*.offload_kqv =*/ true,
  11499. /*.abort_callback =*/ nullptr,
  11500. /*.abort_callback_data =*/ nullptr,
  11501. };
  11502. return result;
  11503. }
  11504. struct llama_model_quantize_params llama_model_quantize_default_params() {
  11505. struct llama_model_quantize_params result = {
  11506. /*.nthread =*/ 0,
  11507. /*.ftype =*/ LLAMA_FTYPE_MOSTLY_Q5_1,
  11508. /*.output_tensor_type =*/ GGML_TYPE_COUNT,
  11509. /*.token_embedding_type =*/ GGML_TYPE_COUNT,
  11510. /*.allow_requantize =*/ false,
  11511. /*.quantize_output_tensor =*/ true,
  11512. /*.only_copy =*/ false,
  11513. /*.pure =*/ false,
  11514. /*.imatrix =*/ nullptr,
  11515. /*.kv_overrides =*/ nullptr,
  11516. };
  11517. return result;
  11518. }
  11519. size_t llama_max_devices(void) {
  11520. #if defined(GGML_USE_METAL)
  11521. return 1;
  11522. #elif defined(GGML_USE_CUDA)
  11523. return GGML_CUDA_MAX_DEVICES;
  11524. #elif defined(GGML_USE_SYCL)
  11525. return GGML_SYCL_MAX_DEVICES;
  11526. #elif defined(GGML_USE_VULKAN)
  11527. return GGML_VK_MAX_DEVICES;
  11528. #else
  11529. return 1;
  11530. #endif
  11531. }
  11532. bool llama_supports_mmap(void) {
  11533. return llama_mmap::SUPPORTED;
  11534. }
  11535. bool llama_supports_mlock(void) {
  11536. return llama_mlock::SUPPORTED;
  11537. }
  11538. bool llama_supports_gpu_offload(void) {
  11539. #if defined(GGML_USE_CUDA) || defined(GGML_USE_CLBLAST) || defined(GGML_USE_METAL) || defined(GGML_USE_VULKAN) || \
  11540. defined(GGML_USE_SYCL) || defined(GGML_USE_KOMPUTE)
  11541. // Defined when llama.cpp is compiled with support for offloading model layers to GPU.
  11542. return true;
  11543. #else
  11544. return false;
  11545. #endif
  11546. }
  11547. void llama_backend_init(void) {
  11548. ggml_time_init();
  11549. // needed to initialize f16 tables
  11550. {
  11551. struct ggml_init_params params = { 0, NULL, false };
  11552. struct ggml_context * ctx = ggml_init(params);
  11553. ggml_free(ctx);
  11554. }
  11555. #ifdef GGML_USE_MPI
  11556. ggml_mpi_backend_init();
  11557. #endif
  11558. }
  11559. void llama_numa_init(enum ggml_numa_strategy numa) {
  11560. if (numa != GGML_NUMA_STRATEGY_DISABLED) {
  11561. ggml_numa_init(numa);
  11562. }
  11563. }
  11564. void llama_backend_free(void) {
  11565. #ifdef GGML_USE_MPI
  11566. ggml_mpi_backend_free();
  11567. #endif
  11568. ggml_quantize_free();
  11569. }
  11570. int64_t llama_time_us(void) {
  11571. return ggml_time_us();
  11572. }
  11573. struct llama_model * llama_load_model_from_file(
  11574. const char * path_model,
  11575. struct llama_model_params params) {
  11576. ggml_time_init();
  11577. llama_model * model = new llama_model;
  11578. unsigned cur_percentage = 0;
  11579. if (params.progress_callback == NULL) {
  11580. params.progress_callback_user_data = &cur_percentage;
  11581. params.progress_callback = [](float progress, void * ctx) {
  11582. unsigned * cur_percentage_p = (unsigned *) ctx;
  11583. unsigned percentage = (unsigned) (100 * progress);
  11584. while (percentage > *cur_percentage_p) {
  11585. *cur_percentage_p = percentage;
  11586. LLAMA_LOG_INFO(".");
  11587. if (percentage >= 100) {
  11588. LLAMA_LOG_INFO("\n");
  11589. }
  11590. }
  11591. return true;
  11592. };
  11593. }
  11594. int status = llama_model_load(path_model, *model, params);
  11595. GGML_ASSERT(status <= 0);
  11596. if (status < 0) {
  11597. if (status == -1) {
  11598. LLAMA_LOG_ERROR("%s: failed to load model\n", __func__);
  11599. } else if (status == -2) {
  11600. LLAMA_LOG_INFO("%s: cancelled model load\n", __func__);
  11601. }
  11602. delete model;
  11603. return nullptr;
  11604. }
  11605. return model;
  11606. }
  11607. void llama_free_model(struct llama_model * model) {
  11608. delete model;
  11609. }
  11610. struct llama_context * llama_new_context_with_model(
  11611. struct llama_model * model,
  11612. struct llama_context_params params) {
  11613. if (!model) {
  11614. LLAMA_LOG_ERROR("%s: model cannot be NULL\n", __func__);
  11615. return nullptr;
  11616. }
  11617. if (params.n_batch == 0 && params.n_ubatch == 0) {
  11618. LLAMA_LOG_ERROR("%s: n_batch and n_ubatch cannot both be zero\n", __func__);
  11619. return nullptr;
  11620. }
  11621. if (params.n_ctx == 0 && model->hparams.n_ctx_train == 0) {
  11622. LLAMA_LOG_ERROR("%s: n_ctx and model->hparams.n_ctx_train cannot both be zero\n", __func__);
  11623. return nullptr;
  11624. }
  11625. llama_context * ctx = new llama_context(*model);
  11626. const auto & hparams = model->hparams;
  11627. auto & cparams = ctx->cparams;
  11628. cparams.n_seq_max = std::max(1u, params.n_seq_max);
  11629. cparams.n_threads = params.n_threads;
  11630. cparams.n_threads_batch = params.n_threads_batch;
  11631. cparams.yarn_ext_factor = params.yarn_ext_factor;
  11632. cparams.yarn_attn_factor = params.yarn_attn_factor;
  11633. cparams.yarn_beta_fast = params.yarn_beta_fast;
  11634. cparams.yarn_beta_slow = params.yarn_beta_slow;
  11635. cparams.defrag_thold = params.defrag_thold;
  11636. cparams.embeddings = params.embeddings;
  11637. cparams.offload_kqv = params.offload_kqv;
  11638. cparams.pooling_type = params.pooling_type;
  11639. cparams.n_ctx = params.n_ctx == 0 ? hparams.n_ctx_train : params.n_ctx;
  11640. cparams.rope_freq_base = params.rope_freq_base == 0.0f ? hparams.rope_freq_base_train : params.rope_freq_base;
  11641. cparams.rope_freq_scale = params.rope_freq_scale == 0.0f ? hparams.rope_freq_scale_train : params.rope_freq_scale;
  11642. // this is necessary due to kv_self.n being padded later during inference
  11643. cparams.n_ctx = GGML_PAD(cparams.n_ctx, 32);
  11644. // with causal attention, the batch size is limited by the context size
  11645. cparams.n_batch = hparams.causal_attn ? std::min(cparams.n_ctx, params.n_batch) : params.n_batch;
  11646. cparams.n_ubatch = std::min(cparams.n_batch, params.n_ubatch == 0 ? params.n_batch : params.n_ubatch);
  11647. cparams.n_yarn_orig_ctx = params.yarn_orig_ctx != 0 ? params.yarn_orig_ctx :
  11648. hparams.n_yarn_orig_ctx != 0 ? hparams.n_yarn_orig_ctx :
  11649. hparams.n_ctx_train;
  11650. cparams.cb_eval = params.cb_eval;
  11651. cparams.cb_eval_user_data = params.cb_eval_user_data;
  11652. auto rope_scaling_type = params.rope_scaling_type;
  11653. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED) {
  11654. rope_scaling_type = hparams.rope_scaling_type_train;
  11655. }
  11656. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_NONE) {
  11657. cparams.rope_freq_scale = 1.0f; // never scale if scaling type is none
  11658. }
  11659. if (cparams.yarn_ext_factor < 0.0f) { // negative indicates 'not set'
  11660. cparams.yarn_ext_factor = rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_YARN ? 1.0f : 0.0f;
  11661. }
  11662. cparams.causal_attn = hparams.causal_attn;
  11663. if (cparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  11664. if (hparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  11665. cparams.pooling_type = LLAMA_POOLING_TYPE_NONE;
  11666. } else {
  11667. cparams.pooling_type = hparams.pooling_type;
  11668. }
  11669. }
  11670. if (params.seed == LLAMA_DEFAULT_SEED) {
  11671. params.seed = time(NULL);
  11672. }
  11673. LLAMA_LOG_INFO("%s: n_ctx = %u\n", __func__, cparams.n_ctx);
  11674. LLAMA_LOG_INFO("%s: n_batch = %u\n", __func__, cparams.n_batch);
  11675. LLAMA_LOG_INFO("%s: n_ubatch = %u\n", __func__, cparams.n_ubatch);
  11676. LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, cparams.rope_freq_base);
  11677. LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, cparams.rope_freq_scale);
  11678. ctx->abort_callback = params.abort_callback;
  11679. ctx->abort_callback_data = params.abort_callback_data;
  11680. ctx->rng = std::mt19937(params.seed);
  11681. ctx->logits_all = params.logits_all;
  11682. uint32_t kv_size = cparams.n_ctx;
  11683. ggml_type type_k = params.type_k;
  11684. ggml_type type_v = params.type_v;
  11685. // Mamba only needs a constant number of KV cache cells per sequence
  11686. if (model->arch == LLM_ARCH_MAMBA) {
  11687. // Mamba needs at least as many KV cells as there are sequences kept at any time
  11688. kv_size = std::max((uint32_t) 1, params.n_seq_max);
  11689. // it's probably best to keep as much precision as possible for the states
  11690. type_k = GGML_TYPE_F32; // required by ggml_ssm_conv for Mamba's conv_states
  11691. type_v = GGML_TYPE_F32; // required by ggml_ssm_scan for Mamba's ssm_states
  11692. }
  11693. GGML_ASSERT(hparams.n_embd_head_k % ggml_blck_size(type_k) == 0);
  11694. GGML_ASSERT(hparams.n_embd_head_v % ggml_blck_size(type_v) == 0);
  11695. if (!hparams.vocab_only) {
  11696. // initialize backends
  11697. #ifdef GGML_USE_METAL
  11698. if (model->n_gpu_layers > 0) {
  11699. ctx->backend_metal = ggml_backend_metal_init();
  11700. if (ctx->backend_metal == nullptr) {
  11701. LLAMA_LOG_ERROR("%s: failed to initialize Metal backend\n", __func__);
  11702. llama_free(ctx);
  11703. return nullptr;
  11704. }
  11705. ctx->backends.push_back(ctx->backend_metal);
  11706. }
  11707. #elif defined(GGML_USE_CUDA)
  11708. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  11709. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  11710. ggml_backend_t backend = ggml_backend_cuda_init(model->main_gpu);
  11711. if (backend == nullptr) {
  11712. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, model->main_gpu);
  11713. llama_free(ctx);
  11714. return nullptr;
  11715. }
  11716. ctx->backends.push_back(backend);
  11717. } else {
  11718. // LLAMA_SPLIT_MODE_LAYER requires a backend for each GPU
  11719. for (int device = 0; device < ggml_backend_cuda_get_device_count(); ++device) {
  11720. ggml_backend_t backend = ggml_backend_cuda_init(device);
  11721. if (backend == nullptr) {
  11722. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, device);
  11723. llama_free(ctx);
  11724. return nullptr;
  11725. }
  11726. ctx->backends.push_back(backend);
  11727. }
  11728. }
  11729. #elif defined(GGML_USE_VULKAN)
  11730. if (model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  11731. LLAMA_LOG_ERROR("%s: Row split not supported. Failed to initialize Vulkan backend\n", __func__);
  11732. llama_free(ctx);
  11733. return nullptr;
  11734. }
  11735. if (model->split_mode == LLAMA_SPLIT_MODE_NONE) {
  11736. ggml_backend_t backend = ggml_backend_vk_init(0);
  11737. if (backend == nullptr) {
  11738. LLAMA_LOG_ERROR("%s: failed to initialize Vulkan backend\n", __func__);
  11739. llama_free(ctx);
  11740. return nullptr;
  11741. }
  11742. ctx->backends.push_back(backend);
  11743. } else {
  11744. for (int device = 0; device < ggml_backend_vk_get_device_count(); ++device) {
  11745. ggml_backend_t backend = ggml_backend_vk_init(device);
  11746. if (backend == nullptr) {
  11747. LLAMA_LOG_ERROR("%s: failed to initialize Vulkan%d backend\n", __func__, device);
  11748. llama_free(ctx);
  11749. return nullptr;
  11750. }
  11751. ctx->backends.push_back(backend);
  11752. }
  11753. }
  11754. #elif defined(GGML_USE_SYCL)
  11755. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  11756. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  11757. ggml_backend_t backend = ggml_backend_sycl_init(model->main_gpu);
  11758. if (backend == nullptr) {
  11759. int main_gpu_id = ggml_backend_sycl_get_device_id(model->main_gpu);
  11760. LLAMA_LOG_ERROR("%s: failed to initialize SYCL%d (index %d) backend\n", __func__, main_gpu_id, model->main_gpu);
  11761. llama_free(ctx);
  11762. return nullptr;
  11763. }
  11764. ctx->backends.push_back(backend);
  11765. } else {
  11766. // LLAMA_SPLIT_LAYER requires a backend for each GPU
  11767. for (int i = 0; i < ggml_backend_sycl_get_device_count(); ++i) {
  11768. ggml_backend_t backend = ggml_backend_sycl_init(i);
  11769. if (backend == nullptr) {
  11770. int id_list[GGML_SYCL_MAX_DEVICES];
  11771. ggml_sycl_get_gpu_list(id_list, GGML_SYCL_MAX_DEVICES);
  11772. LLAMA_LOG_ERROR("%s: failed to initialize SYCL%d (index %d) backend\n", __func__, id_list[i], i);
  11773. llama_free(ctx);
  11774. return nullptr;
  11775. }
  11776. ctx->backends.push_back(backend);
  11777. }
  11778. }
  11779. #elif defined(GGML_USE_KOMPUTE)
  11780. if (model->n_gpu_layers > 0) {
  11781. auto * backend = ggml_backend_kompute_init(model->main_gpu);
  11782. if (backend == nullptr) {
  11783. LLAMA_LOG_ERROR("%s: failed to initialize Kompute backend\n", __func__);
  11784. llama_free(ctx);
  11785. return nullptr;
  11786. }
  11787. ctx->backends.push_back(backend);
  11788. }
  11789. #endif
  11790. ctx->backend_cpu = ggml_backend_cpu_init();
  11791. if (ctx->backend_cpu == nullptr) {
  11792. LLAMA_LOG_ERROR("%s: failed to initialize CPU backend\n", __func__);
  11793. llama_free(ctx);
  11794. return nullptr;
  11795. }
  11796. ctx->backends.push_back(ctx->backend_cpu);
  11797. if (!llama_kv_cache_init(ctx->kv_self, ctx->model, type_k, type_v, kv_size, cparams.offload_kqv)) {
  11798. LLAMA_LOG_ERROR("%s: llama_kv_cache_init() failed for self-attention cache\n", __func__);
  11799. llama_free(ctx);
  11800. return nullptr;
  11801. }
  11802. {
  11803. size_t memory_size_k = 0;
  11804. size_t memory_size_v = 0;
  11805. for (auto & k : ctx->kv_self.k_l) {
  11806. memory_size_k += ggml_nbytes(k);
  11807. }
  11808. for (auto & v : ctx->kv_self.v_l) {
  11809. memory_size_v += ggml_nbytes(v);
  11810. }
  11811. LLAMA_LOG_INFO("%s: KV self size = %7.2f MiB, K (%s): %7.2f MiB, V (%s): %7.2f MiB\n", __func__,
  11812. (float)(memory_size_k + memory_size_v) / (1024.0f * 1024.0f),
  11813. ggml_type_name(type_k), (float)memory_size_k / (1024.0f * 1024.0f),
  11814. ggml_type_name(type_v), (float)memory_size_v / (1024.0f * 1024.0f));
  11815. }
  11816. // graph outputs buffer
  11817. {
  11818. // resized during inference when a batch uses more outputs
  11819. if (llama_output_reserve(*ctx, params.n_seq_max) < params.n_seq_max) {
  11820. LLAMA_LOG_ERROR("%s: failed to reserve initial output buffer\n", __func__);
  11821. llama_free(ctx);
  11822. return nullptr;
  11823. }
  11824. LLAMA_LOG_INFO("%s: %10s output buffer size = %8.2f MiB\n", __func__,
  11825. ggml_backend_buffer_name(ctx->buf_output),
  11826. ggml_backend_buffer_get_size(ctx->buf_output) / 1024.0 / 1024.0);
  11827. }
  11828. // scheduler and compute buffers
  11829. {
  11830. // buffer types used for the compute buffer of each backend
  11831. std::vector<ggml_backend_buffer_type_t> backend_buft;
  11832. for (auto * backend : ctx->backends) {
  11833. if (ggml_backend_is_cpu(backend)) {
  11834. // use host buffers for the CPU backend compute buffer
  11835. backend_buft.push_back(llama_default_buffer_type_cpu(true));
  11836. } else {
  11837. backend_buft.push_back(ggml_backend_get_default_buffer_type(backend));
  11838. }
  11839. }
  11840. // buffer used to store the computation graph and the tensor meta data
  11841. ctx->buf_compute_meta.resize(ggml_tensor_overhead()*LLAMA_MAX_NODES + ggml_graph_overhead_custom(LLAMA_MAX_NODES, false));
  11842. // enabling pipeline parallelism in the scheduler increases memory usage, so it is only done when necessary
  11843. bool pipeline_parallel = llama_get_device_count() > 1 && model->n_gpu_layers > (int)model->hparams.n_layer && model->split_mode == LLAMA_SPLIT_MODE_LAYER;
  11844. #ifndef GGML_USE_CUDA
  11845. // pipeline parallelism requires support for async compute and events
  11846. // currently this is only implemented in the CUDA backend
  11847. pipeline_parallel = false;
  11848. #endif
  11849. ctx->sched = ggml_backend_sched_new(ctx->backends.data(), backend_buft.data(), ctx->backends.size(), LLAMA_MAX_NODES, pipeline_parallel);
  11850. if (pipeline_parallel) {
  11851. LLAMA_LOG_INFO("%s: pipeline parallelism enabled (n_copies=%d)\n", __func__, ggml_backend_sched_get_n_copies(ctx->sched));
  11852. }
  11853. // build worst-case graph
  11854. int n_tokens = (int)std::min(cparams.n_ctx, cparams.n_ubatch);
  11855. int n_past = cparams.n_ctx - n_tokens;
  11856. 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
  11857. ggml_cgraph * gf = llama_build_graph(*ctx, llama_batch_get_one(&token, n_tokens, n_past, 0), true);
  11858. // initialize scheduler with the worst-case graph
  11859. if (!ggml_backend_sched_reserve(ctx->sched, gf)) {
  11860. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  11861. llama_free(ctx);
  11862. return nullptr;
  11863. }
  11864. for (size_t i = 0; i < ctx->backends.size(); i++) {
  11865. ggml_backend_t backend = ctx->backends[i];
  11866. ggml_backend_buffer_type_t buft = backend_buft[i];
  11867. size_t size = ggml_backend_sched_get_buffer_size(ctx->sched, backend);
  11868. if (size > 1) {
  11869. LLAMA_LOG_INFO("%s: %10s compute buffer size = %8.2f MiB\n", __func__,
  11870. ggml_backend_buft_name(buft),
  11871. size / 1024.0 / 1024.0);
  11872. }
  11873. }
  11874. // note: the number of splits during measure is higher than during inference due to the kv shift
  11875. int n_splits = ggml_backend_sched_get_n_splits(ctx->sched);
  11876. LLAMA_LOG_INFO("%s: graph nodes = %d\n", __func__, gf->n_nodes);
  11877. LLAMA_LOG_INFO("%s: graph splits = %d\n", __func__, n_splits);
  11878. }
  11879. }
  11880. #ifdef GGML_USE_MPI
  11881. ctx->ctx_mpi = ggml_mpi_init();
  11882. if (ggml_mpi_rank(ctx->ctx_mpi) > 0) {
  11883. // Enter a blocking eval loop with dummy input, letting rank=0 drive the process
  11884. // TODO: needs fix after #3228
  11885. GGML_ASSERT(false && "not implemented");
  11886. //const std::vector<llama_token> tmp(ctx->model.hparams.n_ctx, llama_token_bos(ctx));
  11887. //while (!llama_eval(ctx, tmp.data(), tmp.size(), 0, 0)) {};
  11888. llama_backend_free();
  11889. exit(1);
  11890. }
  11891. #endif
  11892. return ctx;
  11893. }
  11894. void llama_free(struct llama_context * ctx) {
  11895. delete ctx;
  11896. }
  11897. const llama_model * llama_get_model(const struct llama_context * ctx) {
  11898. return &ctx->model;
  11899. }
  11900. uint32_t llama_n_ctx(const struct llama_context * ctx) {
  11901. return ctx->cparams.n_ctx;
  11902. }
  11903. uint32_t llama_n_batch(const struct llama_context * ctx) {
  11904. return ctx->cparams.n_batch;
  11905. }
  11906. uint32_t llama_n_ubatch(const struct llama_context * ctx) {
  11907. return ctx->cparams.n_ubatch;
  11908. }
  11909. uint32_t llama_n_seq_max(const struct llama_context * ctx) {
  11910. return ctx->kv_self.size;
  11911. }
  11912. enum llama_vocab_type llama_vocab_type(const struct llama_model * model) {
  11913. return model->vocab.type;
  11914. }
  11915. enum llama_rope_type llama_rope_type(const struct llama_model * model) {
  11916. switch (model->arch) {
  11917. // these models do not use RoPE
  11918. case LLM_ARCH_GPT2:
  11919. case LLM_ARCH_GPTJ:
  11920. case LLM_ARCH_GPTNEOX:
  11921. case LLM_ARCH_MPT:
  11922. case LLM_ARCH_REFACT:
  11923. case LLM_ARCH_BLOOM:
  11924. case LLM_ARCH_MAMBA:
  11925. return LLAMA_ROPE_TYPE_NONE;
  11926. // use what we call a normal RoPE, operating on pairs of consecutive head values
  11927. case LLM_ARCH_LLAMA:
  11928. case LLM_ARCH_BAICHUAN:
  11929. case LLM_ARCH_STARCODER:
  11930. case LLM_ARCH_PLAMO:
  11931. case LLM_ARCH_CODESHELL:
  11932. case LLM_ARCH_ORION:
  11933. case LLM_ARCH_INTERNLM2:
  11934. case LLM_ARCH_MINICPM:
  11935. case LLM_ARCH_XVERSE:
  11936. case LLM_ARCH_COMMAND_R:
  11937. return LLAMA_ROPE_TYPE_NORM;
  11938. // the pairs of head values are offset by n_rot/2
  11939. case LLM_ARCH_FALCON:
  11940. case LLM_ARCH_GROK:
  11941. case LLM_ARCH_PERSIMMON:
  11942. case LLM_ARCH_BERT:
  11943. case LLM_ARCH_NOMIC_BERT:
  11944. case LLM_ARCH_STABLELM:
  11945. case LLM_ARCH_QWEN:
  11946. case LLM_ARCH_QWEN2:
  11947. case LLM_ARCH_PHI2:
  11948. case LLM_ARCH_GEMMA:
  11949. case LLM_ARCH_STARCODER2:
  11950. return LLAMA_ROPE_TYPE_NEOX;
  11951. // all model arches should be listed explicitly here
  11952. case LLM_ARCH_UNKNOWN:
  11953. GGML_ASSERT(false && "unknown architecture");
  11954. break;
  11955. }
  11956. return LLAMA_ROPE_TYPE_NONE;
  11957. }
  11958. int32_t llama_n_vocab(const struct llama_model * model) {
  11959. return model->hparams.n_vocab;
  11960. }
  11961. int32_t llama_n_ctx_train(const struct llama_model * model) {
  11962. return model->hparams.n_ctx_train;
  11963. }
  11964. int32_t llama_n_embd(const struct llama_model * model) {
  11965. return model->hparams.n_embd;
  11966. }
  11967. int32_t llama_n_layer(const struct llama_model * model) {
  11968. return model->hparams.n_layer;
  11969. }
  11970. float llama_rope_freq_scale_train(const struct llama_model * model) {
  11971. return model->hparams.rope_freq_scale_train;
  11972. }
  11973. int32_t llama_model_meta_val_str(const struct llama_model * model, const char * key, char * buf, size_t buf_size) {
  11974. const auto & it = model->gguf_kv.find(key);
  11975. if (it == model->gguf_kv.end()) {
  11976. if (buf_size > 0) {
  11977. buf[0] = '\0';
  11978. }
  11979. return -1;
  11980. }
  11981. return snprintf(buf, buf_size, "%s", it->second.c_str());
  11982. }
  11983. int32_t llama_model_meta_count(const struct llama_model * model) {
  11984. return (int)model->gguf_kv.size();
  11985. }
  11986. int32_t llama_model_meta_key_by_index(const struct llama_model * model, int i, char * buf, size_t buf_size) {
  11987. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  11988. if (buf_size > 0) {
  11989. buf[0] = '\0';
  11990. }
  11991. return -1;
  11992. }
  11993. auto it = model->gguf_kv.begin();
  11994. std::advance(it, i);
  11995. return snprintf(buf, buf_size, "%s", it->first.c_str());
  11996. }
  11997. int32_t llama_model_meta_val_str_by_index(const struct llama_model * model, int32_t i, char * buf, size_t buf_size) {
  11998. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  11999. if (buf_size > 0) {
  12000. buf[0] = '\0';
  12001. }
  12002. return -1;
  12003. }
  12004. auto it = model->gguf_kv.begin();
  12005. std::advance(it, i);
  12006. return snprintf(buf, buf_size, "%s", it->second.c_str());
  12007. }
  12008. int32_t llama_model_desc(const struct llama_model * model, char * buf, size_t buf_size) {
  12009. return snprintf(buf, buf_size, "%s %s %s",
  12010. llama_model_arch_name(model->arch),
  12011. llama_model_type_name(model->type),
  12012. llama_model_ftype_name(model->ftype).c_str());
  12013. }
  12014. uint64_t llama_model_size(const struct llama_model * model) {
  12015. uint64_t size = 0;
  12016. for (const auto & it : model->tensors_by_name) {
  12017. size += ggml_nbytes(it.second);
  12018. }
  12019. return size;
  12020. }
  12021. uint64_t llama_model_n_params(const struct llama_model * model) {
  12022. uint64_t nparams = 0;
  12023. for (const auto & it : model->tensors_by_name) {
  12024. nparams += ggml_nelements(it.second);
  12025. }
  12026. return nparams;
  12027. }
  12028. struct ggml_tensor * llama_get_model_tensor(struct llama_model * model, const char * name) {
  12029. auto it = std::find_if(model->tensors_by_name.begin(), model->tensors_by_name.end(),
  12030. [name](const std::pair<std::string, struct ggml_tensor *> & it) {
  12031. return it.first == name;
  12032. });
  12033. if (it == model->tensors_by_name.end()) {
  12034. return nullptr;
  12035. }
  12036. return it->second;
  12037. }
  12038. uint32_t llama_model_quantize(
  12039. const char * fname_inp,
  12040. const char * fname_out,
  12041. const llama_model_quantize_params * params) {
  12042. try {
  12043. llama_model_quantize_internal(fname_inp, fname_out, params);
  12044. return 0;
  12045. } catch (const std::exception & err) {
  12046. LLAMA_LOG_ERROR("%s: failed to quantize: %s\n", __func__, err.what());
  12047. return 1;
  12048. }
  12049. }
  12050. 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) {
  12051. try {
  12052. return llama_apply_lora_from_file_internal(*model, path_lora, scale, path_base_model, n_threads);
  12053. } catch (const std::exception & err) {
  12054. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  12055. return 1;
  12056. }
  12057. }
  12058. static bool llama_control_vector_init(struct llama_control_vector & cvec, const llama_model & model) {
  12059. GGML_ASSERT(cvec.tensors.empty());
  12060. GGML_ASSERT(cvec.ctxs.empty());
  12061. GGML_ASSERT(cvec.bufs.empty());
  12062. // count layer buffer types
  12063. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  12064. for (int64_t i = 0; i < model.hparams.n_layer; i++) {
  12065. buft_layer_count[model.buft_layer[i].buft]++;
  12066. }
  12067. // allocate contexts
  12068. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  12069. for (auto & it : buft_layer_count) {
  12070. int n_layers = it.second;
  12071. struct ggml_init_params params = {
  12072. /*.mem_size =*/ n_layers * ggml_tensor_overhead(),
  12073. /*.mem_buffer =*/ NULL,
  12074. /*.no_alloc =*/ true,
  12075. };
  12076. ggml_context * ctx = ggml_init(params);
  12077. if (!ctx) {
  12078. LLAMA_LOG_ERROR("%s: failed to allocate context for control vector\n", __func__);
  12079. return 1;
  12080. }
  12081. ctx_map[it.first] = ctx;
  12082. }
  12083. // make tensors
  12084. cvec.tensors.push_back(nullptr); // there's never a tensor for layer 0
  12085. for (size_t il = 1; il < model.hparams.n_layer; il++) {
  12086. struct ggml_context * ctx = ctx_map.at(model.buft_layer[il].buft);
  12087. ggml_tensor * tensor = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, model.hparams.n_embd);
  12088. cvec.tensors.push_back(tensor);
  12089. }
  12090. // allocate tensors / buffers and zero
  12091. for (auto it : ctx_map) {
  12092. ggml_backend_buffer_type_t buft = it.first;
  12093. ggml_context * ctx = it.second;
  12094. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  12095. if (!buf) {
  12096. LLAMA_LOG_ERROR("%s: failed to allocate buffer for control vector\n", __func__);
  12097. return false;
  12098. }
  12099. ggml_backend_buffer_clear(buf, 0);
  12100. cvec.ctxs.push_back(ctx);
  12101. cvec.bufs.push_back(buf);
  12102. }
  12103. return true;
  12104. }
  12105. 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) {
  12106. const llama_model & model = lctx->model;
  12107. llama_control_vector & cvec = lctx->cvec;
  12108. if (data == nullptr) {
  12109. // disable the current control vector (but leave allocated for later)
  12110. cvec.layer_start = -1;
  12111. cvec.layer_end = -1;
  12112. return 0;
  12113. }
  12114. if (n_embd != (int) model.hparams.n_embd) {
  12115. LLAMA_LOG_ERROR("%s: control vector n_embd does not match model\n", __func__);
  12116. return 1;
  12117. }
  12118. if (cvec.tensors.empty()) {
  12119. if (!llama_control_vector_init(cvec, model)) {
  12120. return 1;
  12121. }
  12122. }
  12123. cvec.layer_start = il_start;
  12124. cvec.layer_end = il_end;
  12125. for (size_t il = 1; il < model.hparams.n_layer; il++) {
  12126. assert(cvec.tensors[il] != nullptr);
  12127. const size_t off = n_embd * (il - 1); // buffer doesn't have data for layer 0, since it's never present
  12128. if (off + n_embd <= len) {
  12129. ggml_backend_tensor_set(cvec.tensors[il], data + off, 0, n_embd * ggml_element_size(cvec.tensors[il]));
  12130. }
  12131. }
  12132. return 0;
  12133. }
  12134. struct llama_kv_cache_view llama_kv_cache_view_init(const struct llama_context * ctx, int32_t n_seq_max) {
  12135. struct llama_kv_cache_view result = {
  12136. /*.n_cells = */ 0,
  12137. /*.n_seq_max = */ n_seq_max,
  12138. /*.token_count = */ 0,
  12139. /*.used_cells = */ llama_get_kv_cache_used_cells(ctx),
  12140. /*.max_contiguous = */ 0,
  12141. /*.max_contiguous_idx = */ -1,
  12142. /*.cells = */ nullptr,
  12143. /*.cells_sequences = */ nullptr,
  12144. };
  12145. return result;
  12146. }
  12147. void llama_kv_cache_view_free(struct llama_kv_cache_view * view) {
  12148. if (view->cells != nullptr) {
  12149. free(view->cells);
  12150. view->cells = nullptr;
  12151. }
  12152. if (view->cells_sequences != nullptr) {
  12153. free(view->cells_sequences);
  12154. view->cells_sequences = nullptr;
  12155. }
  12156. }
  12157. void llama_kv_cache_view_update(const struct llama_context * ctx, struct llama_kv_cache_view * view) {
  12158. if (uint32_t(view->n_cells) < ctx->kv_self.size || view->cells == nullptr) {
  12159. view->n_cells = int32_t(ctx->kv_self.size);
  12160. void * p = realloc(view->cells, sizeof(struct llama_kv_cache_view_cell) * view->n_cells);
  12161. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells");
  12162. view->cells = (struct llama_kv_cache_view_cell *)p;
  12163. p = realloc(view->cells_sequences, sizeof(llama_seq_id) * view->n_seq_max * view->n_cells);
  12164. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells sequences");
  12165. view->cells_sequences = (llama_seq_id *)p;
  12166. }
  12167. const std::vector<llama_kv_cell> & kv_cells = ctx->kv_self.cells;
  12168. llama_kv_cache_view_cell * c_curr = view->cells;
  12169. llama_seq_id * cs_curr = view->cells_sequences;
  12170. int32_t used_cells = 0;
  12171. int32_t token_count = 0;
  12172. int32_t curr_contig_idx = -1;
  12173. uint32_t max_contig = 0;
  12174. int32_t max_contig_idx = -1;
  12175. for (int32_t i = 0; i < int32_t(ctx->kv_self.size); i++, c_curr++, cs_curr += view->n_seq_max) {
  12176. const size_t curr_size = kv_cells[i].seq_id.size();
  12177. token_count += curr_size;
  12178. c_curr->pos = kv_cells[i].pos + kv_cells[i].delta;
  12179. if (curr_size > 0) {
  12180. if (curr_contig_idx >= 0 && uint32_t(i - curr_contig_idx) > max_contig) {
  12181. max_contig = i - curr_contig_idx;
  12182. max_contig_idx = curr_contig_idx;
  12183. }
  12184. curr_contig_idx = -1;
  12185. } else if (curr_contig_idx < 0) {
  12186. curr_contig_idx = i;
  12187. }
  12188. int seq_idx = 0;
  12189. for (const llama_seq_id it : kv_cells[i].seq_id) {
  12190. if (seq_idx >= view->n_seq_max) {
  12191. break;
  12192. }
  12193. cs_curr[seq_idx] = it;
  12194. seq_idx++;
  12195. }
  12196. if (seq_idx != 0) {
  12197. used_cells++;
  12198. }
  12199. for (; seq_idx < view->n_seq_max; seq_idx++) {
  12200. cs_curr[seq_idx] = -1;
  12201. }
  12202. }
  12203. if (curr_contig_idx >= 0 && kv_cells.size() - curr_contig_idx > max_contig) {
  12204. max_contig_idx = curr_contig_idx;
  12205. max_contig = kv_cells.size() - curr_contig_idx;
  12206. }
  12207. view->max_contiguous = max_contig;
  12208. view->max_contiguous_idx = max_contig_idx;
  12209. view->token_count = token_count;
  12210. view->used_cells = used_cells;
  12211. if (uint32_t(used_cells) != ctx->kv_self.used) {
  12212. LLAMA_LOG_ERROR("%s: used cells mismatch. kv_cache says %d but we calculated %d\n",
  12213. __func__, ctx->kv_self.used, used_cells);
  12214. }
  12215. }
  12216. int32_t llama_get_kv_cache_token_count(const struct llama_context * ctx) {
  12217. int result = 0;
  12218. for (uint32_t i = 0; i < ctx->kv_self.size; i++) {
  12219. result += ctx->kv_self.cells[i].seq_id.size();
  12220. }
  12221. return result;
  12222. }
  12223. int32_t llama_get_kv_cache_used_cells(const struct llama_context * ctx) {
  12224. return ctx->kv_self.used;
  12225. }
  12226. void llama_kv_cache_clear(struct llama_context * ctx) {
  12227. llama_kv_cache_clear(ctx->kv_self);
  12228. }
  12229. bool llama_kv_cache_seq_rm(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
  12230. return llama_kv_cache_seq_rm(ctx->kv_self, seq_id, p0, p1);
  12231. }
  12232. 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) {
  12233. if (seq_id_src == seq_id_dst) {
  12234. return;
  12235. }
  12236. llama_kv_cache_seq_cp(ctx->kv_self, seq_id_src, seq_id_dst, p0, p1);
  12237. }
  12238. void llama_kv_cache_seq_keep(struct llama_context * ctx, llama_seq_id seq_id) {
  12239. llama_kv_cache_seq_keep(ctx->kv_self, seq_id);
  12240. }
  12241. void llama_kv_cache_seq_add(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos delta) {
  12242. if (delta == 0) {
  12243. return;
  12244. }
  12245. llama_kv_cache_seq_add(ctx->kv_self, seq_id, p0, p1, delta);
  12246. }
  12247. void llama_kv_cache_seq_div(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) {
  12248. if (d == 1) {
  12249. return;
  12250. }
  12251. llama_kv_cache_seq_div(ctx->kv_self, seq_id, p0, p1, d);
  12252. }
  12253. llama_pos llama_kv_cache_seq_pos_max(struct llama_context * ctx, llama_seq_id seq_id) {
  12254. return llama_kv_cache_seq_pos_max(ctx->kv_self, seq_id);
  12255. }
  12256. void llama_kv_cache_defrag(struct llama_context * ctx) {
  12257. llama_kv_cache_defrag(ctx->kv_self);
  12258. }
  12259. void llama_kv_cache_update(struct llama_context * ctx) {
  12260. llama_kv_cache_update_internal(*ctx);
  12261. }
  12262. // Returns the *maximum* size of the state
  12263. size_t llama_get_state_size(const struct llama_context * ctx) {
  12264. const auto & cparams = ctx->cparams;
  12265. const auto & hparams = ctx->model.hparams;
  12266. // we don't know size of rng until we actually serialize it. so reserve more than enough memory for its serialized state.
  12267. // for reference, std::mt19937(1337) serializes to 6701 bytes.
  12268. const size_t s_rng_size = sizeof(size_t);
  12269. const size_t s_rng = LLAMA_MAX_RNG_STATE;
  12270. const size_t s_n_outputs = sizeof(size_t);
  12271. // assume worst case for outputs although only currently set ones are serialized
  12272. const size_t s_output_pos = ctx->cparams.n_batch * sizeof(int32_t);
  12273. const size_t s_logits_size = sizeof(size_t);
  12274. const size_t s_logits = ctx->logits_size ? cparams.n_batch * hparams.n_vocab * sizeof(float) : 0;
  12275. const size_t s_embedding_size = sizeof(size_t);
  12276. const size_t s_embedding = ctx->embd_size ? cparams.n_batch * hparams.n_embd * sizeof(float) : 0;
  12277. const size_t s_kv_buf_size = sizeof(size_t);
  12278. const size_t s_kv_head = sizeof(uint32_t);
  12279. const size_t s_kv_size = sizeof(uint32_t);
  12280. const size_t s_kv_used = sizeof(uint32_t);
  12281. const size_t s_kv = ctx->kv_self.total_size();
  12282. const size_t s_kv_cell = sizeof(llama_pos) + sizeof(size_t) + cparams.n_seq_max*sizeof(llama_seq_id);
  12283. const size_t s_kv_cells = ctx->kv_self.size * s_kv_cell;
  12284. const size_t s_total = (
  12285. + s_rng_size
  12286. + s_rng
  12287. + s_n_outputs
  12288. + s_output_pos
  12289. + s_logits_size
  12290. + s_logits
  12291. + s_embedding_size
  12292. + s_embedding
  12293. + s_kv_buf_size
  12294. + s_kv_head
  12295. + s_kv_size
  12296. + s_kv_used
  12297. + s_kv
  12298. + s_kv_cells
  12299. );
  12300. return s_total;
  12301. }
  12302. // llama_context_data
  12303. struct llama_data_context {
  12304. virtual void write(const void * src, size_t size) = 0;
  12305. virtual size_t get_size_written() = 0;
  12306. virtual ~llama_data_context() = default;
  12307. };
  12308. struct llama_data_buffer_context : llama_data_context {
  12309. uint8_t * ptr;
  12310. size_t size_written = 0;
  12311. llama_data_buffer_context(uint8_t * p) : ptr(p) {}
  12312. void write(const void * src, size_t size) override {
  12313. memcpy(ptr, src, size);
  12314. ptr += size;
  12315. size_written += size;
  12316. }
  12317. size_t get_size_written() override {
  12318. return size_written;
  12319. }
  12320. };
  12321. struct llama_data_file_context : llama_data_context {
  12322. llama_file * file;
  12323. size_t size_written = 0;
  12324. llama_data_file_context(llama_file * f) : file(f) {}
  12325. void write(const void * src, size_t size) override {
  12326. file->write_raw(src, size);
  12327. size_written += size;
  12328. }
  12329. size_t get_size_written() override {
  12330. return size_written;
  12331. }
  12332. };
  12333. /** copy state data into either a buffer or file depending on the passed in context
  12334. *
  12335. * file context:
  12336. * llama_file file("/path", "wb");
  12337. * llama_data_file_context data_ctx(&file);
  12338. * llama_copy_state_data(ctx, &data_ctx);
  12339. *
  12340. * buffer context:
  12341. * std::vector<uint8_t> buf(max_size, 0);
  12342. * llama_data_buffer_context data_ctx(&buf.data());
  12343. * llama_copy_state_data(ctx, &data_ctx);
  12344. *
  12345. */
  12346. static void llama_copy_state_data_internal(struct llama_context * ctx, llama_data_context * data_ctx) {
  12347. // copy rng
  12348. {
  12349. std::ostringstream rng_ss;
  12350. rng_ss << ctx->rng;
  12351. const std::string & rng_str = rng_ss.str();
  12352. const size_t rng_size = rng_str.size();
  12353. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  12354. data_ctx->write(&rng_size, sizeof(rng_size));
  12355. data_ctx->write(rng_str.data(), rng_size);
  12356. }
  12357. // copy outputs
  12358. {
  12359. // Can't use ctx->n_outputs because it's not for the
  12360. // entire last batch when n_ubatch is smaller than n_batch
  12361. size_t n_outputs = 0;
  12362. // copy output ids
  12363. {
  12364. std::vector<int32_t> output_pos;
  12365. const size_t n_batch = ctx->cparams.n_batch;
  12366. const auto & output_ids = ctx->output_ids;
  12367. output_pos.resize(ctx->output_size);
  12368. // build a more compact representation of the output ids
  12369. for (size_t i = 0; i < n_batch; ++i) {
  12370. // map an output id to a position in the batch
  12371. int32_t pos = output_ids[i];
  12372. if (pos >= 0) {
  12373. if ((size_t) pos >= n_outputs) {
  12374. n_outputs = pos + 1;
  12375. }
  12376. GGML_ASSERT((size_t) pos < ctx->output_size);
  12377. output_pos[pos] = i;
  12378. }
  12379. }
  12380. data_ctx->write(&n_outputs, sizeof(n_outputs));
  12381. if (n_outputs) {
  12382. data_ctx->write(output_pos.data(), n_outputs * sizeof(int32_t));
  12383. }
  12384. }
  12385. // copy logits
  12386. {
  12387. const size_t logits_size = std::min(ctx->logits_size, n_outputs * ctx->model.hparams.n_vocab);
  12388. data_ctx->write(&logits_size, sizeof(logits_size));
  12389. if (logits_size) {
  12390. data_ctx->write(ctx->logits, logits_size * sizeof(float));
  12391. }
  12392. }
  12393. // copy embeddings
  12394. {
  12395. const size_t embeddings_size = std::min(ctx->embd_size, n_outputs * ctx->model.hparams.n_embd);
  12396. data_ctx->write(&embeddings_size, sizeof(embeddings_size));
  12397. if (embeddings_size) {
  12398. data_ctx->write(ctx->embd, embeddings_size * sizeof(float));
  12399. }
  12400. }
  12401. }
  12402. // copy kv cache
  12403. {
  12404. const auto & kv_self = ctx->kv_self;
  12405. const auto & hparams = ctx->model.hparams;
  12406. const uint32_t n_layer = hparams.n_layer;
  12407. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  12408. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  12409. // NOTE: kv_size and kv_buf_size are mostly used for sanity checks
  12410. const uint32_t kv_head = llama_kv_cache_cell_max(kv_self);
  12411. const uint32_t kv_size = kv_self.size;
  12412. const size_t kv_buf_size = kv_self.total_size() / (kv_size ? kv_size : 1) * kv_head;
  12413. const uint32_t kv_used = kv_self.used;
  12414. data_ctx->write(&kv_buf_size, sizeof(kv_buf_size));
  12415. data_ctx->write(&kv_head, sizeof(kv_head));
  12416. data_ctx->write(&kv_size, sizeof(kv_size));
  12417. data_ctx->write(&kv_used, sizeof(kv_used));
  12418. if (kv_buf_size) {
  12419. const size_t pre_kv_buf_size = data_ctx->get_size_written();
  12420. std::vector<uint8_t> tmp_buf;
  12421. for (int il = 0; il < (int) n_layer; ++il) {
  12422. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_head);
  12423. tmp_buf.resize(k_size);
  12424. ggml_backend_tensor_get(kv_self.k_l[il], tmp_buf.data(), 0, tmp_buf.size());
  12425. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  12426. if (kv_self.recurrent) {
  12427. // v is contiguous for recurrent models
  12428. // TODO: use other tensors for state models than k and v
  12429. const size_t v_size = ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa*kv_head);
  12430. tmp_buf.resize(v_size);
  12431. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), 0, tmp_buf.size());
  12432. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  12433. continue;
  12434. }
  12435. // v is not contiguous, copy row by row
  12436. const size_t v_row_size = ggml_row_size(kv_self.v_l[il]->type, kv_head);
  12437. const size_t v_row_stride = ggml_row_size(kv_self.v_l[il]->type, kv_size);
  12438. tmp_buf.resize(v_row_size);
  12439. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  12440. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), ir*v_row_stride, tmp_buf.size());
  12441. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  12442. }
  12443. }
  12444. GGML_ASSERT(kv_buf_size == data_ctx->get_size_written() - pre_kv_buf_size);
  12445. }
  12446. for (uint32_t i = 0; i < kv_head; ++i) {
  12447. const auto & cell = kv_self.cells[i];
  12448. const llama_pos pos = cell.pos;
  12449. const size_t seq_id_size = cell.seq_id.size();
  12450. data_ctx->write(&pos, sizeof(pos));
  12451. data_ctx->write(&seq_id_size, sizeof(seq_id_size));
  12452. for (auto seq_id : cell.seq_id) {
  12453. data_ctx->write(&seq_id, sizeof(seq_id));
  12454. }
  12455. }
  12456. }
  12457. }
  12458. size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dst) {
  12459. llama_data_buffer_context data_ctx(dst);
  12460. llama_copy_state_data_internal(ctx, &data_ctx);
  12461. return data_ctx.get_size_written();
  12462. }
  12463. // Sets the state reading from the specified source address
  12464. size_t llama_set_state_data(struct llama_context * ctx, const uint8_t * src) {
  12465. const uint8_t * inp = src;
  12466. // set rng
  12467. {
  12468. size_t rng_size;
  12469. memcpy(&rng_size, inp, sizeof(rng_size)); inp += sizeof(rng_size);
  12470. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  12471. std::string rng_str((const char *)inp, rng_size); inp += rng_size;
  12472. std::istringstream rng_ss(rng_str);
  12473. rng_ss >> ctx->rng;
  12474. GGML_ASSERT(!rng_ss.fail());
  12475. }
  12476. // set output ids
  12477. {
  12478. size_t n_outputs;
  12479. std::vector<int32_t> output_pos;
  12480. memcpy(&n_outputs, inp, sizeof(n_outputs)); inp += sizeof(n_outputs);
  12481. GGML_ASSERT(n_outputs <= llama_output_reserve(*ctx, n_outputs));
  12482. if (n_outputs) {
  12483. output_pos.resize(n_outputs);
  12484. memcpy(output_pos.data(), inp, n_outputs * sizeof(int32_t));
  12485. inp += n_outputs * sizeof(int32_t);
  12486. for (int32_t i = 0; i < (int32_t) output_pos.size(); ++i) {
  12487. int32_t id = output_pos[i];
  12488. GGML_ASSERT((uint32_t) id < ctx->cparams.n_batch);
  12489. ctx->output_ids[id] = i;
  12490. }
  12491. }
  12492. }
  12493. // set logits
  12494. {
  12495. size_t logits_size;
  12496. memcpy(&logits_size, inp, sizeof(logits_size)); inp += sizeof(logits_size);
  12497. GGML_ASSERT(ctx->logits_size >= logits_size);
  12498. if (logits_size) {
  12499. memcpy(ctx->logits, inp, logits_size * sizeof(float));
  12500. inp += logits_size * sizeof(float);
  12501. }
  12502. }
  12503. // set embeddings
  12504. {
  12505. size_t embeddings_size;
  12506. memcpy(&embeddings_size, inp, sizeof(embeddings_size)); inp += sizeof(embeddings_size);
  12507. GGML_ASSERT(ctx->embd_size >= embeddings_size);
  12508. if (embeddings_size) {
  12509. memcpy(ctx->embd, inp, embeddings_size * sizeof(float));
  12510. inp += embeddings_size * sizeof(float);
  12511. }
  12512. }
  12513. // set kv cache
  12514. {
  12515. const auto & kv_self = ctx->kv_self;
  12516. const auto & hparams = ctx->model.hparams;
  12517. const uint32_t n_layer = hparams.n_layer;
  12518. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  12519. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  12520. size_t kv_buf_size;
  12521. uint32_t kv_head;
  12522. uint32_t kv_size;
  12523. uint32_t kv_used;
  12524. memcpy(&kv_buf_size, inp, sizeof(kv_buf_size)); inp += sizeof(kv_buf_size);
  12525. memcpy(&kv_head, inp, sizeof(kv_head)); inp += sizeof(kv_head);
  12526. memcpy(&kv_size, inp, sizeof(kv_size)); inp += sizeof(kv_size);
  12527. memcpy(&kv_used, inp, sizeof(kv_used)); inp += sizeof(kv_used);
  12528. if (kv_self.size != kv_size) {
  12529. // the KV cache needs to be big enough to load all the KV cells from the saved state
  12530. GGML_ASSERT(kv_self.size >= kv_head);
  12531. 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",
  12532. __func__, kv_head, kv_size, kv_self.size);
  12533. }
  12534. if (kv_buf_size) {
  12535. const size_t pre_kv_buf_size = inp - src;
  12536. GGML_ASSERT(kv_self.total_size() >= kv_buf_size);
  12537. for (int il = 0; il < (int) n_layer; ++il) {
  12538. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_head);
  12539. ggml_backend_tensor_set(kv_self.k_l[il], inp, 0, k_size);
  12540. inp += k_size;
  12541. if (kv_self.recurrent) {
  12542. // v is contiguous for recurrent models
  12543. // TODO: use other tensors for state models than k and v
  12544. const size_t v_size = ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa*kv_head);
  12545. ggml_backend_tensor_set(kv_self.v_l[il], inp, 0, v_size);
  12546. inp += v_size;
  12547. continue;
  12548. }
  12549. // v is not contiguous, copy row by row
  12550. const size_t v_row_size = ggml_row_size(kv_self.v_l[il]->type, kv_head);
  12551. const size_t v_row_stride = ggml_row_size(kv_self.v_l[il]->type, kv_self.size);
  12552. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  12553. ggml_backend_tensor_set(kv_self.v_l[il], inp, ir*v_row_stride, v_row_size);
  12554. inp += v_row_size;
  12555. }
  12556. }
  12557. GGML_ASSERT(kv_buf_size == inp - src - pre_kv_buf_size);
  12558. }
  12559. llama_kv_cache_clear(ctx);
  12560. ctx->kv_self.head = kv_head;
  12561. ctx->kv_self.used = kv_used;
  12562. for (uint32_t i = 0; i < kv_head; ++i) {
  12563. llama_pos pos;
  12564. size_t seq_id_size;
  12565. memcpy(&pos, inp, sizeof(pos)); inp += sizeof(pos);
  12566. memcpy(&seq_id_size, inp, sizeof(seq_id_size)); inp += sizeof(seq_id_size);
  12567. ctx->kv_self.cells[i].pos = pos;
  12568. llama_seq_id seq_id;
  12569. for (size_t j = 0; j < seq_id_size; ++j) {
  12570. memcpy(&seq_id, inp, sizeof(seq_id)); inp += sizeof(seq_id);
  12571. ctx->kv_self.cells[i].seq_id.insert(seq_id);
  12572. }
  12573. }
  12574. }
  12575. const size_t nread = inp - src;
  12576. const size_t max_size = llama_get_state_size(ctx);
  12577. GGML_ASSERT(nread <= max_size);
  12578. return nread;
  12579. }
  12580. static bool llama_load_session_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) {
  12581. llama_file file(path_session, "rb");
  12582. // sanity checks
  12583. {
  12584. const uint32_t magic = file.read_u32();
  12585. const uint32_t version = file.read_u32();
  12586. if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
  12587. LLAMA_LOG_ERROR("%s : unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
  12588. return false;
  12589. }
  12590. llama_hparams session_hparams;
  12591. file.read_raw(&session_hparams, sizeof(llama_hparams));
  12592. if (session_hparams != ctx->model.hparams) {
  12593. LLAMA_LOG_INFO("%s : model hparams didn't match from session file!\n", __func__);
  12594. return false;
  12595. }
  12596. }
  12597. // load the prompt
  12598. {
  12599. const uint32_t n_token_count = file.read_u32();
  12600. if (n_token_count > n_token_capacity) {
  12601. LLAMA_LOG_ERROR("%s : token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  12602. return false;
  12603. }
  12604. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  12605. *n_token_count_out = n_token_count;
  12606. }
  12607. // restore the context state
  12608. {
  12609. const size_t n_state_size_cur = file.size - file.tell();
  12610. const size_t n_state_size_max = llama_get_state_size(ctx);
  12611. if (n_state_size_cur > n_state_size_max) {
  12612. 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);
  12613. return false;
  12614. }
  12615. std::vector<uint8_t> state_data(n_state_size_max);
  12616. file.read_raw(state_data.data(), n_state_size_cur);
  12617. llama_set_state_data(ctx, state_data.data());
  12618. }
  12619. return true;
  12620. }
  12621. 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) {
  12622. try {
  12623. return llama_load_session_file_internal(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  12624. } catch (const std::exception & err) {
  12625. LLAMA_LOG_ERROR("error loading session file: %s\n", err.what());
  12626. return false;
  12627. }
  12628. }
  12629. bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  12630. llama_file file(path_session, "wb");
  12631. file.write_u32(LLAMA_SESSION_MAGIC);
  12632. file.write_u32(LLAMA_SESSION_VERSION);
  12633. file.write_raw(&ctx->model.hparams, sizeof(llama_hparams));
  12634. // save the prompt
  12635. file.write_u32((uint32_t) n_token_count);
  12636. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  12637. // save the context state using stream saving
  12638. llama_data_file_context data_ctx(&file);
  12639. llama_copy_state_data_internal(ctx, &data_ctx);
  12640. return true;
  12641. }
  12642. void llama_set_n_threads(struct llama_context * ctx, uint32_t n_threads, uint32_t n_threads_batch) {
  12643. ctx->cparams.n_threads = n_threads;
  12644. ctx->cparams.n_threads_batch = n_threads_batch;
  12645. }
  12646. void llama_set_abort_callback(struct llama_context * ctx, bool (*abort_callback)(void * data), void * abort_callback_data) {
  12647. ctx->abort_callback = abort_callback;
  12648. ctx->abort_callback_data = abort_callback_data;
  12649. }
  12650. void llama_set_causal_attn(struct llama_context * ctx, bool causal_attn) {
  12651. ctx->cparams.causal_attn = causal_attn;
  12652. }
  12653. struct llama_batch llama_batch_get_one(
  12654. llama_token * tokens,
  12655. int32_t n_tokens,
  12656. llama_pos pos_0,
  12657. llama_seq_id seq_id) {
  12658. return {
  12659. /*n_tokens =*/ n_tokens,
  12660. /*tokens =*/ tokens,
  12661. /*embd =*/ nullptr,
  12662. /*pos =*/ nullptr,
  12663. /*n_seq_id =*/ nullptr,
  12664. /*seq_id =*/ nullptr,
  12665. /*logits =*/ nullptr,
  12666. /*all_pos_0 =*/ pos_0,
  12667. /*all_pos_1 =*/ 1,
  12668. /*all_seq_id =*/ seq_id,
  12669. };
  12670. }
  12671. struct llama_batch llama_batch_init(int32_t n_tokens_alloc, int32_t embd, int32_t n_seq_max) {
  12672. llama_batch batch = { 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, 0, 0, 0, };
  12673. if (embd) {
  12674. batch.embd = (float *) malloc(sizeof(float) * n_tokens_alloc * embd);
  12675. } else {
  12676. batch.token = (llama_token *) malloc(sizeof(llama_token) * n_tokens_alloc);
  12677. }
  12678. batch.pos = (llama_pos *) malloc(sizeof(llama_pos) * n_tokens_alloc);
  12679. batch.n_seq_id = (int32_t *) malloc(sizeof(int32_t) * n_tokens_alloc);
  12680. batch.seq_id = (llama_seq_id **) malloc(sizeof(llama_seq_id *) * (n_tokens_alloc + 1));
  12681. for (int i = 0; i < n_tokens_alloc; ++i) {
  12682. batch.seq_id[i] = (llama_seq_id *) malloc(sizeof(llama_seq_id) * n_seq_max);
  12683. }
  12684. batch.seq_id[n_tokens_alloc] = nullptr;
  12685. batch.logits = (int8_t *) malloc(sizeof(int8_t) * n_tokens_alloc);
  12686. return batch;
  12687. }
  12688. void llama_batch_free(struct llama_batch batch) {
  12689. if (batch.token) free(batch.token);
  12690. if (batch.embd) free(batch.embd);
  12691. if (batch.pos) free(batch.pos);
  12692. if (batch.n_seq_id) free(batch.n_seq_id);
  12693. if (batch.seq_id) {
  12694. for (int i = 0; batch.seq_id[i] != nullptr; ++i) {
  12695. free(batch.seq_id[i]);
  12696. }
  12697. free(batch.seq_id);
  12698. }
  12699. if (batch.logits) free(batch.logits);
  12700. }
  12701. int32_t llama_decode(
  12702. struct llama_context * ctx,
  12703. struct llama_batch batch) {
  12704. const int ret = llama_decode_internal(*ctx, batch);
  12705. if (ret < 0) {
  12706. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  12707. }
  12708. return ret;
  12709. }
  12710. void llama_synchronize(struct llama_context * ctx) {
  12711. ggml_backend_sched_synchronize(ctx->sched);
  12712. // FIXME: if multiple single tokens are evaluated without a synchronization,
  12713. // the stats will be added to the prompt evaluation stats
  12714. // this should only happen when using batch size 1 to evaluate a batch
  12715. // add the evaluation to the stats
  12716. if (ctx->n_queued_tokens == 1) {
  12717. ctx->t_eval_us += ggml_time_us() - ctx->t_compute_start_us;
  12718. ctx->n_eval++;
  12719. } else if (ctx->n_queued_tokens > 1) {
  12720. ctx->t_p_eval_us += ggml_time_us() - ctx->t_compute_start_us;
  12721. ctx->n_p_eval += ctx->n_queued_tokens;
  12722. }
  12723. // get a more accurate load time, upon first eval
  12724. if (ctx->n_queued_tokens > 0 && !ctx->has_evaluated_once) {
  12725. ctx->t_load_us = ggml_time_us() - ctx->t_start_us;
  12726. ctx->has_evaluated_once = true;
  12727. }
  12728. ctx->n_queued_tokens = 0;
  12729. ctx->t_compute_start_us = 0;
  12730. }
  12731. float * llama_get_logits(struct llama_context * ctx) {
  12732. llama_synchronize(ctx);
  12733. return ctx->logits;
  12734. }
  12735. float * llama_get_logits_ith(struct llama_context * ctx, int32_t i) {
  12736. llama_synchronize(ctx);
  12737. try {
  12738. if (ctx->logits == nullptr) {
  12739. throw std::runtime_error("no logits");
  12740. }
  12741. if ((size_t) i >= ctx->output_ids.size()) {
  12742. throw std::runtime_error(format("out of range [0, %lu)", ctx->output_ids.size()));
  12743. }
  12744. const int32_t j = ctx->output_ids[i];
  12745. if (j < 0) {
  12746. throw std::runtime_error(format("batch.logits[%d] != true", i));
  12747. }
  12748. if ((size_t) j >= ctx->output_size) {
  12749. // This should not happen
  12750. throw std::runtime_error(format("corrupt output buffer (j=%d, output_size=%lu)", j, ctx->output_size));
  12751. }
  12752. return ctx->logits + j*ctx->model.hparams.n_vocab;
  12753. } catch (const std::exception & err) {
  12754. LLAMA_LOG_ERROR("%s: invalid logits id %d, reason: %s\n", __func__, i, err.what());
  12755. #ifndef NDEBUG
  12756. GGML_ASSERT(false);
  12757. #endif
  12758. return nullptr;
  12759. }
  12760. }
  12761. float * llama_get_embeddings(struct llama_context * ctx) {
  12762. llama_synchronize(ctx);
  12763. return ctx->embd;
  12764. }
  12765. float * llama_get_embeddings_ith(struct llama_context * ctx, int32_t i) {
  12766. llama_synchronize(ctx);
  12767. try {
  12768. if (ctx->embd == nullptr) {
  12769. throw std::runtime_error("no embeddings");
  12770. }
  12771. if ((size_t) i >= ctx->output_ids.size()) {
  12772. throw std::runtime_error(format("out of range [0, %lu)", ctx->output_ids.size()));
  12773. }
  12774. const int32_t j = ctx->output_ids[i];
  12775. if (j < 0) {
  12776. throw std::runtime_error(format("batch.logits[%d] != true", i));
  12777. }
  12778. if ((size_t) j >= ctx->output_size) {
  12779. // This should not happen
  12780. throw std::runtime_error(format("corrupt output buffer (j=%d, output_size=%lu)", j, ctx->output_size));
  12781. }
  12782. return ctx->embd + j*ctx->model.hparams.n_embd;
  12783. } catch (const std::exception & err) {
  12784. LLAMA_LOG_ERROR("%s: invalid embeddings id %d, reason: %s\n", __func__, i, err.what());
  12785. #ifndef NDEBUG
  12786. GGML_ASSERT(false);
  12787. #endif
  12788. return nullptr;
  12789. }
  12790. }
  12791. float * llama_get_embeddings_seq(struct llama_context * ctx, llama_seq_id seq_id) {
  12792. llama_synchronize(ctx);
  12793. auto it = ctx->embd_seq.find(seq_id);
  12794. if (it == ctx->embd_seq.end()) {
  12795. return nullptr;
  12796. }
  12797. return it->second.data();
  12798. }
  12799. const char * llama_token_get_text(const struct llama_model * model, llama_token token) {
  12800. GGML_ASSERT(model->vocab.type != LLAMA_VOCAB_TYPE_NONE);
  12801. return model->vocab.id_to_token[token].text.c_str();
  12802. }
  12803. float llama_token_get_score(const struct llama_model * model, llama_token token) {
  12804. GGML_ASSERT(model->vocab.type != LLAMA_VOCAB_TYPE_NONE);
  12805. return model->vocab.id_to_token[token].score;
  12806. }
  12807. llama_token_type llama_token_get_type(const struct llama_model * model, llama_token token) {
  12808. GGML_ASSERT(model->vocab.type != LLAMA_VOCAB_TYPE_NONE);
  12809. return model->vocab.id_to_token[token].type;
  12810. }
  12811. llama_token llama_token_bos(const struct llama_model * model) {
  12812. return model->vocab.special_bos_id;
  12813. }
  12814. llama_token llama_token_eos(const struct llama_model * model) {
  12815. return model->vocab.special_eos_id;
  12816. }
  12817. llama_token llama_token_nl(const struct llama_model * model) {
  12818. return model->vocab.linefeed_id;
  12819. }
  12820. int32_t llama_add_bos_token(const struct llama_model * model) {
  12821. return model->vocab.special_add_bos;
  12822. }
  12823. int32_t llama_add_eos_token(const struct llama_model * model) {
  12824. return model->vocab.special_add_eos;
  12825. }
  12826. llama_token llama_token_prefix(const struct llama_model * model) {
  12827. return model->vocab.special_prefix_id;
  12828. }
  12829. llama_token llama_token_middle(const struct llama_model * model) {
  12830. return model->vocab.special_middle_id;
  12831. }
  12832. llama_token llama_token_suffix(const struct llama_model * model) {
  12833. return model->vocab.special_suffix_id;
  12834. }
  12835. llama_token llama_token_eot(const struct llama_model * model) {
  12836. return model->vocab.special_eot_id;
  12837. }
  12838. int32_t llama_tokenize(
  12839. const struct llama_model * model,
  12840. const char * text,
  12841. int32_t text_len,
  12842. llama_token * tokens,
  12843. int32_t n_tokens_max,
  12844. bool add_bos,
  12845. bool special) {
  12846. auto res = llama_tokenize_internal(model->vocab, std::string(text, text_len), add_bos, special);
  12847. if (n_tokens_max < (int) res.size()) {
  12848. // LLAMA_LOG_ERROR("%s: too many tokens\n", __func__);
  12849. return -((int) res.size());
  12850. }
  12851. for (size_t i = 0; i < res.size(); i++) {
  12852. tokens[i] = res[i];
  12853. }
  12854. return res.size();
  12855. }
  12856. static std::string llama_decode_text(const std::string & text) {
  12857. std::string decoded_text;
  12858. auto unicode_sequences = unicode_cpts_from_utf8(text);
  12859. for (auto & unicode_sequence : unicode_sequences) {
  12860. decoded_text += unicode_utf8_to_byte(unicode_cpt_to_utf8(unicode_sequence));
  12861. }
  12862. return decoded_text;
  12863. }
  12864. // does not write null-terminator to buf
  12865. int32_t llama_token_to_piece(const struct llama_model * model, llama_token token, char * buf, int32_t length) {
  12866. if (0 <= token && token < llama_n_vocab(model)) {
  12867. switch (llama_vocab_get_type(model->vocab)) {
  12868. case LLAMA_VOCAB_TYPE_WPM:
  12869. case LLAMA_VOCAB_TYPE_SPM: {
  12870. // NOTE: we accept all unsupported token types,
  12871. // suppressing them like CONTROL tokens.
  12872. if (llama_is_normal_token(model->vocab, token)) {
  12873. std::string result = model->vocab.id_to_token[token].text;
  12874. llama_unescape_whitespace(result);
  12875. if (length < (int) result.length()) {
  12876. return -(int) result.length();
  12877. }
  12878. memcpy(buf, result.c_str(), result.length());
  12879. return result.length();
  12880. } else if (llama_is_user_defined_token(model->vocab, token)) {
  12881. std::string result = model->vocab.id_to_token[token].text;
  12882. if (length < (int) result.length()) {
  12883. return -(int) result.length();
  12884. }
  12885. memcpy(buf, result.c_str(), result.length());
  12886. return result.length();
  12887. } else if (llama_is_unknown_token(model->vocab, token)) { // NOLINT
  12888. if (length < 3) {
  12889. return -3;
  12890. }
  12891. memcpy(buf, "\xe2\x96\x85", 3);
  12892. return 3;
  12893. } else if (llama_is_control_token(model->vocab, token)) {
  12894. ;
  12895. } else if (llama_is_byte_token(model->vocab, token)) {
  12896. if (length < 1) {
  12897. return -1;
  12898. }
  12899. buf[0] = llama_token_to_byte(model->vocab, token);
  12900. return 1;
  12901. }
  12902. break;
  12903. }
  12904. case LLAMA_VOCAB_TYPE_BPE: {
  12905. // NOTE: we accept all unsupported token types,
  12906. // suppressing them like CONTROL tokens.
  12907. if (llama_is_normal_token(model->vocab, token)) {
  12908. std::string result = model->vocab.id_to_token[token].text;
  12909. result = llama_decode_text(result);
  12910. if (length < (int) result.length()) {
  12911. return -(int) result.length();
  12912. }
  12913. memcpy(buf, result.c_str(), result.length());
  12914. return result.length();
  12915. } else if (llama_is_user_defined_token(model->vocab, token)) {
  12916. std::string result = model->vocab.id_to_token[token].text;
  12917. if (length < (int) result.length()) {
  12918. return -(int) result.length();
  12919. }
  12920. memcpy(buf, result.c_str(), result.length());
  12921. return result.length();
  12922. } else if (llama_is_control_token(model->vocab, token)) {
  12923. ;
  12924. }
  12925. break;
  12926. }
  12927. default:
  12928. GGML_ASSERT(false);
  12929. }
  12930. }
  12931. return 0;
  12932. }
  12933. // trim whitespace from the beginning and end of a string
  12934. static std::string trim(const std::string & str) {
  12935. size_t start = 0;
  12936. size_t end = str.size();
  12937. while (start < end && isspace(str[start])) {
  12938. start += 1;
  12939. }
  12940. while (end > start && isspace(str[end - 1])) {
  12941. end -= 1;
  12942. }
  12943. return str.substr(start, end - start);
  12944. }
  12945. // Simple version of "llama_apply_chat_template" that only works with strings
  12946. // This function uses heuristic checks to determine commonly used template. It is not a jinja parser.
  12947. static int32_t llama_chat_apply_template_internal(
  12948. const std::string & tmpl,
  12949. const std::vector<const llama_chat_message *> & chat,
  12950. std::string & dest, bool add_ass) {
  12951. // Taken from the research: https://github.com/ggerganov/llama.cpp/issues/5527
  12952. std::stringstream ss;
  12953. if (tmpl == "chatml" || tmpl.find("<|im_start|>") != std::string::npos) {
  12954. // chatml template
  12955. for (auto message : chat) {
  12956. ss << "<|im_start|>" << message->role << "\n" << message->content << "<|im_end|>\n";
  12957. }
  12958. if (add_ass) {
  12959. ss << "<|im_start|>assistant\n";
  12960. }
  12961. } else if (tmpl == "llama2" || tmpl.find("[INST]") != std::string::npos) {
  12962. // llama2 template and its variants
  12963. // [variant] support system message
  12964. bool support_system_message = tmpl.find("<<SYS>>") != std::string::npos;
  12965. // [variant] space before + after response
  12966. bool space_around_response = tmpl.find("' ' + eos_token") != std::string::npos;
  12967. // [variant] add BOS inside history
  12968. bool add_bos_inside_history = tmpl.find("bos_token + '[INST]") != std::string::npos;
  12969. // [variant] trim spaces from the input message
  12970. bool strip_message = tmpl.find("content.strip()") != std::string::npos;
  12971. // construct the prompt
  12972. bool is_inside_turn = true; // skip BOS at the beginning
  12973. ss << "[INST] ";
  12974. for (auto message : chat) {
  12975. std::string content = strip_message ? trim(message->content) : message->content;
  12976. std::string role(message->role);
  12977. if (!is_inside_turn) {
  12978. is_inside_turn = true;
  12979. ss << (add_bos_inside_history ? "<s>[INST] " : "[INST] ");
  12980. }
  12981. if (role == "system") {
  12982. if (support_system_message) {
  12983. ss << "<<SYS>>\n" << content << "\n<</SYS>>\n\n";
  12984. } else {
  12985. // if the model does not support system message, we still include it in the first message, but without <<SYS>>
  12986. ss << content << "\n";
  12987. }
  12988. } else if (role == "user") {
  12989. ss << content << " [/INST]";
  12990. } else {
  12991. ss << (space_around_response ? " " : "") << content << (space_around_response ? " " : "") << "</s>";
  12992. is_inside_turn = false;
  12993. }
  12994. }
  12995. // llama2 templates seem to not care about "add_generation_prompt"
  12996. } else if (tmpl == "zephyr" || tmpl.find("<|user|>") != std::string::npos) {
  12997. // zephyr template
  12998. for (auto message : chat) {
  12999. ss << "<|" << message->role << "|>" << "\n" << message->content << "<|endoftext|>\n";
  13000. }
  13001. if (add_ass) {
  13002. ss << "<|assistant|>\n";
  13003. }
  13004. } else if (tmpl == "monarch" || tmpl.find("bos_token + message['role']") != std::string::npos) {
  13005. // mlabonne/AlphaMonarch-7B template (the <s> is included inside history)
  13006. for (auto message : chat) {
  13007. std::string bos = (message == chat.front()) ? "" : "<s>"; // skip BOS for first message
  13008. ss << bos << message->role << "\n" << message->content << "</s>\n";
  13009. }
  13010. if (add_ass) {
  13011. ss << "<s>assistant\n";
  13012. }
  13013. } else if (tmpl == "gemma" || tmpl.find("<start_of_turn>") != std::string::npos) {
  13014. // google/gemma-7b-it
  13015. std::string system_prompt = "";
  13016. for (auto message : chat) {
  13017. std::string role(message->role);
  13018. if (role == "system") {
  13019. // there is no system message for gemma, but we will merge it with user prompt, so nothing is broken
  13020. system_prompt = trim(message->content);
  13021. continue;
  13022. }
  13023. // in gemma, "assistant" is "model"
  13024. role = role == "assistant" ? "model" : message->role;
  13025. ss << "<start_of_turn>" << role << "\n";
  13026. if (!system_prompt.empty() && role != "model") {
  13027. ss << system_prompt << "\n\n";
  13028. system_prompt = "";
  13029. }
  13030. ss << trim(message->content) << "<end_of_turn>\n";
  13031. }
  13032. if (add_ass) {
  13033. ss << "<start_of_turn>model\n";
  13034. }
  13035. } else if (tmpl == "orion" || tmpl.find("'\\n\\nAssistant: ' + eos_token") != std::string::npos) {
  13036. // OrionStarAI/Orion-14B-Chat
  13037. std::string system_prompt = "";
  13038. for (auto message : chat) {
  13039. std::string role(message->role);
  13040. if (role == "system") {
  13041. // there is no system message support, we will merge it with user prompt
  13042. system_prompt = message->content;
  13043. continue;
  13044. } else if (role == "user") {
  13045. ss << "Human: ";
  13046. if (!system_prompt.empty()) {
  13047. ss << system_prompt << "\n\n";
  13048. system_prompt = "";
  13049. }
  13050. ss << message->content << "\n\nAssistant: </s>";
  13051. } else {
  13052. ss << message->content << "</s>";
  13053. }
  13054. }
  13055. } else {
  13056. // template not supported
  13057. return -1;
  13058. }
  13059. dest = ss.str();
  13060. return dest.size();
  13061. }
  13062. LLAMA_API int32_t llama_chat_apply_template(
  13063. const struct llama_model * model,
  13064. const char * tmpl,
  13065. const struct llama_chat_message * chat,
  13066. size_t n_msg,
  13067. bool add_ass,
  13068. char * buf,
  13069. int32_t length) {
  13070. std::string curr_tmpl(tmpl == nullptr ? "" : tmpl);
  13071. if (tmpl == nullptr) {
  13072. GGML_ASSERT(model != nullptr);
  13073. // load template from model
  13074. std::vector<char> model_template(2048, 0); // longest known template is about 1200 bytes
  13075. std::string template_key = "tokenizer.chat_template";
  13076. int32_t res = llama_model_meta_val_str(model, template_key.c_str(), model_template.data(), model_template.size());
  13077. if (res < 0) {
  13078. // worst case: there is no information about template, we will use chatml by default
  13079. curr_tmpl = "chatml"; // see llama_chat_apply_template_internal
  13080. } else {
  13081. curr_tmpl = std::string(model_template.data(), model_template.size());
  13082. }
  13083. }
  13084. // format the chat to string
  13085. std::vector<const llama_chat_message *> chat_vec;
  13086. chat_vec.resize(n_msg);
  13087. for (size_t i = 0; i < n_msg; i++) {
  13088. chat_vec[i] = &chat[i];
  13089. }
  13090. std::string formatted_chat;
  13091. int32_t res = llama_chat_apply_template_internal(curr_tmpl, chat_vec, formatted_chat, add_ass);
  13092. if (res < 0) {
  13093. return res;
  13094. }
  13095. if (buf && length > 0) {
  13096. strncpy(buf, formatted_chat.c_str(), length);
  13097. }
  13098. return res;
  13099. }
  13100. LLAMA_API int llama_split_path(char * split_path, size_t maxlen, const char * path_prefix, int split_no, int split_count) {
  13101. static const char * const SPLIT_PATH_FORMAT = "%s-%05d-of-%05d.gguf";
  13102. if (snprintf(split_path, maxlen, SPLIT_PATH_FORMAT, path_prefix, split_no + 1, split_count)) {
  13103. return strlen(split_path);
  13104. }
  13105. return 0;
  13106. }
  13107. int llama_split_prefix(char * dest, size_t maxlen, const char * split_path, int split_no, int split_count) {
  13108. std::string str_split_path(split_path);
  13109. char postfix[32];
  13110. snprintf(postfix, 32, "-%05d-of-%05d.gguf", split_no + 1, split_count);
  13111. std::string str_postfix(postfix);
  13112. // check if dest ends with postfix
  13113. int size_prefix = str_split_path.size() - str_postfix.size();
  13114. if (size_prefix > 0 && str_split_path.find(str_postfix, size_prefix) != std::string::npos) {
  13115. snprintf(dest, std::min((size_t) size_prefix + 1, maxlen), "%s", split_path);
  13116. return size_prefix;
  13117. }
  13118. return 0;
  13119. }
  13120. struct llama_timings llama_get_timings(struct llama_context * ctx) {
  13121. struct llama_timings result = {
  13122. /*.t_start_ms =*/ 1e-3 * ctx->t_start_us,
  13123. /*.t_end_ms =*/ 1.00 * ggml_time_ms(),
  13124. /*.t_load_ms =*/ 1e-3 * ctx->t_load_us,
  13125. /*.t_sample_ms =*/ 1e-3 * ctx->t_sample_us,
  13126. /*.t_p_eval_ms =*/ 1e-3 * ctx->t_p_eval_us,
  13127. /*.t_eval_ms =*/ 1e-3 * ctx->t_eval_us,
  13128. /*.n_sample =*/ std::max(1, ctx->n_sample),
  13129. /*.n_p_eval =*/ std::max(1, ctx->n_p_eval),
  13130. /*.n_eval =*/ std::max(1, ctx->n_eval),
  13131. };
  13132. return result;
  13133. }
  13134. void llama_print_timings(struct llama_context * ctx) {
  13135. const llama_timings timings = llama_get_timings(ctx);
  13136. LLAMA_LOG_INFO("\n");
  13137. LLAMA_LOG_INFO("%s: load time = %10.2f ms\n", __func__, timings.t_load_ms);
  13138. LLAMA_LOG_INFO("%s: sample time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  13139. __func__, timings.t_sample_ms, timings.n_sample, timings.t_sample_ms / timings.n_sample, 1e3 / timings.t_sample_ms * timings.n_sample);
  13140. LLAMA_LOG_INFO("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  13141. __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);
  13142. LLAMA_LOG_INFO("%s: eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  13143. __func__, timings.t_eval_ms, timings.n_eval, timings.t_eval_ms / timings.n_eval, 1e3 / timings.t_eval_ms * timings.n_eval);
  13144. 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));
  13145. }
  13146. void llama_reset_timings(struct llama_context * ctx) {
  13147. ctx->t_start_us = ggml_time_us();
  13148. ctx->t_sample_us = ctx->n_sample = 0;
  13149. ctx->t_eval_us = ctx->n_eval = 0;
  13150. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  13151. }
  13152. const char * llama_print_system_info(void) {
  13153. static std::string s;
  13154. s = "";
  13155. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  13156. s += "AVX_VNNI = " + std::to_string(ggml_cpu_has_avx_vnni()) + " | ";
  13157. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  13158. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  13159. s += "AVX512_VBMI = " + std::to_string(ggml_cpu_has_avx512_vbmi()) + " | ";
  13160. s += "AVX512_VNNI = " + std::to_string(ggml_cpu_has_avx512_vnni()) + " | ";
  13161. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  13162. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  13163. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  13164. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  13165. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  13166. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  13167. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  13168. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  13169. s += "SSSE3 = " + std::to_string(ggml_cpu_has_ssse3()) + " | ";
  13170. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  13171. s += "MATMUL_INT8 = " + std::to_string(ggml_cpu_has_matmul_int8()) + " | ";
  13172. return s.c_str();
  13173. }
  13174. void llama_dump_timing_info_yaml(FILE * stream, const llama_context * ctx) {
  13175. fprintf(stream, "\n");
  13176. fprintf(stream, "###########\n");
  13177. fprintf(stream, "# Timings #\n");
  13178. fprintf(stream, "###########\n");
  13179. fprintf(stream, "\n");
  13180. fprintf(stream, "mst_eval: %.2f # ms / token during generation\n",
  13181. 1.0e-3 * ctx->t_eval_us / ctx->n_eval);
  13182. fprintf(stream, "mst_p_eval: %.2f # ms / token during prompt processing\n",
  13183. 1.0e-3 * ctx->t_p_eval_us / ctx->n_p_eval);
  13184. fprintf(stream, "mst_sample: %.2f # ms / token during sampling\n",
  13185. 1.0e-3 * ctx->t_sample_us / ctx->n_sample);
  13186. fprintf(stream, "n_eval: %d # number of tokens generated (excluding the first one)\n", ctx->n_eval);
  13187. fprintf(stream, "n_p_eval: %d # number of tokens processed in batches at the beginning\n", ctx->n_p_eval);
  13188. fprintf(stream, "n_sample: %d # number of sampled tokens\n", ctx->n_sample);
  13189. fprintf(stream, "t_eval_us: %" PRId64 " # total microseconds spent generating tokens\n", ctx->t_eval_us);
  13190. fprintf(stream, "t_load_us: %" PRId64 " # total microseconds spent loading the model\n", ctx->t_load_us);
  13191. fprintf(stream, "t_p_eval_us: %" PRId64 " # total microseconds spent prompt processing\n", ctx->t_p_eval_us);
  13192. fprintf(stream, "t_sample_us: %" PRId64 " # total microseconds spent sampling\n", ctx->t_sample_us);
  13193. fprintf(stream, "ts_eval: %.2f # tokens / second during generation\n",
  13194. 1.0e6 * ctx->n_eval / ctx->t_eval_us);
  13195. fprintf(stream, "ts_p_eval: %.2f # tokens / second during prompt processing\n",
  13196. 1.0e6 * ctx->n_p_eval / ctx->t_p_eval_us);
  13197. fprintf(stream, "ts_sample: %.2f # tokens / second during sampling\n",
  13198. 1.0e6 * ctx->n_sample / ctx->t_sample_us);
  13199. }
  13200. // For internal test use
  13201. const std::vector<std::pair<std::string, struct ggml_tensor *>> & llama_internal_get_tensor_map(
  13202. struct llama_context * ctx
  13203. ) {
  13204. return ctx->model.tensors_by_name;
  13205. }
  13206. void llama_log_set(ggml_log_callback log_callback, void * user_data) {
  13207. g_state.log_callback = log_callback ? log_callback : llama_log_callback_default;
  13208. g_state.log_callback_user_data = user_data;
  13209. #ifdef GGML_USE_METAL
  13210. ggml_backend_metal_log_set_callback(g_state.log_callback, g_state.log_callback_user_data);
  13211. #endif
  13212. }
  13213. static void llama_log_internal_v(ggml_log_level level, const char * format, va_list args) {
  13214. va_list args_copy;
  13215. va_copy(args_copy, args);
  13216. char buffer[128];
  13217. int len = vsnprintf(buffer, 128, format, args);
  13218. if (len < 128) {
  13219. g_state.log_callback(level, buffer, g_state.log_callback_user_data);
  13220. } else {
  13221. char* buffer2 = new char[len+1];
  13222. vsnprintf(buffer2, len+1, format, args_copy);
  13223. buffer2[len] = 0;
  13224. g_state.log_callback(level, buffer2, g_state.log_callback_user_data);
  13225. delete[] buffer2;
  13226. }
  13227. va_end(args_copy);
  13228. }
  13229. static void llama_log_internal(ggml_log_level level, const char * format, ...) {
  13230. va_list args;
  13231. va_start(args, format);
  13232. llama_log_internal_v(level, format, args);
  13233. va_end(args);
  13234. }
  13235. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data) {
  13236. (void) level;
  13237. (void) user_data;
  13238. fputs(text, stderr);
  13239. fflush(stderr);
  13240. }