llama.cpp 622 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899
  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. #ifdef GGML_USE_VULKAN
  1887. ggml_vk_free_cpu_assist();
  1888. #endif
  1889. ggml_backend_buffer_free(buf_output);
  1890. }
  1891. llama_cparams cparams;
  1892. std::vector<ggml_backend_t> backends;
  1893. #ifdef GGML_USE_METAL
  1894. ggml_backend_t backend_metal = nullptr;
  1895. #endif
  1896. ggml_backend_t backend_cpu = nullptr;
  1897. const llama_model & model;
  1898. // key + value cache for the self attention
  1899. struct llama_kv_cache kv_self;
  1900. std::mt19937 rng;
  1901. bool has_evaluated_once = false;
  1902. int64_t t_start_us;
  1903. int64_t t_load_us;
  1904. int64_t t_sample_us = 0;
  1905. int64_t t_p_eval_us = 0;
  1906. int64_t t_eval_us = 0;
  1907. int64_t t_compute_start_us = 0;
  1908. int64_t n_queued_tokens = 0;
  1909. int32_t n_sample = 0; // number of tokens sampled
  1910. int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1)
  1911. int32_t n_eval = 0; // number of eval calls
  1912. // host buffer for the model output (logits and embeddings)
  1913. ggml_backend_buffer_t buf_output = nullptr;
  1914. // decode output (2-dimensional array: [n_outputs][n_vocab])
  1915. size_t logits_size = 0; // capacity (of floats) for logits
  1916. float * logits = nullptr;
  1917. std::vector<int32_t> output_ids; // map batch token positions to ids of the logits and embd buffers
  1918. size_t output_size = 0; // capacity (of tokens positions) for the output buffers
  1919. int32_t n_outputs = 0; // number of actually-used outputs in the current ubatch
  1920. bool logits_all = false;
  1921. // embeddings output (2-dimensional array: [n_outputs][n_embd])
  1922. // populated only when pooling_type == LLAMA_POOLING_TYPE_NONE
  1923. size_t embd_size = 0; // capacity (of floats) for embeddings
  1924. float * embd = nullptr;
  1925. // sequence embeddings output (map of [n_embd] vectors)
  1926. // populated only when pooling_type != LLAMA_POOLING_TYPE_NONE
  1927. std::map<llama_seq_id, std::vector<float>> embd_seq;
  1928. // memory buffers used to evaluate the model
  1929. std::vector<uint8_t> buf_compute_meta;
  1930. ggml_backend_sched_t sched = nullptr;
  1931. ggml_abort_callback abort_callback = nullptr;
  1932. void * abort_callback_data = nullptr;
  1933. // input tensors
  1934. struct ggml_tensor * inp_tokens; // I32 [n_batch]
  1935. struct ggml_tensor * inp_embd; // F32 [n_embd, n_batch]
  1936. struct ggml_tensor * inp_pos; // I32 [n_batch]
  1937. struct ggml_tensor * inp_out_ids; // I32 [n_outputs]
  1938. struct ggml_tensor * inp_KQ_mask; // F32 [kv_size, n_batch]
  1939. struct ggml_tensor * inp_KQ_pos; // F32 [n_kv]
  1940. struct ggml_tensor * inp_K_shift; // I32 [kv_size]
  1941. struct ggml_tensor * inp_mean; // F32 [n_batch, n_batch]
  1942. struct ggml_tensor * inp_cls; // I32 [n_batch]
  1943. struct ggml_tensor * inp_s_copy; // I32 [kv_size]
  1944. struct ggml_tensor * inp_s_mask; // F32 [1, n_kv]
  1945. struct ggml_tensor * inp_s_seq; // I32 [n_kv, n_batch]
  1946. // control vectors
  1947. struct llama_control_vector cvec;
  1948. #ifdef GGML_USE_MPI
  1949. ggml_mpi_context * ctx_mpi = NULL;
  1950. #endif
  1951. };
  1952. //
  1953. // kv cache helpers
  1954. //
  1955. static bool llama_kv_cache_init(
  1956. struct llama_kv_cache & cache,
  1957. const llama_model & model,
  1958. ggml_type type_k,
  1959. ggml_type type_v,
  1960. uint32_t kv_size,
  1961. bool offload) {
  1962. const struct llama_hparams & hparams = model.hparams;
  1963. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  1964. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  1965. const int64_t n_layer = hparams.n_layer;
  1966. cache.has_shift = false;
  1967. // TODO: find a nicer way to add other recurrent model architectures
  1968. cache.recurrent = model.arch == LLM_ARCH_MAMBA;
  1969. // TODO: support mixed reccurent Transformer architectues
  1970. // NOTE: (!a || b) is a logical implication (a -> b)
  1971. GGML_ASSERT(!cache.recurrent || n_embd_k_gqa == hparams.n_embd_k_s());
  1972. GGML_ASSERT(!cache.recurrent || n_embd_v_gqa == hparams.n_embd_v_s());
  1973. GGML_ASSERT( cache.recurrent || n_embd_k_gqa == hparams.n_embd_k_gqa());
  1974. GGML_ASSERT( cache.recurrent || n_embd_v_gqa == hparams.n_embd_v_gqa());
  1975. cache.head = 0;
  1976. cache.size = kv_size;
  1977. cache.used = 0;
  1978. cache.type_k = type_k;
  1979. cache.type_v = type_v;
  1980. cache.cells.clear();
  1981. cache.cells.resize(kv_size);
  1982. if (cache.recurrent) {
  1983. // init state copy sources
  1984. for (uint32_t i = 0; i < cache.size; ++i) {
  1985. cache.cells[i].src = i;
  1986. }
  1987. }
  1988. #ifdef GGML_USE_CLBLAST
  1989. offload = false;
  1990. #endif
  1991. // count used buffer types
  1992. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  1993. if (offload) {
  1994. for (int64_t i = 0; i < n_layer; ++i) {
  1995. buft_layer_count[model.buft_layer[i].buft]++;
  1996. }
  1997. } else {
  1998. buft_layer_count[llama_default_buffer_type_cpu(true)] = n_layer;
  1999. }
  2000. // create a context for each buffer type
  2001. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  2002. for (auto & it : buft_layer_count) {
  2003. int n_layers = it.second;
  2004. struct ggml_init_params params = {
  2005. /*.mem_size =*/ 2u*n_layers*ggml_tensor_overhead(),
  2006. /*.mem_buffer =*/ NULL,
  2007. /*.no_alloc =*/ true,
  2008. };
  2009. ggml_context * ctx = ggml_init(params);
  2010. if (!ctx) {
  2011. LLAMA_LOG_ERROR("%s: failed to allocate context for kv cache\n", __func__);
  2012. return false;
  2013. }
  2014. ctx_map[it.first] = ctx;
  2015. cache.ctxs.push_back(ctx);
  2016. }
  2017. cache.k_l.reserve(n_layer);
  2018. cache.v_l.reserve(n_layer);
  2019. for (int i = 0; i < (int) n_layer; i++) {
  2020. struct ggml_context * ctx = offload ? ctx_map.at(model.buft_layer[i].buft) : cache.ctxs.front();
  2021. ggml_tensor * k = ggml_new_tensor_1d(ctx, type_k, n_embd_k_gqa*kv_size);
  2022. ggml_tensor * v = ggml_new_tensor_1d(ctx, type_v, n_embd_v_gqa*kv_size);
  2023. ggml_format_name(k, "cache_k_l%d", i);
  2024. ggml_format_name(v, "cache_v_l%d", i);
  2025. cache.k_l.push_back(k);
  2026. cache.v_l.push_back(v);
  2027. }
  2028. // allocate tensors and initialize the buffers to avoid NaNs in the padding
  2029. for (auto it : ctx_map) {
  2030. ggml_backend_buffer_type_t buft = it.first;
  2031. ggml_context * ctx = it.second;
  2032. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  2033. if (!buf) {
  2034. LLAMA_LOG_ERROR("%s: failed to allocate buffer for kv cache\n", __func__);
  2035. return false;
  2036. }
  2037. ggml_backend_buffer_clear(buf, 0);
  2038. 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);
  2039. cache.bufs.push_back(buf);
  2040. }
  2041. return true;
  2042. }
  2043. // find an empty slot of size "n_tokens" in the cache
  2044. // updates the cache head
  2045. // Note: On success, it's important that cache.head points
  2046. // to the first cell of the slot.
  2047. static bool llama_kv_cache_find_slot(
  2048. struct llama_kv_cache & cache,
  2049. const struct llama_batch & batch) {
  2050. const uint32_t n_ctx = cache.size;
  2051. const uint32_t n_tokens = batch.n_tokens;
  2052. if (cache.recurrent) {
  2053. // For recurrent state architectures (like Mamba),
  2054. // each KV cache cell can store the state for a whole sequence.
  2055. llama_seq_id min = cache.size - 1;
  2056. llama_seq_id max = 0;
  2057. for (uint32_t i = 0; i < n_tokens; ++i) {
  2058. for (int32_t j = 0; j < batch.n_seq_id[i]; ++j) {
  2059. llama_seq_id seq_id = batch.seq_id[i][j];
  2060. // make sure it's a valid seq_id
  2061. if ((uint32_t) seq_id < cache.size) {
  2062. if (seq_id > max) {
  2063. max = seq_id;
  2064. }
  2065. if (seq_id < min) {
  2066. min = seq_id;
  2067. }
  2068. // Assuming the tokens are in-order
  2069. if (batch.pos[i] != cache.cells[seq_id].pos + 1) {
  2070. // What should happen when the pos backtracks or skips a value?
  2071. // Clearing the state mid-batch would require special-casing which isn't done.
  2072. LLAMA_LOG_WARN("%s: non-consecutive token position %d after %d for sequence %d\n",
  2073. __func__, batch.pos[i], cache.cells[seq_id].pos, seq_id);
  2074. }
  2075. if (cache.cells[seq_id].pos < 0 && 0 <= batch.pos[i]) {
  2076. cache.used += 1;
  2077. }
  2078. cache.cells[seq_id].pos = batch.pos[i];
  2079. // NOTE: seq_ids are not inserted here; they are handled when the input tensors are set
  2080. } else {
  2081. // too big seq_id
  2082. // TODO: would it be possible to resize the KV cache size instead?
  2083. LLAMA_LOG_ERROR("%s: seq_id=%d >= kv_size=%d Try using a bigger --parallel value\n", __func__, seq_id, cache.size);
  2084. return false;
  2085. }
  2086. }
  2087. }
  2088. // allow getting the range of used cells, from head to head + n
  2089. cache.head = min;
  2090. cache.n = max - min + 1;
  2091. // sanity check
  2092. return max >= min;
  2093. }
  2094. // otherwise, one cell per token.
  2095. if (n_tokens > n_ctx) {
  2096. LLAMA_LOG_ERROR("%s: n_tokens=%d > n_ctx=%d\n", __func__, n_tokens, n_ctx);
  2097. return false;
  2098. }
  2099. uint32_t n_tested = 0;
  2100. while (true) {
  2101. if (cache.head + n_tokens > n_ctx) {
  2102. n_tested += n_ctx - cache.head;
  2103. cache.head = 0;
  2104. continue;
  2105. }
  2106. bool found = true;
  2107. for (uint32_t i = 0; i < n_tokens; i++) {
  2108. if (cache.cells[cache.head + i].pos >= 0) {
  2109. found = false;
  2110. cache.head += i + 1;
  2111. n_tested += i + 1;
  2112. break;
  2113. }
  2114. }
  2115. if (found) {
  2116. break;
  2117. }
  2118. if (n_tested >= n_ctx) {
  2119. //LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens);
  2120. return false;
  2121. }
  2122. }
  2123. for (uint32_t i = 0; i < n_tokens; i++) {
  2124. cache.cells[cache.head + i].pos = batch.pos[i];
  2125. for (int32_t j = 0; j < batch.n_seq_id[i]; j++) {
  2126. cache.cells[cache.head + i].seq_id.insert(batch.seq_id[i][j]);
  2127. }
  2128. }
  2129. cache.used += n_tokens;
  2130. return true;
  2131. }
  2132. // find how many cells are currently in use
  2133. static uint32_t llama_kv_cache_cell_max(const struct llama_kv_cache & cache) {
  2134. for (uint32_t i = cache.size; i > 0; --i) {
  2135. const llama_kv_cell & cell = cache.cells[i - 1];
  2136. if (cell.pos >= 0 && !cell.is_empty()) {
  2137. return i;
  2138. }
  2139. }
  2140. return 0;
  2141. }
  2142. static void llama_kv_cache_clear(struct llama_kv_cache & cache) {
  2143. for (int32_t i = 0; i < (int32_t) cache.size; ++i) {
  2144. cache.cells[i].pos = -1;
  2145. cache.cells[i].seq_id.clear();
  2146. }
  2147. cache.head = 0;
  2148. cache.used = 0;
  2149. }
  2150. static bool llama_kv_cache_seq_rm(
  2151. struct llama_kv_cache & cache,
  2152. llama_seq_id seq_id,
  2153. llama_pos p0,
  2154. llama_pos p1) {
  2155. uint32_t new_head = cache.size;
  2156. if (p0 < 0) p0 = 0;
  2157. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2158. // models like Mamba can't have a state partially erased
  2159. if (cache.recurrent) {
  2160. if (seq_id >= (int64_t) cache.size) {
  2161. // could be fatal
  2162. return false;
  2163. }
  2164. if (0 <= seq_id) {
  2165. // partial intersection is invalid
  2166. if ((0 < p0 && p0 <= cache.cells[seq_id].pos) || (0 < p1 && p1 <= cache.cells[seq_id].pos)) {
  2167. return false;
  2168. }
  2169. } else {
  2170. // seq_id is negative, then the range should include everything or nothing
  2171. if (p0 != p1 && (p0 != 0 || p1 != std::numeric_limits<llama_pos>::max())) {
  2172. return false;
  2173. }
  2174. }
  2175. }
  2176. for (uint32_t i = 0; i < cache.size; ++i) {
  2177. if (cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2178. if (seq_id < 0) {
  2179. cache.cells[i].seq_id.clear();
  2180. } else if (cache.cells[i].has_seq_id(seq_id)) {
  2181. cache.cells[i].seq_id.erase(seq_id);
  2182. } else {
  2183. continue;
  2184. }
  2185. if (cache.cells[i].is_empty()) {
  2186. // keep count of the number of used cells
  2187. if (cache.cells[i].pos >= 0) cache.used--;
  2188. cache.cells[i].pos = -1;
  2189. if (new_head == cache.size) new_head = i;
  2190. }
  2191. }
  2192. }
  2193. // If we freed up a slot, set head to it so searching can start there.
  2194. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  2195. return true;
  2196. }
  2197. static void llama_kv_cache_seq_cp(
  2198. struct llama_kv_cache & cache,
  2199. llama_seq_id seq_id_src,
  2200. llama_seq_id seq_id_dst,
  2201. llama_pos p0,
  2202. llama_pos p1) {
  2203. if (p0 < 0) p0 = 0;
  2204. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2205. if (cache.recurrent) {
  2206. if ((uint32_t) seq_id_dst < cache.size && (uint32_t) seq_id_src < cache.size) {
  2207. seq_id_src = cache.cells[seq_id_src].src;
  2208. GGML_ASSERT((uint32_t) seq_id_src < cache.size);
  2209. // intent to "copy from"
  2210. // supports copy chains thanks to taking the source of the source
  2211. cache.cells[seq_id_dst].src = seq_id_src;
  2212. // preserve the "keep or clear" status of the copied sequence
  2213. if (cache.cells[seq_id_src].has_seq_id(seq_id_src)) {
  2214. cache.cells[seq_id_dst].seq_id.insert(seq_id_dst);
  2215. } else {
  2216. cache.cells[seq_id_dst].seq_id.erase(seq_id_dst);
  2217. }
  2218. cache.do_copy = true;
  2219. cache.cells[seq_id_dst].pos = cache.cells[seq_id_src].pos;
  2220. }
  2221. return;
  2222. }
  2223. // otherwise, this is the KV cache of a Transformer-like model
  2224. cache.head = 0;
  2225. for (uint32_t i = 0; i < cache.size; ++i) {
  2226. if (cache.cells[i].has_seq_id(seq_id_src) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2227. cache.cells[i].seq_id.insert(seq_id_dst);
  2228. }
  2229. }
  2230. }
  2231. static void llama_kv_cache_seq_keep(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  2232. uint32_t new_head = cache.size;
  2233. for (uint32_t i = 0; i < cache.size; ++i) {
  2234. if (!cache.cells[i].has_seq_id(seq_id)) {
  2235. if (cache.cells[i].pos >= 0) cache.used--;
  2236. cache.cells[i].pos = -1;
  2237. cache.cells[i].seq_id.clear();
  2238. if (new_head == cache.size) new_head = i;
  2239. } else {
  2240. cache.cells[i].seq_id.clear();
  2241. cache.cells[i].seq_id.insert(seq_id);
  2242. }
  2243. }
  2244. // If we freed up a slot, set head to it so searching can start there.
  2245. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  2246. }
  2247. static void llama_kv_cache_seq_add(
  2248. struct llama_kv_cache & cache,
  2249. llama_seq_id seq_id,
  2250. llama_pos p0,
  2251. llama_pos p1,
  2252. llama_pos delta) {
  2253. uint32_t new_head = cache.size;
  2254. if (p0 < 0) p0 = 0;
  2255. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2256. if (cache.recurrent) {
  2257. // for Mamba-like models, only the pos needs to be shifted
  2258. if (0 <= seq_id && seq_id < (int64_t) cache.size) {
  2259. llama_kv_cell & cell = cache.cells[seq_id];
  2260. if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
  2261. cell.pos += delta;
  2262. }
  2263. }
  2264. return;
  2265. }
  2266. for (uint32_t i = 0; i < cache.size; ++i) {
  2267. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2268. cache.has_shift = true;
  2269. cache.cells[i].pos += delta;
  2270. cache.cells[i].delta += delta;
  2271. if (cache.cells[i].pos < 0) {
  2272. if (!cache.cells[i].is_empty()) {
  2273. cache.used--;
  2274. }
  2275. cache.cells[i].pos = -1;
  2276. cache.cells[i].seq_id.clear();
  2277. if (new_head == cache.size) {
  2278. new_head = i;
  2279. }
  2280. }
  2281. }
  2282. }
  2283. // If we freed up a slot, set head to it so searching can start there.
  2284. // Otherwise we just start the next search from the beginning.
  2285. cache.head = new_head != cache.size ? new_head : 0;
  2286. }
  2287. static void llama_kv_cache_seq_div(
  2288. struct llama_kv_cache & cache,
  2289. llama_seq_id seq_id,
  2290. llama_pos p0,
  2291. llama_pos p1,
  2292. int d) {
  2293. if (p0 < 0) p0 = 0;
  2294. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2295. if (cache.recurrent) {
  2296. // for Mamba-like models, only the pos needs to be changed
  2297. if (0 <= seq_id && seq_id < (int64_t) cache.size) {
  2298. llama_kv_cell & cell = cache.cells[seq_id];
  2299. if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
  2300. cell.pos /= d;
  2301. }
  2302. }
  2303. return;
  2304. }
  2305. for (uint32_t i = 0; i < cache.size; ++i) {
  2306. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2307. cache.has_shift = true;
  2308. {
  2309. llama_pos p_old = cache.cells[i].pos;
  2310. cache.cells[i].pos /= d;
  2311. cache.cells[i].delta += cache.cells[i].pos - p_old;
  2312. }
  2313. }
  2314. }
  2315. }
  2316. static llama_pos llama_kv_cache_seq_pos_max(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  2317. llama_pos result = 0;
  2318. for (uint32_t i = 0; i < cache.size; ++i) {
  2319. if (cache.cells[i].has_seq_id(seq_id)) {
  2320. result = std::max(result, cache.cells[i].pos);
  2321. }
  2322. }
  2323. return result;
  2324. }
  2325. static void llama_kv_cache_defrag(struct llama_kv_cache & cache) {
  2326. cache.do_defrag = true;
  2327. }
  2328. //
  2329. // model loading and saving
  2330. //
  2331. enum llama_fver {
  2332. GGUF_FILE_VERSION_V1 = 1,
  2333. GGUF_FILE_VERSION_V2 = 2,
  2334. GGUF_FILE_VERSION_V3 = 3,
  2335. };
  2336. static const char * llama_file_version_name(llama_fver version) {
  2337. switch (version) {
  2338. case GGUF_FILE_VERSION_V1: return "GGUF V1 (support until nov 2023)";
  2339. case GGUF_FILE_VERSION_V2: return "GGUF V2";
  2340. case GGUF_FILE_VERSION_V3: return "GGUF V3 (latest)";
  2341. }
  2342. return "unknown";
  2343. }
  2344. static std::string llama_format_tensor_shape(const std::vector<int64_t> & ne) {
  2345. char buf[256];
  2346. snprintf(buf, sizeof(buf), "%5" PRId64, ne.at(0));
  2347. for (size_t i = 1; i < ne.size(); i++) {
  2348. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, ne.at(i));
  2349. }
  2350. return buf;
  2351. }
  2352. static std::string llama_format_tensor_shape(const struct ggml_tensor * t) {
  2353. char buf[256];
  2354. snprintf(buf, sizeof(buf), "%5" PRId64, t->ne[0]);
  2355. for (int i = 1; i < GGML_MAX_DIMS; i++) {
  2356. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, t->ne[i]);
  2357. }
  2358. return buf;
  2359. }
  2360. namespace GGUFMeta {
  2361. template <typename T, gguf_type gt_, T (*gfun)(const gguf_context *, const int)>
  2362. struct GKV_Base_Type {
  2363. static constexpr gguf_type gt = gt_;
  2364. static T getter(const gguf_context * ctx, const int kid) {
  2365. return gfun(ctx, kid);
  2366. }
  2367. };
  2368. template<typename T> struct GKV_Base;
  2369. template<> struct GKV_Base<bool >: GKV_Base_Type<bool, GGUF_TYPE_BOOL, gguf_get_val_bool> {};
  2370. template<> struct GKV_Base<uint8_t >: GKV_Base_Type<uint8_t, GGUF_TYPE_UINT8, gguf_get_val_u8 > {};
  2371. template<> struct GKV_Base<uint16_t >: GKV_Base_Type<uint16_t, GGUF_TYPE_UINT16, gguf_get_val_u16 > {};
  2372. template<> struct GKV_Base<uint32_t >: GKV_Base_Type<uint32_t, GGUF_TYPE_UINT32, gguf_get_val_u32 > {};
  2373. template<> struct GKV_Base<uint64_t >: GKV_Base_Type<uint64_t, GGUF_TYPE_UINT64, gguf_get_val_u64 > {};
  2374. template<> struct GKV_Base<int8_t >: GKV_Base_Type<int8_t, GGUF_TYPE_INT8, gguf_get_val_i8 > {};
  2375. template<> struct GKV_Base<int16_t >: GKV_Base_Type<int16_t, GGUF_TYPE_INT16, gguf_get_val_i16 > {};
  2376. template<> struct GKV_Base<int32_t >: GKV_Base_Type<int32_t, GGUF_TYPE_INT32, gguf_get_val_i32 > {};
  2377. template<> struct GKV_Base<int64_t >: GKV_Base_Type<int64_t, GGUF_TYPE_INT64, gguf_get_val_i64 > {};
  2378. template<> struct GKV_Base<float >: GKV_Base_Type<float, GGUF_TYPE_FLOAT32, gguf_get_val_f32 > {};
  2379. template<> struct GKV_Base<double >: GKV_Base_Type<double, GGUF_TYPE_FLOAT64, gguf_get_val_f64 > {};
  2380. template<> struct GKV_Base<const char *>: GKV_Base_Type<const char *, GGUF_TYPE_STRING, gguf_get_val_str > {};
  2381. template<> struct GKV_Base<std::string> {
  2382. static constexpr gguf_type gt = GGUF_TYPE_STRING;
  2383. static std::string getter(const gguf_context * ctx, const int kid) {
  2384. return gguf_get_val_str(ctx, kid);
  2385. }
  2386. };
  2387. struct ArrayInfo {
  2388. const gguf_type gt;
  2389. const size_t length;
  2390. const void * data;
  2391. };
  2392. template<> struct GKV_Base<ArrayInfo> {
  2393. public:
  2394. static constexpr gguf_type gt = GGUF_TYPE_ARRAY;
  2395. static ArrayInfo getter(const gguf_context *ctx, const int k) {
  2396. return ArrayInfo {
  2397. gguf_get_arr_type(ctx, k),
  2398. size_t(gguf_get_arr_n(ctx, k)),
  2399. gguf_get_arr_data(ctx, k),
  2400. };
  2401. }
  2402. };
  2403. template<typename T>
  2404. class GKV : public GKV_Base<T> {
  2405. GKV() = delete;
  2406. public:
  2407. static T get_kv(const gguf_context * ctx, const int k) {
  2408. const enum gguf_type kt = gguf_get_kv_type(ctx, k);
  2409. if (kt != GKV::gt) {
  2410. throw std::runtime_error(format("key %s has wrong type %s but expected type %s",
  2411. gguf_get_key(ctx, k), gguf_type_name(kt), gguf_type_name(GKV::gt)));
  2412. }
  2413. return GKV::getter(ctx, k);
  2414. }
  2415. static const char * override_type_to_str(const llama_model_kv_override_type ty) {
  2416. switch (ty) {
  2417. case LLAMA_KV_OVERRIDE_TYPE_BOOL: return "bool";
  2418. case LLAMA_KV_OVERRIDE_TYPE_INT: return "int";
  2419. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: return "float";
  2420. }
  2421. return "unknown";
  2422. }
  2423. static bool validate_override(const llama_model_kv_override_type expected_type, const struct llama_model_kv_override * ovrd) {
  2424. if (!ovrd) { return false; }
  2425. if (ovrd->tag == expected_type) {
  2426. LLAMA_LOG_INFO("%s: Using metadata override (%5s) '%s' = ",
  2427. __func__, override_type_to_str(ovrd->tag), ovrd->key);
  2428. switch (ovrd->tag) {
  2429. case LLAMA_KV_OVERRIDE_TYPE_BOOL: {
  2430. LLAMA_LOG_INFO("%s\n", ovrd->bool_value ? "true" : "false");
  2431. } break;
  2432. case LLAMA_KV_OVERRIDE_TYPE_INT: {
  2433. LLAMA_LOG_INFO("%" PRId64 "\n", ovrd->int_value);
  2434. } break;
  2435. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: {
  2436. LLAMA_LOG_INFO("%.6f\n", ovrd->float_value);
  2437. } break;
  2438. default:
  2439. // Shouldn't be possible to end up here, but just in case...
  2440. throw std::runtime_error(
  2441. format("Unsupported attempt to override %s type for metadata key %s\n",
  2442. override_type_to_str(ovrd->tag), ovrd->key));
  2443. }
  2444. return true;
  2445. }
  2446. LLAMA_LOG_WARN("%s: Warning: Bad metadata override type for key '%s', expected %s but got %s\n",
  2447. __func__, ovrd->key, override_type_to_str(expected_type), override_type_to_str(ovrd->tag));
  2448. return false;
  2449. }
  2450. template<typename OT>
  2451. static typename std::enable_if<std::is_same<OT, bool>::value, bool>::type
  2452. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  2453. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_BOOL, ovrd)) {
  2454. target = ovrd->bool_value;
  2455. return true;
  2456. }
  2457. return false;
  2458. }
  2459. template<typename OT>
  2460. static typename std::enable_if<!std::is_same<OT, bool>::value && std::is_integral<OT>::value, bool>::type
  2461. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  2462. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_INT, ovrd)) {
  2463. target = ovrd->int_value;
  2464. return true;
  2465. }
  2466. return false;
  2467. }
  2468. template<typename OT>
  2469. static typename std::enable_if<std::is_floating_point<OT>::value, bool>::type
  2470. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  2471. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_FLOAT, ovrd)) {
  2472. target = ovrd->float_value;
  2473. return true;
  2474. }
  2475. return false;
  2476. }
  2477. template<typename OT>
  2478. static typename std::enable_if<std::is_same<OT, std::string>::value, bool>::type
  2479. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  2480. (void)target;
  2481. (void)ovrd;
  2482. if (!ovrd) { return false; }
  2483. // Currently, we should never end up here so it would be a bug if we do.
  2484. throw std::runtime_error(format("Unsupported attempt to override string type for metadata key %s\n",
  2485. ovrd ? ovrd->key : "NULL"));
  2486. }
  2487. static bool set(const gguf_context * ctx, const int k, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  2488. if (try_override<T>(target, ovrd)) {
  2489. return true;
  2490. }
  2491. if (k < 0) { return false; }
  2492. target = get_kv(ctx, k);
  2493. return true;
  2494. }
  2495. static bool set(const gguf_context * ctx, const char * key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  2496. return set(ctx, gguf_find_key(ctx, key), target, ovrd);
  2497. }
  2498. static bool set(const gguf_context * ctx, const std::string & key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  2499. return set(ctx, key.c_str(), target, ovrd);
  2500. }
  2501. };
  2502. }
  2503. using llama_buf_map = std::unordered_map<uint32_t, ggml_backend_buffer_t>;
  2504. struct llama_model_loader {
  2505. int n_kv = 0;
  2506. int n_tensors = 0;
  2507. int n_created = 0;
  2508. int64_t n_elements = 0;
  2509. size_t n_bytes = 0;
  2510. bool use_mmap = false;
  2511. llama_files files;
  2512. llama_ftype ftype;
  2513. llama_fver fver;
  2514. llama_mmaps mappings;
  2515. // Holds information on a model weights
  2516. struct llama_tensor_weights {
  2517. uint16_t idx; // source file index
  2518. size_t offs; // tensor data offset in the original file
  2519. ggml_tensor * tensor;
  2520. llama_tensor_weights(uint16_t idx, const char * name, const struct gguf_context * gguf_ctx, ggml_tensor * tensor) : idx(idx), tensor(tensor) {
  2521. const int tensor_idx = gguf_find_tensor(gguf_ctx, name);
  2522. offs = gguf_get_data_offset(gguf_ctx) + gguf_get_tensor_offset(gguf_ctx, tensor_idx);
  2523. }
  2524. };
  2525. std::vector<llama_tensor_weights> weights;
  2526. std::unordered_map<std::string, struct llama_model_kv_override> kv_overrides;
  2527. struct gguf_context * meta = NULL;
  2528. std::vector<ggml_context *> contexts;
  2529. std::string arch_name;
  2530. LLM_KV llm_kv = LLM_KV(LLM_ARCH_UNKNOWN);
  2531. llama_model_loader(const std::string & fname, bool use_mmap, const struct llama_model_kv_override * param_overrides_p) {
  2532. int trace = 0;
  2533. if (getenv("LLAMA_TRACE")) {
  2534. trace = atoi(getenv("LLAMA_TRACE"));
  2535. }
  2536. if (param_overrides_p != nullptr) {
  2537. for (const struct llama_model_kv_override *p = param_overrides_p; p->key[0] != 0; p++) {
  2538. kv_overrides.insert({std::string(p->key), *p});
  2539. }
  2540. }
  2541. struct ggml_context * ctx = NULL;
  2542. struct gguf_init_params params = {
  2543. /*.no_alloc = */ true,
  2544. /*.ctx = */ &ctx,
  2545. };
  2546. meta = gguf_init_from_file(fname.c_str(), params);
  2547. if (!meta) {
  2548. throw std::runtime_error(format("%s: failed to load model from %s\n", __func__, fname.c_str()));
  2549. }
  2550. get_key(llm_kv(LLM_KV_GENERAL_ARCHITECTURE), arch_name, false);
  2551. llm_kv = LLM_KV(llm_arch_from_string(arch_name));
  2552. // Save tensors data offset of the main file.
  2553. // For subsidiary files, `meta` tensor data offset must not be used,
  2554. // so we build a unified tensors index for weights.
  2555. for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  2556. weights.emplace_back(llama_tensor_weights(0, cur->name, meta, cur));
  2557. }
  2558. files.emplace_back(new llama_file(fname.c_str(), "rb"));
  2559. contexts.emplace_back(ctx);
  2560. uint16_t n_split = 0;
  2561. get_key(llm_kv(LLM_KV_SPLIT_COUNT), n_split, false);
  2562. // Load additional GGML contexts
  2563. if (n_split > 1) {
  2564. uint16_t idx = 0;
  2565. get_key(llm_kv(LLM_KV_SPLIT_NO), idx);
  2566. if (idx != 0) {
  2567. throw std::runtime_error(format("illegal split file: %d, model must be loaded with the first split", idx));
  2568. }
  2569. char split_prefix[PATH_MAX] = {0};
  2570. if (!llama_split_prefix(split_prefix, sizeof(split_prefix), fname.c_str(), idx, n_split)) {
  2571. throw std::runtime_error(format("invalid split file: %s", fname.c_str()));
  2572. }
  2573. if (trace > 0) {
  2574. LLAMA_LOG_INFO("%s: loading additional %d GGUFs\n", __func__, n_split);
  2575. }
  2576. char split_path[PATH_MAX] = {0};
  2577. for (idx = 1; idx < n_split; idx++) {
  2578. llama_split_path(split_path, sizeof(split_path), split_prefix, idx, n_split);
  2579. struct gguf_init_params split_params = {
  2580. /*.no_alloc = */ true,
  2581. /*.ctx = */ &ctx,
  2582. };
  2583. struct gguf_context * ctx_gguf = gguf_init_from_file(split_path, split_params);
  2584. if (!ctx_gguf) {
  2585. throw std::runtime_error(format("%s: failed to load GGUF split from %s\n", __func__, split_path));
  2586. }
  2587. // Save tensors data offset info of the shard.
  2588. for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  2589. weights.emplace_back(llama_tensor_weights(idx, cur->name, ctx_gguf, cur));
  2590. }
  2591. files.emplace_back(new llama_file(split_path, "rb"));
  2592. contexts.emplace_back(ctx);
  2593. gguf_free(ctx_gguf);
  2594. }
  2595. get_key(llm_kv(LLM_KV_SPLIT_TENSORS_COUNT), n_tensors);
  2596. // sanity check
  2597. {
  2598. const int n_tensors_loaded = (int) weights.size();
  2599. if (n_tensors != n_tensors_loaded) {
  2600. throw std::runtime_error(format("corrupted model: %d tensors expected but %d found", n_tensors, n_tensors_loaded));
  2601. }
  2602. }
  2603. LLAMA_LOG_INFO("%s: additional %d GGUFs metadata loaded.\n", __func__, n_split - 1);
  2604. }
  2605. n_kv = gguf_get_n_kv(meta);
  2606. n_tensors = weights.size();
  2607. fver = (enum llama_fver) gguf_get_version(meta);
  2608. for (auto & w : weights) {
  2609. n_elements += ggml_nelements(w.tensor);
  2610. n_bytes += ggml_nbytes(w.tensor);
  2611. }
  2612. LLAMA_LOG_INFO("%s: loaded meta data with %d key-value pairs and %d tensors from %s (version %s)\n",
  2613. __func__, n_kv, n_tensors, fname.c_str(), llama_file_version_name(fver));
  2614. // determine file type based on the number of tensors for each quantization and print meta data
  2615. // TODO: make optional
  2616. {
  2617. std::map<enum ggml_type, uint32_t> n_type;
  2618. uint32_t n_type_max = 0;
  2619. enum ggml_type type_max = GGML_TYPE_F32;
  2620. for (int i = 0; i < n_tensors; i++) {
  2621. const ggml_tensor * tensor = weights.at(i).tensor;
  2622. enum ggml_type type = tensor->type;
  2623. n_type[type]++;
  2624. if (n_type_max < n_type[type]) {
  2625. n_type_max = n_type[type];
  2626. type_max = type;
  2627. }
  2628. if (trace > 0) {
  2629. const uint16_t sid = weights.at(i).idx;
  2630. 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());
  2631. }
  2632. }
  2633. switch (type_max) {
  2634. case GGML_TYPE_F32: ftype = LLAMA_FTYPE_ALL_F32; break;
  2635. case GGML_TYPE_F16: ftype = LLAMA_FTYPE_MOSTLY_F16; break;
  2636. case GGML_TYPE_Q4_0: ftype = LLAMA_FTYPE_MOSTLY_Q4_0; break;
  2637. case GGML_TYPE_Q4_1: ftype = LLAMA_FTYPE_MOSTLY_Q4_1; break;
  2638. case GGML_TYPE_Q5_0: ftype = LLAMA_FTYPE_MOSTLY_Q5_0; break;
  2639. case GGML_TYPE_Q5_1: ftype = LLAMA_FTYPE_MOSTLY_Q5_1; break;
  2640. case GGML_TYPE_Q8_0: ftype = LLAMA_FTYPE_MOSTLY_Q8_0; break;
  2641. case GGML_TYPE_Q2_K: ftype = LLAMA_FTYPE_MOSTLY_Q2_K; break;
  2642. case GGML_TYPE_Q3_K: ftype = LLAMA_FTYPE_MOSTLY_Q3_K_M; break;
  2643. case GGML_TYPE_Q4_K: ftype = LLAMA_FTYPE_MOSTLY_Q4_K_M; break;
  2644. case GGML_TYPE_Q5_K: ftype = LLAMA_FTYPE_MOSTLY_Q5_K_M; break;
  2645. case GGML_TYPE_Q6_K: ftype = LLAMA_FTYPE_MOSTLY_Q6_K; break;
  2646. case GGML_TYPE_IQ2_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XXS; break;
  2647. case GGML_TYPE_IQ2_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XS; break;
  2648. case GGML_TYPE_IQ2_S: ftype = LLAMA_FTYPE_MOSTLY_IQ2_S; break;
  2649. case GGML_TYPE_IQ3_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ3_XXS; break;
  2650. case GGML_TYPE_IQ1_S: ftype = LLAMA_FTYPE_MOSTLY_IQ1_S; break;
  2651. case GGML_TYPE_IQ1_M: ftype = LLAMA_FTYPE_MOSTLY_IQ1_M; break;
  2652. case GGML_TYPE_IQ4_NL: ftype = LLAMA_FTYPE_MOSTLY_IQ4_NL; break;
  2653. case GGML_TYPE_IQ4_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ4_XS; break;
  2654. case GGML_TYPE_IQ3_S: ftype = LLAMA_FTYPE_MOSTLY_IQ3_S; break;
  2655. default:
  2656. {
  2657. LLAMA_LOG_WARN("%s: unknown type %s\n", __func__, ggml_type_name(type_max));
  2658. ftype = LLAMA_FTYPE_ALL_F32;
  2659. } break;
  2660. }
  2661. // this is a way to mark that we have "guessed" the file type
  2662. ftype = (llama_ftype) (ftype | LLAMA_FTYPE_GUESSED);
  2663. {
  2664. const int kid = gguf_find_key(meta, "general.file_type");
  2665. if (kid >= 0) {
  2666. ftype = (llama_ftype) gguf_get_val_u32(meta, kid);
  2667. }
  2668. }
  2669. LLAMA_LOG_INFO("%s: Dumping metadata keys/values. Note: KV overrides do not apply in this output.\n", __func__);
  2670. for (int i = 0; i < n_kv; i++) {
  2671. const char * name = gguf_get_key(meta, i);
  2672. const enum gguf_type type = gguf_get_kv_type(meta, i);
  2673. const std::string type_name =
  2674. type == GGUF_TYPE_ARRAY
  2675. ? format("%s[%s,%d]", gguf_type_name(type), gguf_type_name(gguf_get_arr_type(meta, i)), gguf_get_arr_n(meta, i))
  2676. : gguf_type_name(type);
  2677. std::string value = gguf_kv_to_str(meta, i);
  2678. const size_t MAX_VALUE_LEN = 40;
  2679. if (value.size() > MAX_VALUE_LEN) {
  2680. value = format("%s...", value.substr(0, MAX_VALUE_LEN - 3).c_str());
  2681. }
  2682. replace_all(value, "\n", "\\n");
  2683. LLAMA_LOG_INFO("%s: - kv %3d: %42s %-16s = %s\n", __func__, i, name, type_name.c_str(), value.c_str());
  2684. }
  2685. // print type counts
  2686. for (auto & kv : n_type) {
  2687. if (kv.second == 0) {
  2688. continue;
  2689. }
  2690. LLAMA_LOG_INFO("%s: - type %4s: %4d tensors\n", __func__, ggml_type_name(kv.first), kv.second);
  2691. }
  2692. }
  2693. if (!llama_mmap::SUPPORTED) {
  2694. LLAMA_LOG_WARN("%s: mmap is not supported on this platform\n", __func__);
  2695. use_mmap = false;
  2696. }
  2697. this->use_mmap = use_mmap;
  2698. }
  2699. ~llama_model_loader() {
  2700. if (meta) {
  2701. gguf_free(meta);
  2702. }
  2703. for (auto * ctx : contexts) {
  2704. ggml_free(ctx);
  2705. }
  2706. }
  2707. template<typename T>
  2708. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2709. get_arr_n(const std::string & key, T & result, const bool required = true) {
  2710. const int kid = gguf_find_key(meta, key.c_str());
  2711. if (kid < 0) {
  2712. if (required) {
  2713. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2714. }
  2715. return false;
  2716. }
  2717. struct GGUFMeta::ArrayInfo arr_info =
  2718. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(meta, kid);
  2719. result = arr_info.length;
  2720. return true;
  2721. }
  2722. template<typename T>
  2723. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2724. get_arr_n(const enum llm_kv kid, T & result, const bool required = true) {
  2725. return get_arr_n(llm_kv(kid), result, required);
  2726. }
  2727. template<typename T>
  2728. bool get_key(const std::string & key, T & result, const bool required = true) {
  2729. auto it = kv_overrides.find(key);
  2730. const struct llama_model_kv_override * override =
  2731. it != kv_overrides.end() ? &it->second : nullptr;
  2732. const bool found = GGUFMeta::GKV<T>::set(meta, key, result, override);
  2733. if (required && !found) {
  2734. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2735. }
  2736. return found;
  2737. }
  2738. template<typename T>
  2739. bool get_key(const enum llm_kv kid, T & result, const bool required = true) {
  2740. return get_key(llm_kv(kid), result, required);
  2741. }
  2742. std::string get_arch_name() const {
  2743. return arch_name;
  2744. }
  2745. enum llm_arch get_arch() const {
  2746. return llm_kv.arch;
  2747. }
  2748. const char * get_tensor_name(int i) const {
  2749. return weights.at(i).tensor->name;
  2750. }
  2751. const llama_tensor_weights & get_weights(const char * name) const {
  2752. for (const auto & weight : weights) {
  2753. if (strcmp(name, weight.tensor->name) == 0) {
  2754. return weight;
  2755. }
  2756. }
  2757. throw std::runtime_error(format("tensor %s not found", name));
  2758. }
  2759. struct ggml_tensor * get_tensor_meta(const char * name) const {
  2760. try {
  2761. return get_weights(name).tensor;
  2762. } catch (const std::runtime_error & e) {
  2763. return NULL;
  2764. }
  2765. }
  2766. struct ggml_tensor * get_tensor_meta(int i) const {
  2767. return get_tensor_meta(get_tensor_name(i));
  2768. }
  2769. struct ggml_tensor * create_tensor_for(struct ggml_context * ctx, const struct ggml_tensor * cur) {
  2770. struct ggml_tensor * tensor = ggml_dup_tensor(ctx, cur);
  2771. ggml_set_name(tensor, ggml_get_name(cur));
  2772. n_created++;
  2773. return tensor;
  2774. }
  2775. struct ggml_tensor * create_tensor(struct ggml_context * ctx, const std::string & name, const std::vector<int64_t> & ne, bool required = true) {
  2776. const struct ggml_tensor * cur = get_tensor_meta(name.c_str());
  2777. if (cur == NULL) {
  2778. if (!required) {
  2779. return NULL;
  2780. }
  2781. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
  2782. }
  2783. {
  2784. bool is_ok = true;
  2785. for (size_t i = 0; i < ne.size(); ++i) {
  2786. if (ne[i] != cur->ne[i]) {
  2787. is_ok = false;
  2788. break;
  2789. }
  2790. }
  2791. if (!is_ok) {
  2792. throw std::runtime_error(
  2793. format("%s: tensor '%s' has wrong shape; expected %s, got %s",
  2794. __func__, name.c_str(),
  2795. llama_format_tensor_shape(ne).c_str(),
  2796. llama_format_tensor_shape(cur).c_str()));
  2797. }
  2798. }
  2799. return create_tensor_for(ctx, cur);
  2800. }
  2801. void done_getting_tensors() const {
  2802. if (n_created != n_tensors) {
  2803. throw std::runtime_error(format("%s: wrong number of tensors; expected %d, got %d", __func__, n_tensors, n_created));
  2804. }
  2805. }
  2806. void init_mappings(bool prefetch = true, llama_mlocks * mlock_mmaps = nullptr) {
  2807. if (use_mmap) {
  2808. mappings.reserve(files.size());
  2809. mmaps_used.reserve(files.size());
  2810. for (const auto & file : files) {
  2811. std::unique_ptr<llama_mmap> mapping(new llama_mmap(file.get(), prefetch ? -1 : 0, ggml_is_numa()));
  2812. mmaps_used.emplace_back(std::make_pair(mapping->size, 0));
  2813. if (mlock_mmaps) {
  2814. std::unique_ptr<llama_mlock> mlock_mmap(new llama_mlock());
  2815. mlock_mmap->init(mapping->addr);
  2816. mlock_mmaps->emplace_back(std::move(mlock_mmap));
  2817. }
  2818. mappings.emplace_back(std::move(mapping));
  2819. }
  2820. }
  2821. // compute the total size of all tensors for progress reporting
  2822. for (auto & w : weights) {
  2823. size_data += ggml_nbytes(w.tensor);
  2824. }
  2825. }
  2826. void get_mapping_range(size_t * first, size_t * last, void ** addr, int idx, ggml_context * ctx) const {
  2827. GGML_ASSERT(!mappings.empty());
  2828. const auto & mapping = mappings.at(idx);
  2829. *first = mapping->size;
  2830. *last = 0;
  2831. *addr = mapping->addr;
  2832. for (ggml_tensor * tensor = ggml_get_first_tensor(ctx); tensor; tensor = ggml_get_next_tensor(ctx, tensor)) {
  2833. const auto & w = get_weights(ggml_get_name(tensor));
  2834. if (w.idx != idx) {
  2835. continue;
  2836. }
  2837. *first = std::min(*first, w.offs);
  2838. *last = std::max(*last, w.offs + ggml_nbytes(tensor));
  2839. }
  2840. }
  2841. // for backwards compatibility, does not support ggml-backend
  2842. void load_data_for(struct ggml_tensor * cur) const {
  2843. const auto & w = get_weights(ggml_get_name(cur));
  2844. if (use_mmap) {
  2845. const auto & mapping = mappings.at(w.idx);
  2846. if (cur->data == nullptr) {
  2847. cur->data = (uint8_t *)mapping->addr + w.offs;
  2848. } else {
  2849. memcpy(cur->data, (uint8_t *)mapping->addr + w.offs, ggml_nbytes(cur));
  2850. }
  2851. } else {
  2852. GGML_ASSERT(cur->data != nullptr);
  2853. GGML_ASSERT(w.idx < files.size());
  2854. const auto & file = files.at(w.idx);
  2855. file->seek(w.offs, SEEK_SET);
  2856. file->read_raw(cur->data, ggml_nbytes(cur));
  2857. }
  2858. }
  2859. size_t size_done = 0;
  2860. size_t size_data = 0;
  2861. std::vector<std::pair<size_t, size_t>> mmaps_used;
  2862. // Returns false if cancelled by progress_callback
  2863. bool load_all_data(
  2864. struct ggml_context * ctx,
  2865. llama_buf_map & bufs_mmap,
  2866. llama_mlocks * lmlocks,
  2867. llama_progress_callback progress_callback,
  2868. void * progress_callback_user_data) {
  2869. GGML_ASSERT(size_data != 0 && "call init_mappings() first");
  2870. std::vector<no_init<uint8_t>> read_buf;
  2871. for (struct ggml_tensor * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  2872. if (progress_callback) {
  2873. if (!progress_callback((float) size_done / size_data, progress_callback_user_data)) {
  2874. return false;
  2875. }
  2876. }
  2877. const auto & w = get_weights(ggml_get_name(cur));
  2878. size_t n_size = ggml_nbytes(cur);
  2879. if (use_mmap) {
  2880. const auto & mapping = mappings.at(w.idx);
  2881. ggml_backend_buffer_t buf_mmap = nullptr;
  2882. if (bufs_mmap.count(w.idx)) {
  2883. buf_mmap = bufs_mmap.at(w.idx);
  2884. }
  2885. GGML_ASSERT(buf_mmap || cur->data); // either we have a buffer to allocate the tensor in, or it is already allocated
  2886. if (buf_mmap && cur->data == nullptr) {
  2887. ggml_backend_tensor_alloc(buf_mmap, cur, (uint8_t *) mapping->addr + w.offs);
  2888. if (lmlocks) {
  2889. const auto & lmlock = lmlocks->at(w.idx);
  2890. lmlock->grow_to(w.offs + ggml_nbytes(cur));
  2891. }
  2892. auto & mmap_used = mmaps_used[w.idx];
  2893. mmap_used.first = std::min(mmap_used.first, w.offs);
  2894. mmap_used.second = std::max(mmap_used.second, w.offs + n_size);
  2895. } else {
  2896. ggml_backend_tensor_set(cur, (uint8_t *) mapping->addr + w.offs, 0, n_size);
  2897. }
  2898. } else {
  2899. GGML_ASSERT(w.idx < files.size());
  2900. const auto & file = files.at(w.idx);
  2901. if (ggml_backend_buffer_is_host(cur->buffer)) {
  2902. file->seek(w.offs, SEEK_SET);
  2903. file->read_raw(cur->data, ggml_nbytes(cur));
  2904. } else {
  2905. read_buf.resize(ggml_nbytes(cur));
  2906. file->seek(w.offs, SEEK_SET);
  2907. file->read_raw(read_buf.data(), ggml_nbytes(cur));
  2908. ggml_backend_tensor_set(cur, read_buf.data(), 0, n_size);
  2909. }
  2910. }
  2911. size_done += n_size;
  2912. }
  2913. // check if this is the last call and do final cleanup
  2914. if (size_done >= size_data) {
  2915. // unmap offloaded tensors and metadata
  2916. if (use_mmap) {
  2917. for (uint32_t idx = 0; idx < mappings.size(); idx++) {
  2918. const auto & mmap_used = mmaps_used.at(idx);
  2919. auto & mapping = mappings.at(idx);
  2920. mapping->unmap_fragment(0, mmap_used.first);
  2921. if (mmap_used.second != 0) {
  2922. mapping->unmap_fragment(mmap_used.second, mapping->size);
  2923. }
  2924. }
  2925. }
  2926. if (progress_callback) {
  2927. // Even though the model is done loading, we still honor
  2928. // cancellation since we need to free allocations.
  2929. return progress_callback(1.0f, progress_callback_user_data);
  2930. }
  2931. }
  2932. return true;
  2933. }
  2934. };
  2935. template<>
  2936. bool llama_model_loader::get_key(const enum llm_kv kid, enum llama_pooling_type & result, const bool required) {
  2937. uint32_t tmp;
  2938. const bool found = get_key(kid, tmp, required);
  2939. if (found) {
  2940. result = (enum llama_pooling_type) tmp;
  2941. } else {
  2942. result = LLAMA_POOLING_TYPE_UNSPECIFIED;
  2943. }
  2944. return found;
  2945. }
  2946. //
  2947. // load LLaMA models
  2948. //
  2949. static const char * llama_model_arch_name(llm_arch arch) {
  2950. auto it = LLM_ARCH_NAMES.find(arch);
  2951. if (it == LLM_ARCH_NAMES.end()) {
  2952. return "unknown";
  2953. }
  2954. return it->second;
  2955. }
  2956. static std::string llama_model_ftype_name(llama_ftype ftype) {
  2957. if (ftype & LLAMA_FTYPE_GUESSED) {
  2958. return llama_model_ftype_name((enum llama_ftype) (ftype & ~LLAMA_FTYPE_GUESSED)) + " (guessed)";
  2959. }
  2960. switch (ftype) {
  2961. case LLAMA_FTYPE_ALL_F32: return "all F32";
  2962. case LLAMA_FTYPE_MOSTLY_F16: return "F16";
  2963. case LLAMA_FTYPE_MOSTLY_Q4_0: return "Q4_0";
  2964. case LLAMA_FTYPE_MOSTLY_Q4_1: return "Q4_1";
  2965. case LLAMA_FTYPE_MOSTLY_Q4_1_SOME_F16:
  2966. return "Q4_1, some F16";
  2967. case LLAMA_FTYPE_MOSTLY_Q5_0: return "Q5_0";
  2968. case LLAMA_FTYPE_MOSTLY_Q5_1: return "Q5_1";
  2969. case LLAMA_FTYPE_MOSTLY_Q8_0: return "Q8_0";
  2970. // K-quants
  2971. case LLAMA_FTYPE_MOSTLY_Q2_K: return "Q2_K - Medium";
  2972. case LLAMA_FTYPE_MOSTLY_Q2_K_S: return "Q2_K - Small";
  2973. case LLAMA_FTYPE_MOSTLY_Q3_K_S: return "Q3_K - Small";
  2974. case LLAMA_FTYPE_MOSTLY_Q3_K_M: return "Q3_K - Medium";
  2975. case LLAMA_FTYPE_MOSTLY_Q3_K_L: return "Q3_K - Large";
  2976. case LLAMA_FTYPE_MOSTLY_Q4_K_S: return "Q4_K - Small";
  2977. case LLAMA_FTYPE_MOSTLY_Q4_K_M: return "Q4_K - Medium";
  2978. case LLAMA_FTYPE_MOSTLY_Q5_K_S: return "Q5_K - Small";
  2979. case LLAMA_FTYPE_MOSTLY_Q5_K_M: return "Q5_K - Medium";
  2980. case LLAMA_FTYPE_MOSTLY_Q6_K: return "Q6_K";
  2981. case LLAMA_FTYPE_MOSTLY_IQ2_XXS:return "IQ2_XXS - 2.0625 bpw";
  2982. case LLAMA_FTYPE_MOSTLY_IQ2_XS: return "IQ2_XS - 2.3125 bpw";
  2983. case LLAMA_FTYPE_MOSTLY_IQ2_S: return "IQ2_S - 2.5 bpw";
  2984. case LLAMA_FTYPE_MOSTLY_IQ2_M: return "IQ2_M - 2.7 bpw";
  2985. case LLAMA_FTYPE_MOSTLY_IQ3_XS: return "IQ3_XS - 3.3 bpw";
  2986. case LLAMA_FTYPE_MOSTLY_IQ3_XXS:return "IQ3_XXS - 3.0625 bpw";
  2987. case LLAMA_FTYPE_MOSTLY_IQ1_S :return "IQ1_S - 1.5625 bpw";
  2988. case LLAMA_FTYPE_MOSTLY_IQ1_M :return "IQ1_M - 1.75 bpw";
  2989. case LLAMA_FTYPE_MOSTLY_IQ4_NL: return "IQ4_NL - 4.5 bpw";
  2990. case LLAMA_FTYPE_MOSTLY_IQ4_XS: return "IQ4_XS - 4.25 bpw";
  2991. case LLAMA_FTYPE_MOSTLY_IQ3_S: return "IQ3_S - 3.4375 bpw";
  2992. case LLAMA_FTYPE_MOSTLY_IQ3_M: return "IQ3_S mix - 3.66 bpw";
  2993. default: return "unknown, may not work";
  2994. }
  2995. }
  2996. static const char * llama_model_type_name(e_model type) {
  2997. switch (type) {
  2998. case MODEL_22M: return "22M";
  2999. case MODEL_33M: return "33M";
  3000. case MODEL_109M: return "109M";
  3001. case MODEL_137M: return "137M";
  3002. case MODEL_0_5B: return "0.5B";
  3003. case MODEL_1B: return "1B";
  3004. case MODEL_2B: return "2B";
  3005. case MODEL_3B: return "3B";
  3006. case MODEL_7B: return "7B";
  3007. case MODEL_8B: return "8B";
  3008. case MODEL_13B: return "13B";
  3009. case MODEL_14B: return "14B";
  3010. case MODEL_15B: return "15B";
  3011. case MODEL_20B: return "20B";
  3012. case MODEL_30B: return "30B";
  3013. case MODEL_34B: return "34B";
  3014. case MODEL_35B: return "35B";
  3015. case MODEL_40B: return "40B";
  3016. case MODEL_65B: return "65B";
  3017. case MODEL_70B: return "70B";
  3018. case MODEL_314B: return "314B";
  3019. case MODEL_SMALL: return "0.1B";
  3020. case MODEL_MEDIUM: return "0.4B";
  3021. case MODEL_LARGE: return "0.8B";
  3022. case MODEL_XL: return "1.5B";
  3023. default: return "?B";
  3024. }
  3025. }
  3026. static const char * llama_model_vocab_type_name(enum llama_vocab_type type){
  3027. switch (type) {
  3028. case LLAMA_VOCAB_TYPE_NONE: return "no vocab";
  3029. case LLAMA_VOCAB_TYPE_SPM: return "SPM";
  3030. case LLAMA_VOCAB_TYPE_BPE: return "BPE";
  3031. case LLAMA_VOCAB_TYPE_WPM: return "WPM";
  3032. default: return "unknown";
  3033. }
  3034. }
  3035. static void llm_load_arch(llama_model_loader & ml, llama_model & model) {
  3036. model.arch = ml.get_arch();
  3037. if (model.arch == LLM_ARCH_UNKNOWN) {
  3038. throw std::runtime_error("unknown model architecture: '" + ml.get_arch_name() + "'");
  3039. }
  3040. }
  3041. static void llm_load_hparams(
  3042. llama_model_loader & ml,
  3043. llama_model & model) {
  3044. auto & hparams = model.hparams;
  3045. const gguf_context * ctx = ml.meta;
  3046. // get metadata as string
  3047. for (int i = 0; i < gguf_get_n_kv(ctx); i++) {
  3048. enum gguf_type type = gguf_get_kv_type(ctx, i);
  3049. if (type == GGUF_TYPE_ARRAY) {
  3050. continue;
  3051. }
  3052. const char * name = gguf_get_key(ctx, i);
  3053. const std::string value = gguf_kv_to_str(ctx, i);
  3054. model.gguf_kv.emplace(name, value);
  3055. }
  3056. // get general kv
  3057. ml.get_key(LLM_KV_GENERAL_NAME, model.name, false);
  3058. // get hparams kv
  3059. ml.get_key(LLM_KV_VOCAB_SIZE, hparams.n_vocab, false) || ml.get_arr_n(LLM_KV_TOKENIZER_LIST, hparams.n_vocab);
  3060. ml.get_key(LLM_KV_CONTEXT_LENGTH, hparams.n_ctx_train);
  3061. ml.get_key(LLM_KV_EMBEDDING_LENGTH, hparams.n_embd);
  3062. ml.get_key(LLM_KV_FEED_FORWARD_LENGTH, hparams.n_ff);
  3063. ml.get_key(LLM_KV_ATTENTION_HEAD_COUNT, hparams.n_head);
  3064. ml.get_key(LLM_KV_BLOCK_COUNT, hparams.n_layer);
  3065. ml.get_key(LLM_KV_EXPERT_COUNT, hparams.n_expert, false);
  3066. ml.get_key(LLM_KV_EXPERT_USED_COUNT, hparams.n_expert_used, false);
  3067. GGML_ASSERT(hparams.n_expert <= LLAMA_MAX_EXPERTS);
  3068. GGML_ASSERT(hparams.n_expert_used <= hparams.n_expert);
  3069. if (hparams.n_expert > 0) {
  3070. GGML_ASSERT(hparams.n_expert_used > 0);
  3071. } else {
  3072. GGML_ASSERT(hparams.n_expert_used == 0);
  3073. }
  3074. // n_head_kv is optional, default to n_head
  3075. hparams.n_head_kv = hparams.n_head;
  3076. ml.get_key(LLM_KV_ATTENTION_HEAD_COUNT_KV, hparams.n_head_kv, false);
  3077. bool rope_finetuned = false;
  3078. ml.get_key(LLM_KV_ROPE_SCALING_FINETUNED, rope_finetuned, false);
  3079. hparams.rope_finetuned = rope_finetuned;
  3080. hparams.n_yarn_orig_ctx = hparams.n_ctx_train;
  3081. ml.get_key(LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, hparams.n_yarn_orig_ctx, false);
  3082. // rope_freq_base (optional)
  3083. hparams.rope_freq_base_train = 10000.0f;
  3084. ml.get_key(LLM_KV_ROPE_FREQ_BASE, hparams.rope_freq_base_train, false);
  3085. std::string rope_scaling("linear");
  3086. ml.get_key(LLM_KV_ROPE_SCALING_TYPE, rope_scaling, false);
  3087. hparams.rope_scaling_type_train = llama_rope_scaling_type_from_string(rope_scaling);
  3088. GGML_ASSERT(hparams.rope_scaling_type_train != LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED);
  3089. // rope_freq_scale (inverse of the kv) is optional
  3090. float ropescale = 0.0f;
  3091. if (!ml.get_key(LLM_KV_ROPE_SCALING_FACTOR, ropescale, false)) {
  3092. // try the old key name
  3093. ml.get_key(LLM_KV_ROPE_SCALE_LINEAR, ropescale, false);
  3094. }
  3095. hparams.rope_freq_scale_train = ropescale == 0.0f ? 1.0f : 1.0f/ropescale;
  3096. // sanity check for n_rot (optional)
  3097. {
  3098. hparams.n_rot = (hparams.n_head == 0) ? 0 : hparams.n_embd / hparams.n_head;
  3099. ml.get_key(LLM_KV_ROPE_DIMENSION_COUNT, hparams.n_rot, false);
  3100. if (model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON) {
  3101. if (hparams.n_rot != hparams.n_embd / hparams.n_head) {
  3102. throw std::runtime_error(format("invalid n_rot: %u, expected %u", hparams.n_rot, hparams.n_embd / hparams.n_head));
  3103. }
  3104. }
  3105. // gpt-neox n_rot = rotary_pct * (n_embd / n_head)
  3106. // gpt-j n_rot = rotary_dim
  3107. }
  3108. hparams.n_embd_head_k = (hparams.n_head == 0) ? 0 : hparams.n_embd / hparams.n_head;
  3109. ml.get_key(LLM_KV_ATTENTION_KEY_LENGTH, hparams.n_embd_head_k, false);
  3110. hparams.n_embd_head_v = (hparams.n_head == 0) ? 0 : hparams.n_embd / hparams.n_head;
  3111. ml.get_key(LLM_KV_ATTENTION_VALUE_LENGTH, hparams.n_embd_head_v, false);
  3112. // arch-specific KVs
  3113. switch (model.arch) {
  3114. case LLM_ARCH_LLAMA:
  3115. {
  3116. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3117. switch (hparams.n_layer) {
  3118. case 22: model.type = e_model::MODEL_1B; break;
  3119. case 26: model.type = e_model::MODEL_3B; break;
  3120. case 32: model.type = e_model::MODEL_7B; break;
  3121. case 40: model.type = e_model::MODEL_13B; break;
  3122. case 48: model.type = e_model::MODEL_34B; break;
  3123. case 60: model.type = e_model::MODEL_30B; break;
  3124. case 80: model.type = hparams.n_head == hparams.n_head_kv ? e_model::MODEL_65B : e_model::MODEL_70B; break;
  3125. default: model.type = e_model::MODEL_UNKNOWN;
  3126. }
  3127. } break;
  3128. case LLM_ARCH_MINICPM:
  3129. {
  3130. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3131. switch (hparams.n_layer) {
  3132. case 40: model.type = e_model::MODEL_2B; break;
  3133. default: model.type = e_model::MODEL_UNKNOWN;
  3134. }
  3135. } break;
  3136. case LLM_ARCH_GROK:
  3137. {
  3138. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3139. switch (hparams.n_layer) {
  3140. case 64: model.type = e_model::MODEL_314B; break;
  3141. default: model.type = e_model::MODEL_UNKNOWN;
  3142. }
  3143. } break;
  3144. case LLM_ARCH_FALCON:
  3145. {
  3146. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3147. switch (hparams.n_layer) {
  3148. case 32: model.type = e_model::MODEL_7B; break;
  3149. case 60: model.type = e_model::MODEL_40B; break;
  3150. default: model.type = e_model::MODEL_UNKNOWN;
  3151. }
  3152. } break;
  3153. case LLM_ARCH_BAICHUAN:
  3154. {
  3155. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3156. switch (hparams.n_layer) {
  3157. case 32: model.type = e_model::MODEL_7B; break;
  3158. case 40: model.type = e_model::MODEL_13B; break;
  3159. default: model.type = e_model::MODEL_UNKNOWN;
  3160. }
  3161. if (model.type == e_model::MODEL_13B) {
  3162. // TODO: become GGUF KV parameter
  3163. hparams.f_max_alibi_bias = 8.0f;
  3164. }
  3165. } break;
  3166. case LLM_ARCH_STARCODER:
  3167. {
  3168. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3169. switch (hparams.n_layer) {
  3170. case 24: model.type = e_model::MODEL_1B; break;
  3171. case 36: model.type = e_model::MODEL_3B; break;
  3172. case 42: model.type = e_model::MODEL_7B; break;
  3173. case 40: model.type = e_model::MODEL_15B; break;
  3174. default: model.type = e_model::MODEL_UNKNOWN;
  3175. }
  3176. } break;
  3177. case LLM_ARCH_PERSIMMON:
  3178. {
  3179. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3180. switch (hparams.n_layer) {
  3181. case 36: model.type = e_model::MODEL_8B; break;
  3182. default: model.type = e_model::MODEL_UNKNOWN;
  3183. }
  3184. } break;
  3185. case LLM_ARCH_REFACT:
  3186. {
  3187. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3188. switch (hparams.n_layer) {
  3189. case 32: model.type = e_model::MODEL_1B; break;
  3190. default: model.type = e_model::MODEL_UNKNOWN;
  3191. }
  3192. // TODO: become GGUF KV parameter
  3193. hparams.f_max_alibi_bias = 8.0f;
  3194. } break;
  3195. case LLM_ARCH_BERT:
  3196. {
  3197. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3198. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  3199. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  3200. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type, false);
  3201. switch (hparams.n_layer) {
  3202. case 3:
  3203. model.type = e_model::MODEL_17M; break; // bge-micro
  3204. case 6:
  3205. model.type = e_model::MODEL_22M; break; // MiniLM-L6
  3206. case 12:
  3207. switch (hparams.n_embd) {
  3208. case 384: model.type = e_model::MODEL_33M; break; // MiniLM-L12, bge-small
  3209. case 768: model.type = e_model::MODEL_109M; break; // bge-base
  3210. } break;
  3211. case 24:
  3212. model.type = e_model::MODEL_335M; break; // bge-large
  3213. }
  3214. } break;
  3215. case LLM_ARCH_NOMIC_BERT:
  3216. {
  3217. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3218. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  3219. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  3220. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type);
  3221. if (hparams.n_layer == 12 && hparams.n_embd == 768) {
  3222. model.type = e_model::MODEL_137M;
  3223. }
  3224. } break;
  3225. case LLM_ARCH_BLOOM:
  3226. {
  3227. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3228. switch (hparams.n_layer) {
  3229. case 24: model.type = e_model::MODEL_1B; break;
  3230. case 30:
  3231. switch (hparams.n_embd) {
  3232. case 2560: model.type = e_model::MODEL_3B; break;
  3233. case 4096: model.type = e_model::MODEL_7B; break;
  3234. } break;
  3235. }
  3236. // TODO: become GGUF KV parameter
  3237. hparams.f_max_alibi_bias = 8.0f;
  3238. } break;
  3239. case LLM_ARCH_MPT:
  3240. {
  3241. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3242. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv, false);
  3243. ml.get_key(LLM_KV_ATTENTION_MAX_ALIBI_BIAS, hparams.f_max_alibi_bias);
  3244. switch (hparams.n_layer) {
  3245. case 32: model.type = e_model::MODEL_7B; break;
  3246. case 48: model.type = e_model::MODEL_30B; break;
  3247. default: model.type = e_model::MODEL_UNKNOWN;
  3248. }
  3249. } break;
  3250. case LLM_ARCH_STABLELM:
  3251. {
  3252. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3253. switch (hparams.n_layer) {
  3254. case 24: model.type = e_model::MODEL_1B; break;
  3255. case 32: model.type = e_model::MODEL_3B; break;
  3256. default: model.type = e_model::MODEL_UNKNOWN;
  3257. }
  3258. } break;
  3259. case LLM_ARCH_QWEN:
  3260. {
  3261. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3262. switch (hparams.n_layer) {
  3263. case 32: model.type = e_model::MODEL_7B; break;
  3264. case 40: model.type = e_model::MODEL_13B; break;
  3265. default: model.type = e_model::MODEL_UNKNOWN;
  3266. }
  3267. } break;
  3268. case LLM_ARCH_QWEN2:
  3269. {
  3270. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3271. switch (hparams.n_layer) {
  3272. case 24: model.type = hparams.n_embd == 1024 ? e_model::MODEL_0_5B : e_model::MODEL_1B; break;
  3273. case 32: model.type = e_model::MODEL_7B; break;
  3274. case 40: model.type = hparams.n_head == 20 ? e_model::MODEL_4B : e_model::MODEL_13B; break;
  3275. case 80: model.type = e_model::MODEL_70B; break;
  3276. default: model.type = e_model::MODEL_UNKNOWN;
  3277. }
  3278. } break;
  3279. case LLM_ARCH_PHI2:
  3280. {
  3281. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3282. switch (hparams.n_layer) {
  3283. case 24: model.type = e_model::MODEL_1B; break;
  3284. case 32: model.type = e_model::MODEL_3B; break;
  3285. default: model.type = e_model::MODEL_UNKNOWN;
  3286. }
  3287. } break;
  3288. case LLM_ARCH_PLAMO:
  3289. {
  3290. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3291. switch (hparams.n_layer) {
  3292. case 40: model.type = e_model::MODEL_13B; break;
  3293. default: model.type = e_model::MODEL_UNKNOWN;
  3294. }
  3295. } break;
  3296. case LLM_ARCH_GPT2:
  3297. {
  3298. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3299. switch (hparams.n_layer) {
  3300. case 12: model.type = e_model::MODEL_SMALL; break;
  3301. case 24: model.type = e_model::MODEL_MEDIUM; break;
  3302. case 36: model.type = e_model::MODEL_LARGE; break;
  3303. case 48: model.type = e_model::MODEL_XL; break;
  3304. default: model.type = e_model::MODEL_UNKNOWN;
  3305. }
  3306. } break;
  3307. case LLM_ARCH_CODESHELL:
  3308. {
  3309. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3310. switch (hparams.n_layer) {
  3311. case 42: model.type = e_model::MODEL_SMALL; break;
  3312. default: model.type = e_model::MODEL_UNKNOWN;
  3313. }
  3314. } break;
  3315. case LLM_ARCH_ORION:
  3316. {
  3317. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3318. switch (hparams.n_layer) {
  3319. case 40: model.type = e_model::MODEL_14B; break;
  3320. default: model.type = e_model::MODEL_UNKNOWN;
  3321. }
  3322. } break;
  3323. case LLM_ARCH_INTERNLM2:
  3324. {
  3325. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3326. switch (hparams.n_layer) {
  3327. case 32: model.type = e_model::MODEL_7B; break;
  3328. case 48: model.type = e_model::MODEL_20B; break;
  3329. default: model.type = e_model::MODEL_UNKNOWN;
  3330. }
  3331. } break;
  3332. case LLM_ARCH_GEMMA:
  3333. {
  3334. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3335. switch (hparams.n_layer) {
  3336. case 18: model.type = e_model::MODEL_2B; break;
  3337. case 28: model.type = e_model::MODEL_7B; break;
  3338. default: model.type = e_model::MODEL_UNKNOWN;
  3339. }
  3340. } break;
  3341. case LLM_ARCH_STARCODER2:
  3342. {
  3343. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3344. switch (hparams.n_layer) {
  3345. case 30: model.type = e_model::MODEL_3B; break;
  3346. case 32: model.type = e_model::MODEL_7B; break;
  3347. case 40: model.type = e_model::MODEL_15B; break;
  3348. default: model.type = e_model::MODEL_UNKNOWN;
  3349. }
  3350. } break;
  3351. case LLM_ARCH_MAMBA:
  3352. {
  3353. ml.get_key(LLM_KV_SSM_CONV_KERNEL, hparams.ssm_d_conv);
  3354. ml.get_key(LLM_KV_SSM_INNER_SIZE, hparams.ssm_d_inner);
  3355. ml.get_key(LLM_KV_SSM_STATE_SIZE, hparams.ssm_d_state);
  3356. ml.get_key(LLM_KV_SSM_TIME_STEP_RANK, hparams.ssm_dt_rank);
  3357. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3358. switch (hparams.n_layer) {
  3359. case 24:
  3360. switch (hparams.n_embd) {
  3361. case 768: model.type = e_model::MODEL_SMALL; break;
  3362. default: model.type = e_model::MODEL_UNKNOWN;
  3363. } break;
  3364. case 48:
  3365. switch (hparams.n_embd) {
  3366. case 1024: model.type = e_model::MODEL_MEDIUM; break;
  3367. case 1536: model.type = e_model::MODEL_LARGE; break;
  3368. case 2048: model.type = e_model::MODEL_XL; break;
  3369. default: model.type = e_model::MODEL_UNKNOWN;
  3370. } break;
  3371. case 64:
  3372. switch (hparams.n_embd) {
  3373. case 2560: model.type = e_model::MODEL_3B; break;
  3374. default: model.type = e_model::MODEL_UNKNOWN;
  3375. } break;
  3376. default: model.type = e_model::MODEL_UNKNOWN;
  3377. }
  3378. } break;
  3379. case LLM_ARCH_XVERSE:
  3380. {
  3381. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3382. switch (hparams.n_layer) {
  3383. case 32: model.type = e_model::MODEL_7B; break;
  3384. case 40: model.type = e_model::MODEL_13B; break;
  3385. case 80: model.type = e_model::MODEL_65B; break;
  3386. default: model.type = e_model::MODEL_UNKNOWN;
  3387. }
  3388. } break;
  3389. case LLM_ARCH_COMMAND_R:
  3390. {
  3391. ml.get_key(LLM_KV_LOGIT_SCALE, hparams.f_logit_scale);
  3392. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3393. switch (hparams.n_layer) {
  3394. case 40: model.type = e_model::MODEL_35B; break;
  3395. default: model.type = e_model::MODEL_UNKNOWN;
  3396. }
  3397. } break;
  3398. default: (void)0;
  3399. }
  3400. model.ftype = ml.ftype;
  3401. if (hparams.f_max_alibi_bias > 0.0f) {
  3402. hparams.need_kq_pos = true;
  3403. }
  3404. hparams.rope_type = llama_rope_type(&model);
  3405. }
  3406. // TODO: This should probably be in llama.h
  3407. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special = false);
  3408. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch);
  3409. static void llm_load_vocab(
  3410. llama_model_loader & ml,
  3411. llama_model & model) {
  3412. auto & vocab = model.vocab;
  3413. struct gguf_context * ctx = ml.meta;
  3414. const auto kv = LLM_KV(model.arch);
  3415. // determine vocab type
  3416. {
  3417. std::string tokenizer_name;
  3418. ml.get_key(LLM_KV_TOKENIZER_MODEL, tokenizer_name);
  3419. if (tokenizer_name == "no_vocab") {
  3420. vocab.type = LLAMA_VOCAB_TYPE_NONE;
  3421. // default special tokens
  3422. vocab.special_bos_id = -1;
  3423. vocab.special_eos_id = -1;
  3424. vocab.special_unk_id = -1;
  3425. vocab.special_sep_id = -1;
  3426. vocab.special_pad_id = -1;
  3427. vocab.linefeed_id = -1;
  3428. return;
  3429. } else if (tokenizer_name == "llama") {
  3430. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  3431. // default special tokens
  3432. vocab.special_bos_id = 1;
  3433. vocab.special_eos_id = 2;
  3434. vocab.special_unk_id = 0;
  3435. vocab.special_sep_id = -1;
  3436. vocab.special_pad_id = -1;
  3437. const int add_space_prefix_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_ADD_PREFIX).c_str());
  3438. if (add_space_prefix_keyidx != -1) {
  3439. vocab.add_space_prefix = gguf_get_val_bool(ctx, add_space_prefix_keyidx);
  3440. } // The default value of add_space_prefix is true.
  3441. } else if (tokenizer_name == "gpt2") {
  3442. vocab.type = LLAMA_VOCAB_TYPE_BPE;
  3443. // read bpe merges and populate bpe ranks
  3444. const int merges_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_MERGES).c_str());
  3445. if (merges_keyidx == -1) {
  3446. throw std::runtime_error("cannot find tokenizer merges in model file\n");
  3447. }
  3448. const int n_merges = gguf_get_arr_n(ctx, merges_keyidx);
  3449. for (int i = 0; i < n_merges; i++) {
  3450. const std::string word = gguf_get_arr_str(ctx, merges_keyidx, i);
  3451. GGML_ASSERT(unicode_cpts_from_utf8(word).size() > 0);
  3452. std::string first;
  3453. std::string second;
  3454. const size_t pos = word.find(' ', 1);
  3455. if (pos != std::string::npos) {
  3456. first = word.substr(0, pos);
  3457. second = word.substr(pos + 1);
  3458. }
  3459. vocab.bpe_ranks.emplace(std::make_pair(first, second), i);
  3460. }
  3461. // default special tokens
  3462. vocab.special_bos_id = 11;
  3463. vocab.special_eos_id = 11;
  3464. vocab.special_unk_id = -1;
  3465. vocab.special_sep_id = -1;
  3466. vocab.special_pad_id = -1;
  3467. } else if (tokenizer_name == "bert") {
  3468. vocab.type = LLAMA_VOCAB_TYPE_WPM;
  3469. // default special tokens
  3470. vocab.special_bos_id = 101;
  3471. vocab.special_eos_id = 102;
  3472. vocab.special_unk_id = 100;
  3473. vocab.special_sep_id = -1;
  3474. vocab.special_pad_id = -1;
  3475. vocab.add_space_prefix = false;
  3476. } else {
  3477. LLAMA_LOG_WARN("%s: unknown tokenizer: '%s'", __func__, tokenizer_name.c_str());
  3478. LLAMA_LOG_WARN("%s: using default tokenizer: 'llama'", __func__);
  3479. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  3480. }
  3481. }
  3482. const int token_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_LIST).c_str());
  3483. if (token_idx == -1) {
  3484. throw std::runtime_error("cannot find tokenizer vocab in model file\n");
  3485. }
  3486. const float * scores = nullptr;
  3487. const int score_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_SCORES).c_str());
  3488. if (score_idx != -1) {
  3489. scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
  3490. }
  3491. const int * toktypes = nullptr;
  3492. const int toktype_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE).c_str());
  3493. if (toktype_idx != -1) {
  3494. toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
  3495. }
  3496. const uint32_t n_vocab = gguf_get_arr_n(ctx, token_idx);
  3497. vocab.id_to_token.resize(n_vocab);
  3498. for (uint32_t i = 0; i < n_vocab; i++) {
  3499. std::string word = gguf_get_arr_str(ctx, token_idx, i);
  3500. GGML_ASSERT(unicode_cpts_from_utf8(word).size() > 0);
  3501. vocab.token_to_id[word] = i;
  3502. auto & token_data = vocab.id_to_token[i];
  3503. token_data.text = std::move(word);
  3504. token_data.score = scores ? scores[i] : 0.0f;
  3505. token_data.type = toktypes ? (llama_token_type) toktypes[i] : LLAMA_TOKEN_TYPE_NORMAL;
  3506. }
  3507. GGML_ASSERT(vocab.id_to_token.size() == vocab.token_to_id.size());
  3508. // determine the newline token: LLaMA "<0x0A>" == 10 == '\n', Falcon 193 == '\n'
  3509. if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  3510. try {
  3511. vocab.linefeed_id = llama_byte_to_token(vocab, '\n');
  3512. } catch (const std::exception & e) {
  3513. LLAMA_LOG_WARN("%s: SPM vocabulary, but newline token not found: %s! Using special_pad_id instead.", __func__, e.what());
  3514. vocab.linefeed_id = vocab.special_pad_id;
  3515. }
  3516. } else if (vocab.type == LLAMA_VOCAB_TYPE_WPM) {
  3517. vocab.linefeed_id = vocab.special_pad_id;
  3518. } else {
  3519. const std::vector<int> ids = llama_tokenize_internal(vocab, "\xC4\x8A", false); // U+010A
  3520. GGML_ASSERT(!ids.empty() && "model vocab missing newline token");
  3521. vocab.linefeed_id = ids[0];
  3522. }
  3523. // special tokens
  3524. {
  3525. const std::vector<std::pair<enum llm_kv, int32_t &>> special_token_types = {
  3526. { LLM_KV_TOKENIZER_BOS_ID, vocab.special_bos_id },
  3527. { LLM_KV_TOKENIZER_EOS_ID, vocab.special_eos_id },
  3528. { LLM_KV_TOKENIZER_UNK_ID, vocab.special_unk_id },
  3529. { LLM_KV_TOKENIZER_SEP_ID, vocab.special_sep_id },
  3530. { LLM_KV_TOKENIZER_PAD_ID, vocab.special_pad_id },
  3531. };
  3532. for (const auto & it : special_token_types) {
  3533. const std::string & key = kv(std::get<0>(it));
  3534. int32_t & id = std::get<1>(it);
  3535. uint32_t new_id;
  3536. if (!ml.get_key(std::get<0>(it), new_id, false)) {
  3537. continue;
  3538. }
  3539. if (new_id >= vocab.id_to_token.size()) {
  3540. LLAMA_LOG_WARN("%s: bad special token: '%s' = %ud, using default id %d\n",
  3541. __func__, key.c_str(), new_id, id);
  3542. } else {
  3543. id = new_id;
  3544. }
  3545. }
  3546. // Handle add_bos_token and add_eos_token
  3547. {
  3548. bool temp = true;
  3549. if (ml.get_key(LLM_KV_TOKENIZER_ADD_BOS, temp, false)) {
  3550. vocab.special_add_bos = int(temp);
  3551. }
  3552. if (ml.get_key(LLM_KV_TOKENIZER_ADD_EOS, temp, false)) {
  3553. vocab.special_add_eos = int(temp);
  3554. }
  3555. }
  3556. }
  3557. // build special tokens cache
  3558. {
  3559. // TODO: It is unclear (to me) at this point, whether special tokes are guaranteed to be of a deterministic type,
  3560. // and will always be correctly labeled in 'added_tokens.json' etc.
  3561. // The assumption is, since special tokens aren't meant to be exposed to end user, they are designed
  3562. // to be unmatchable by the tokenizer, therefore tokens from the vocab, which are unmatchable by the tokenizer
  3563. // are special tokens.
  3564. // From testing, this appears to correlate 1:1 with special tokens.
  3565. //
  3566. // Counting special tokens and verifying in only one direction
  3567. // is sufficient to detect difference in those two sets.
  3568. //
  3569. uint32_t special_tokens_count_by_type = 0;
  3570. uint32_t special_tokens_count_from_verification = 0;
  3571. bool special_tokens_definition_mismatch = false;
  3572. for (const auto & t : vocab.token_to_id) {
  3573. const auto & token = t.first;
  3574. const auto & id = t.second;
  3575. // Count all non-normal tokens in the vocab while iterating
  3576. if (vocab.id_to_token[id].type != LLAMA_TOKEN_TYPE_NORMAL) {
  3577. special_tokens_count_by_type++;
  3578. }
  3579. // Skip single character tokens
  3580. if (token.length() > 1) {
  3581. bool is_tokenizable = false;
  3582. // Split token string representation in two, in all possible ways
  3583. // and check if both halves can be matched to a valid token
  3584. for (unsigned i = 1; i < token.length();) {
  3585. const auto left = token.substr(0, i);
  3586. const auto right = token.substr(i);
  3587. // check if we didnt partition in the middle of a utf sequence
  3588. auto utf = utf8_len(left.at(left.length() - 1));
  3589. if (utf == 1) {
  3590. if (vocab.token_to_id.find(left) != vocab.token_to_id.end() &&
  3591. vocab.token_to_id.find(right) != vocab.token_to_id.end() ) {
  3592. is_tokenizable = true;
  3593. break;
  3594. }
  3595. i++;
  3596. } else {
  3597. // skip over the rest of multibyte utf sequence
  3598. i += utf - 1;
  3599. }
  3600. }
  3601. if (!is_tokenizable) {
  3602. // Some tokens are multibyte, but they are utf sequences with equivalent text length of 1
  3603. // it's faster to re-filter them here, since there are way less candidates now
  3604. // Calculate a total "utf" length of a token string representation
  3605. size_t utf8_str_len = 0;
  3606. for (unsigned i = 0; i < token.length();) {
  3607. utf8_str_len++;
  3608. i += utf8_len(token.at(i));
  3609. }
  3610. // And skip the ones which are one character
  3611. if (utf8_str_len > 1) {
  3612. // At this point what we have left are special tokens only
  3613. vocab.special_tokens_cache[token] = id;
  3614. // Count manually found special tokens
  3615. special_tokens_count_from_verification++;
  3616. // If this manually found special token is not marked as such, flag a mismatch
  3617. if (vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL) {
  3618. special_tokens_definition_mismatch = true;
  3619. }
  3620. }
  3621. }
  3622. }
  3623. }
  3624. if (special_tokens_definition_mismatch || special_tokens_count_from_verification != special_tokens_count_by_type) {
  3625. LLAMA_LOG_WARN("%s: mismatch in special tokens definition ( %u/%zu vs %u/%zu ).\n",
  3626. __func__,
  3627. special_tokens_count_from_verification, vocab.id_to_token.size(),
  3628. special_tokens_count_by_type, vocab.id_to_token.size()
  3629. );
  3630. } else {
  3631. LLAMA_LOG_INFO("%s: special tokens definition check successful ( %u/%zu ).\n",
  3632. __func__,
  3633. special_tokens_count_from_verification, vocab.id_to_token.size()
  3634. );
  3635. }
  3636. }
  3637. }
  3638. static void llm_load_print_meta(llama_model_loader & ml, llama_model & model) {
  3639. const auto & hparams = model.hparams;
  3640. const auto & vocab = model.vocab;
  3641. const char * rope_scaling_type = LLAMA_ROPE_SCALING_TYPES.at(hparams.rope_scaling_type_train);
  3642. // hparams
  3643. LLAMA_LOG_INFO("%s: format = %s\n", __func__, llama_file_version_name(ml.fver));
  3644. LLAMA_LOG_INFO("%s: arch = %s\n", __func__, LLM_ARCH_NAMES.at(model.arch));
  3645. LLAMA_LOG_INFO("%s: vocab type = %s\n", __func__, llama_model_vocab_type_name(vocab.type));
  3646. LLAMA_LOG_INFO("%s: n_vocab = %u\n", __func__, hparams.n_vocab);
  3647. LLAMA_LOG_INFO("%s: n_merges = %u\n", __func__, (int) vocab.bpe_ranks.size());
  3648. LLAMA_LOG_INFO("%s: n_ctx_train = %u\n", __func__, hparams.n_ctx_train);
  3649. LLAMA_LOG_INFO("%s: n_embd = %u\n", __func__, hparams.n_embd);
  3650. LLAMA_LOG_INFO("%s: n_head = %u\n", __func__, hparams.n_head);
  3651. LLAMA_LOG_INFO("%s: n_head_kv = %u\n", __func__, hparams.n_head_kv);
  3652. LLAMA_LOG_INFO("%s: n_layer = %u\n", __func__, hparams.n_layer);
  3653. LLAMA_LOG_INFO("%s: n_rot = %u\n", __func__, hparams.n_rot);
  3654. LLAMA_LOG_INFO("%s: n_embd_head_k = %u\n", __func__, hparams.n_embd_head_k);
  3655. LLAMA_LOG_INFO("%s: n_embd_head_v = %u\n", __func__, hparams.n_embd_head_v);
  3656. LLAMA_LOG_INFO("%s: n_gqa = %u\n", __func__, hparams.n_gqa());
  3657. LLAMA_LOG_INFO("%s: n_embd_k_gqa = %u\n", __func__, hparams.n_embd_k_gqa());
  3658. LLAMA_LOG_INFO("%s: n_embd_v_gqa = %u\n", __func__, hparams.n_embd_v_gqa());
  3659. LLAMA_LOG_INFO("%s: f_norm_eps = %.1e\n", __func__, hparams.f_norm_eps);
  3660. LLAMA_LOG_INFO("%s: f_norm_rms_eps = %.1e\n", __func__, hparams.f_norm_rms_eps);
  3661. LLAMA_LOG_INFO("%s: f_clamp_kqv = %.1e\n", __func__, hparams.f_clamp_kqv);
  3662. LLAMA_LOG_INFO("%s: f_max_alibi_bias = %.1e\n", __func__, hparams.f_max_alibi_bias);
  3663. LLAMA_LOG_INFO("%s: f_logit_scale = %.1e\n", __func__, hparams.f_logit_scale);
  3664. LLAMA_LOG_INFO("%s: n_ff = %u\n", __func__, hparams.n_ff);
  3665. LLAMA_LOG_INFO("%s: n_expert = %u\n", __func__, hparams.n_expert);
  3666. LLAMA_LOG_INFO("%s: n_expert_used = %u\n", __func__, hparams.n_expert_used);
  3667. LLAMA_LOG_INFO("%s: causal attn = %d\n", __func__, hparams.causal_attn);
  3668. LLAMA_LOG_INFO("%s: pooling type = %d\n", __func__, hparams.pooling_type);
  3669. LLAMA_LOG_INFO("%s: rope type = %d\n", __func__, hparams.rope_type);
  3670. LLAMA_LOG_INFO("%s: rope scaling = %s\n", __func__, rope_scaling_type);
  3671. LLAMA_LOG_INFO("%s: freq_base_train = %.1f\n", __func__, hparams.rope_freq_base_train);
  3672. LLAMA_LOG_INFO("%s: freq_scale_train = %g\n", __func__, hparams.rope_freq_scale_train);
  3673. LLAMA_LOG_INFO("%s: n_yarn_orig_ctx = %u\n", __func__, hparams.n_yarn_orig_ctx);
  3674. LLAMA_LOG_INFO("%s: rope_finetuned = %s\n", __func__, hparams.rope_finetuned ? "yes" : "unknown");
  3675. LLAMA_LOG_INFO("%s: ssm_d_conv = %u\n", __func__, hparams.ssm_d_conv);
  3676. LLAMA_LOG_INFO("%s: ssm_d_inner = %u\n", __func__, hparams.ssm_d_inner);
  3677. LLAMA_LOG_INFO("%s: ssm_d_state = %u\n", __func__, hparams.ssm_d_state);
  3678. LLAMA_LOG_INFO("%s: ssm_dt_rank = %u\n", __func__, hparams.ssm_dt_rank);
  3679. LLAMA_LOG_INFO("%s: model type = %s\n", __func__, llama_model_type_name(model.type));
  3680. LLAMA_LOG_INFO("%s: model ftype = %s\n", __func__, llama_model_ftype_name(model.ftype).c_str());
  3681. if (ml.n_elements >= 1e12) {
  3682. LLAMA_LOG_INFO("%s: model params = %.2f T\n", __func__, ml.n_elements*1e-12);
  3683. } else if (ml.n_elements >= 1e9) {
  3684. LLAMA_LOG_INFO("%s: model params = %.2f B\n", __func__, ml.n_elements*1e-9);
  3685. } else if (ml.n_elements >= 1e6) {
  3686. LLAMA_LOG_INFO("%s: model params = %.2f M\n", __func__, ml.n_elements*1e-6);
  3687. } else {
  3688. LLAMA_LOG_INFO("%s: model params = %.2f K\n", __func__, ml.n_elements*1e-3);
  3689. }
  3690. if (ml.n_bytes < GiB) {
  3691. 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);
  3692. } else {
  3693. 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);
  3694. }
  3695. // general kv
  3696. LLAMA_LOG_INFO("%s: general.name = %s\n", __func__, model.name.c_str());
  3697. // special tokens
  3698. 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() ); }
  3699. 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() ); }
  3700. 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() ); }
  3701. 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() ); }
  3702. 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() ); }
  3703. 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() ); }
  3704. }
  3705. // Returns false if cancelled by progress_callback
  3706. static bool llm_load_tensors(
  3707. llama_model_loader & ml,
  3708. llama_model & model,
  3709. int n_gpu_layers,
  3710. enum llama_split_mode split_mode,
  3711. int main_gpu,
  3712. const float * tensor_split,
  3713. bool use_mlock,
  3714. llama_progress_callback progress_callback,
  3715. void * progress_callback_user_data) {
  3716. model.t_start_us = ggml_time_us();
  3717. auto & hparams = model.hparams;
  3718. model.split_mode = split_mode;
  3719. model.main_gpu = main_gpu;
  3720. model.n_gpu_layers = n_gpu_layers;
  3721. const int64_t n_layer = hparams.n_layer;
  3722. const int64_t i_gpu_start = std::max((int64_t) hparams.n_layer - n_gpu_layers, (int64_t) 0);
  3723. // there is very little benefit to offloading the input layer, so always keep it on the CPU
  3724. model.buft_input = llama_default_buffer_type_cpu(true);
  3725. //model.buft_input = llama_default_buffer_type_offload(main_gpu);
  3726. model.buft_layer.resize(n_layer);
  3727. // assign cpu layers
  3728. for (int64_t i = 0; i < i_gpu_start; ++i) {
  3729. model.buft_layer[i] = llama_default_buffer_type_cpu(true);
  3730. }
  3731. if (split_mode == LLAMA_SPLIT_MODE_LAYER) {
  3732. // calculate the split points
  3733. int device_count = llama_get_device_count();
  3734. bool all_zero = tensor_split == nullptr || std::all_of(tensor_split, tensor_split + device_count, [](float x) { return x == 0.0f; });
  3735. std::vector<float> splits(device_count);
  3736. if (all_zero) {
  3737. // default split, by free memory
  3738. for (int i = 0; i < device_count; ++i) {
  3739. splits[i] = llama_get_device_memory(i);
  3740. }
  3741. } else {
  3742. std::copy(tensor_split, tensor_split + device_count, splits.begin());
  3743. }
  3744. // sum and normalize the splits to get the split points
  3745. float split_sum = 0.0f;
  3746. for (int i = 0; i < device_count; ++i) {
  3747. split_sum += splits[i];
  3748. splits[i] = split_sum;
  3749. }
  3750. for (int i = 0; i < device_count; ++i) {
  3751. splits[i] /= split_sum;
  3752. }
  3753. // assign the repeating layers to the devices according to the splits
  3754. int act_gpu_layers = std::min(n_gpu_layers, (int)n_layer + 1);
  3755. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  3756. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(i - i_gpu_start)/act_gpu_layers) - splits.begin();
  3757. model.buft_layer[i] = llama_default_buffer_type_offload(layer_gpu);
  3758. }
  3759. // assign the output layer
  3760. if (n_gpu_layers > n_layer) {
  3761. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(act_gpu_layers - 1)/act_gpu_layers) - splits.begin();
  3762. model.buft_output = llama_default_buffer_type_offload(layer_gpu);
  3763. } else {
  3764. model.buft_output = llama_default_buffer_type_cpu(true);
  3765. }
  3766. } else {
  3767. ggml_backend_buffer_type_t split_buft;
  3768. if (split_mode == LLAMA_SPLIT_MODE_ROW) {
  3769. split_buft = llama_default_buffer_type_split(main_gpu, tensor_split);
  3770. } else {
  3771. // LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_LAYER in backends where it is not supported
  3772. split_buft = llama_default_buffer_type_offload(main_gpu);
  3773. }
  3774. // assign the repeating layers
  3775. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  3776. model.buft_layer[i] = {
  3777. split_buft,
  3778. llama_default_buffer_type_offload(main_gpu)
  3779. };
  3780. }
  3781. // assign the output layer
  3782. if (n_gpu_layers > n_layer) {
  3783. model.buft_output = {
  3784. split_buft,
  3785. llama_default_buffer_type_offload(main_gpu)
  3786. };
  3787. } else {
  3788. model.buft_output = llama_default_buffer_type_cpu(true);
  3789. }
  3790. }
  3791. // count used buffer types
  3792. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  3793. buft_layer_count[model.buft_input.buft]++;
  3794. buft_layer_count[model.buft_input.buft_matrix]++;
  3795. buft_layer_count[model.buft_output.buft]++;
  3796. buft_layer_count[model.buft_output.buft_matrix]++;
  3797. for (int64_t i = 0; i < n_layer; ++i) {
  3798. buft_layer_count[model.buft_layer[i].buft]++;
  3799. buft_layer_count[model.buft_layer[i].buft_matrix]++;
  3800. }
  3801. // create one context per buffer type
  3802. size_t ctx_size = ggml_tensor_overhead()*(ml.n_tensors + 1); // +1 for models where tok_embd is duplicated as output
  3803. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  3804. for (auto & it : buft_layer_count) {
  3805. struct ggml_init_params params = {
  3806. /*.mem_size =*/ ctx_size,
  3807. /*.mem_buffer =*/ NULL,
  3808. /*.no_alloc =*/ true,
  3809. };
  3810. ggml_context * ctx = ggml_init(params);
  3811. if (!ctx) {
  3812. throw std::runtime_error(format("failed to create context"));
  3813. }
  3814. ctx_map[it.first] = ctx;
  3815. model.ctxs.push_back(ctx);
  3816. }
  3817. LLAMA_LOG_INFO("%s: ggml ctx size = %7.2f MiB\n", __func__, model.ctxs.size()*ctx_size/1024.0/1024.0);
  3818. // create tensors for the weights
  3819. {
  3820. const int64_t n_embd = hparams.n_embd;
  3821. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3822. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  3823. const int64_t n_embd_gqa = n_embd_v_gqa;
  3824. const int64_t n_vocab = hparams.n_vocab;
  3825. const int64_t n_vocab_type = hparams.n_vocab_type;
  3826. const int64_t n_ff = hparams.n_ff;
  3827. GGML_ASSERT(n_embd_gqa == n_embd_k_gqa);
  3828. ggml_context * ctx_input = ctx_map.at(model.buft_input.buft);
  3829. ggml_context * ctx_output = ctx_map.at(model.buft_output.buft);
  3830. ggml_context * ctx_output_split = ctx_map.at(model.buft_output.buft_matrix);
  3831. auto ctx_for_layer = [&](int i) { return ctx_map.at(model.buft_layer[i].buft); };
  3832. auto ctx_for_layer_split = [&](int i) { return ctx_map.at(model.buft_layer[i].buft_matrix); };
  3833. model.layers.resize(n_layer);
  3834. const auto tn = LLM_TN(model.arch);
  3835. switch (model.arch) {
  3836. case LLM_ARCH_LLAMA:
  3837. case LLM_ARCH_REFACT:
  3838. case LLM_ARCH_MINICPM:
  3839. {
  3840. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3841. // output
  3842. {
  3843. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3844. if (model.arch != LLM_ARCH_MINICPM){
  3845. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  3846. // if output is NULL, init from the input tok embed
  3847. if (model.output == NULL) {
  3848. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3849. ml.n_created--; // artificial tensor
  3850. ml.size_data += ggml_nbytes(model.output);
  3851. }
  3852. }
  3853. }
  3854. for (int i = 0; i < n_layer; ++i) {
  3855. ggml_context * ctx_layer = ctx_for_layer(i);
  3856. ggml_context * ctx_split = ctx_for_layer_split(i);
  3857. auto & layer = model.layers[i];
  3858. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3859. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3860. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3861. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3862. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3863. // optional bias tensors
  3864. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, false);
  3865. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, false);
  3866. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, false);
  3867. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, false);
  3868. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3869. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd}, false);
  3870. if (layer.ffn_gate_inp == nullptr) {
  3871. GGML_ASSERT(hparams.n_expert == 0);
  3872. GGML_ASSERT(hparams.n_expert_used == 0);
  3873. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3874. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3875. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3876. } else {
  3877. GGML_ASSERT(hparams.n_expert > 0);
  3878. GGML_ASSERT(hparams.n_expert_used > 0);
  3879. // MoE branch
  3880. for (uint32_t x = 0; x < hparams.n_expert; ++x) {
  3881. layer.ffn_gate_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, x), {n_embd, n_ff});
  3882. layer.ffn_down_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, x), { n_ff, n_embd});
  3883. layer.ffn_up_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, x), {n_embd, n_ff});
  3884. }
  3885. }
  3886. }
  3887. } break;
  3888. case LLM_ARCH_GROK:
  3889. {
  3890. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3891. // output
  3892. {
  3893. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3894. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  3895. // if output is NULL, init from the input tok embed
  3896. if (model.output == NULL) {
  3897. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3898. ml.n_created--; // artificial tensor
  3899. ml.size_data += ggml_nbytes(model.output);
  3900. }
  3901. }
  3902. for (int i = 0; i < n_layer; ++i) {
  3903. ggml_context * ctx_layer = ctx_for_layer(i);
  3904. ggml_context * ctx_split = ctx_for_layer_split(i);
  3905. auto & layer = model.layers[i];
  3906. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3907. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3908. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3909. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3910. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3911. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  3912. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3913. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd});
  3914. GGML_ASSERT(hparams.n_expert > 0);
  3915. GGML_ASSERT(hparams.n_expert_used > 0);
  3916. // MoE branch
  3917. for (uint32_t x = 0; x < hparams.n_expert; ++x) {
  3918. layer.ffn_gate_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, x), {n_embd, n_ff});
  3919. layer.ffn_down_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, x), { n_ff, n_embd});
  3920. layer.ffn_up_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, x), {n_embd, n_ff});
  3921. }
  3922. layer.layer_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd});
  3923. }
  3924. } break;
  3925. case LLM_ARCH_BAICHUAN:
  3926. {
  3927. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3928. {
  3929. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3930. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3931. }
  3932. for (int i = 0; i < n_layer; ++i) {
  3933. ggml_context * ctx_layer = ctx_for_layer(i);
  3934. ggml_context * ctx_split = ctx_for_layer_split(i);
  3935. auto & layer = model.layers[i];
  3936. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3937. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3938. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3939. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3940. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3941. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3942. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3943. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3944. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3945. }
  3946. } break;
  3947. case LLM_ARCH_FALCON:
  3948. {
  3949. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3950. // output
  3951. {
  3952. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3953. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3954. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  3955. if (!model.output) {
  3956. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}); // needs to be on GPU
  3957. ml.n_created--; // artificial tensor
  3958. ml.size_data += ggml_nbytes(model.output);
  3959. }
  3960. }
  3961. for (int i = 0; i < n_layer; ++i) {
  3962. ggml_context * ctx_layer = ctx_for_layer(i);
  3963. ggml_context * ctx_split = ctx_for_layer_split(i);
  3964. auto & layer = model.layers[i];
  3965. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3966. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3967. layer.attn_norm_2 = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i), {n_embd}, false);
  3968. layer.attn_norm_2_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "bias", i), {n_embd}, false);
  3969. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3970. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3971. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3972. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3973. }
  3974. } break;
  3975. case LLM_ARCH_STARCODER:
  3976. {
  3977. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3978. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3979. // output
  3980. {
  3981. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3982. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3983. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3984. }
  3985. for (int i = 0; i < n_layer; ++i) {
  3986. ggml_context * ctx_layer = ctx_for_layer(i);
  3987. ggml_context * ctx_split = ctx_for_layer_split(i);
  3988. auto & layer = model.layers[i];
  3989. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3990. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3991. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3992. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3993. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3994. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3995. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3996. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3997. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3998. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3999. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4000. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4001. }
  4002. } break;
  4003. case LLM_ARCH_PERSIMMON:
  4004. {
  4005. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4006. {
  4007. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4008. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4009. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4010. }
  4011. for (int i = 0; i < n_layer; ++i) {
  4012. ggml_context * ctx_layer = ctx_for_layer(i);
  4013. ggml_context * ctx_split = ctx_for_layer_split(i);
  4014. auto & layer = model.layers[i];
  4015. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4016. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4017. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4018. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  4019. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4020. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4021. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4022. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4023. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4024. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4025. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4026. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4027. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {64});
  4028. layer.attn_q_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "bias", i), {64});
  4029. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {64});
  4030. layer.attn_k_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "bias", i), {64});
  4031. }
  4032. } break;
  4033. case LLM_ARCH_BERT:
  4034. case LLM_ARCH_NOMIC_BERT:
  4035. {
  4036. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4037. model.type_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_TYPES, "weight"), {n_embd, n_vocab_type});
  4038. if (model.arch == LLM_ARCH_BERT) {
  4039. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  4040. }
  4041. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  4042. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  4043. for (int i = 0; i < n_layer; ++i) {
  4044. ggml_context * ctx_layer = ctx_for_layer(i);
  4045. ggml_context * ctx_split = ctx_for_layer_split(i);
  4046. auto & layer = model.layers[i];
  4047. if (model.arch == LLM_ARCH_BERT) {
  4048. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4049. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  4050. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4051. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  4052. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4053. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  4054. } else {
  4055. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4056. }
  4057. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4058. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  4059. layer.attn_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "bias", i), {n_embd});
  4060. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4061. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4062. if (model.arch == LLM_ARCH_BERT) {
  4063. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4064. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4065. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4066. } else {
  4067. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4068. }
  4069. layer.layer_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd});
  4070. layer.layer_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "bias", i), {n_embd});
  4071. }
  4072. } break;
  4073. case LLM_ARCH_BLOOM:
  4074. {
  4075. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4076. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  4077. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  4078. // output
  4079. {
  4080. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4081. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4082. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4083. }
  4084. for (int i = 0; i < n_layer; ++i) {
  4085. ggml_context * ctx_layer = ctx_for_layer(i);
  4086. ggml_context * ctx_split = ctx_for_layer_split(i);
  4087. auto & layer = model.layers[i];
  4088. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4089. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4090. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4091. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  4092. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4093. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4094. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4095. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4096. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4097. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4098. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4099. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4100. }
  4101. } break;
  4102. case LLM_ARCH_MPT:
  4103. {
  4104. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4105. // output
  4106. {
  4107. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4108. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, false);
  4109. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  4110. if (!model.output) {
  4111. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}); // needs to be on GPU
  4112. ml.n_created--; // artificial tensor
  4113. ml.size_data += ggml_nbytes(model.output);
  4114. }
  4115. }
  4116. for (int i = 0; i < n_layer; ++i) {
  4117. ggml_context * ctx_layer = ctx_for_layer(i);
  4118. ggml_context * ctx_split = ctx_for_layer_split(i);
  4119. auto & layer = model.layers[i];
  4120. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4121. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, false);
  4122. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4123. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, false);
  4124. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4125. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, false);
  4126. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4127. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, false);
  4128. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4129. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, false);
  4130. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4131. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, false);
  4132. // AWQ ScaleActivation layer
  4133. layer.ffn_act = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_ACT, "scales", i), {n_ff}, false);
  4134. }
  4135. } break;
  4136. case LLM_ARCH_STABLELM:
  4137. {
  4138. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4139. // output
  4140. {
  4141. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4142. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4143. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4144. }
  4145. for (int i = 0; i < n_layer; ++i) {
  4146. ggml_context * ctx_layer = ctx_for_layer(i);
  4147. ggml_context * ctx_split = ctx_for_layer_split(i);
  4148. auto & layer = model.layers[i];
  4149. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4150. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4151. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4152. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4153. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4154. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4155. // optional bias tensors, present in Stable LM 2 1.6B
  4156. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, false);
  4157. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, false);
  4158. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, false);
  4159. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4160. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4161. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4162. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4163. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4164. }
  4165. } break;
  4166. case LLM_ARCH_QWEN:
  4167. {
  4168. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4169. // output
  4170. {
  4171. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4172. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4173. }
  4174. for (int i = 0; i < n_layer; ++i) {
  4175. ggml_context * ctx_layer = ctx_for_layer(i);
  4176. ggml_context * ctx_split = ctx_for_layer_split(i);
  4177. auto & layer = model.layers[i];
  4178. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4179. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd*3});
  4180. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd*3});
  4181. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4182. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4183. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff/2});
  4184. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff/2, n_embd});
  4185. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff/2});
  4186. }
  4187. } break;
  4188. case LLM_ARCH_QWEN2:
  4189. {
  4190. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4191. // output
  4192. {
  4193. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4194. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4195. }
  4196. for (int i = 0; i < n_layer; ++i) {
  4197. ggml_context * ctx_layer = ctx_for_layer(i);
  4198. ggml_context * ctx_split = ctx_for_layer_split(i);
  4199. auto & layer = model.layers[i];
  4200. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4201. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4202. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4203. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4204. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4205. // optional bias tensors
  4206. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  4207. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  4208. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  4209. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4210. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4211. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4212. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4213. }
  4214. } break;
  4215. case LLM_ARCH_PHI2:
  4216. {
  4217. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4218. // output
  4219. {
  4220. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4221. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4222. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4223. model.output_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT, "bias"), {n_vocab});
  4224. }
  4225. for (int i = 0; i < n_layer; ++i) {
  4226. ggml_context * ctx_layer = ctx_for_layer(i);
  4227. ggml_context * ctx_split = ctx_for_layer_split(i);
  4228. auto & layer = model.layers[i];
  4229. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4230. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4231. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, false);
  4232. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, false);
  4233. if (layer.wqkv == nullptr) {
  4234. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4235. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  4236. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4237. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  4238. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4239. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  4240. }
  4241. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4242. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4243. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4244. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4245. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4246. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4247. }
  4248. } break;
  4249. case LLM_ARCH_PLAMO:
  4250. {
  4251. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4252. // output
  4253. {
  4254. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4255. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4256. }
  4257. for (int i = 0; i < n_layer; ++i) {
  4258. ggml_context * ctx_layer = ctx_for_layer(i);
  4259. ggml_context * ctx_split = ctx_for_layer_split(i);
  4260. auto & layer = model.layers[i];
  4261. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4262. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4263. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4264. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4265. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4266. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4267. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4268. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4269. }
  4270. } break;
  4271. case LLM_ARCH_GPT2:
  4272. {
  4273. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4274. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  4275. // output
  4276. {
  4277. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4278. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4279. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4280. }
  4281. for (int i = 0; i < n_layer; ++i) {
  4282. ggml_context * ctx_layer = ctx_for_layer(i);
  4283. ggml_context * ctx_split = ctx_for_layer_split(i);
  4284. auto & layer = model.layers[i];
  4285. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4286. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4287. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4288. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  4289. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4290. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4291. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4292. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4293. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4294. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4295. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4296. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4297. }
  4298. } break;
  4299. case LLM_ARCH_CODESHELL:
  4300. {
  4301. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4302. // output
  4303. {
  4304. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4305. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4306. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4307. }
  4308. for (int i = 0; i < n_layer; ++i) {
  4309. ggml_context * ctx_layer = ctx_for_layer(i);
  4310. ggml_context * ctx_split = ctx_for_layer_split(i);
  4311. auto & layer = model.layers[i];
  4312. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4313. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4314. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4315. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  4316. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4317. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4318. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4319. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4320. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4321. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4322. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4323. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4324. }
  4325. } break;
  4326. case LLM_ARCH_ORION:
  4327. {
  4328. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4329. {
  4330. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4331. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4332. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4333. }
  4334. for (int i = 0; i < n_layer; ++i) {
  4335. ggml_context * ctx_layer = ctx_for_layer(i);
  4336. ggml_context * ctx_split = ctx_for_layer_split(i);
  4337. auto & layer = model.layers[i];
  4338. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4339. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4340. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4341. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4342. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4343. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4344. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4345. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4346. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4347. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4348. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4349. }
  4350. } break;
  4351. case LLM_ARCH_INTERNLM2:
  4352. {
  4353. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4354. // output
  4355. {
  4356. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4357. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4358. }
  4359. for (int i = 0; i < n_layer; ++i) {
  4360. ggml_context * ctx_layer = ctx_for_layer(i);
  4361. ggml_context * ctx_split = ctx_for_layer_split(i);
  4362. auto & layer = model.layers[i];
  4363. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4364. // layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4365. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4366. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4367. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4368. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4369. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4370. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4371. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4372. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4373. }
  4374. } break;
  4375. case LLM_ARCH_GEMMA:
  4376. {
  4377. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4378. // output
  4379. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4380. 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
  4381. ml.n_created--; // artificial tensor
  4382. ml.size_data += ggml_nbytes(model.output);
  4383. const int64_t n_ff = hparams.n_ff;
  4384. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  4385. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  4386. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  4387. for (uint32_t i = 0; i < n_layer; ++i) {
  4388. ggml_context * ctx_layer = ctx_for_layer(i);
  4389. ggml_context * ctx_split = ctx_for_layer_split(i);
  4390. auto & layer = model.layers[i];
  4391. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4392. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * hparams.n_head});
  4393. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  4394. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  4395. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * hparams.n_head, n_embd});
  4396. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4397. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4398. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4399. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4400. }
  4401. } break;
  4402. case LLM_ARCH_STARCODER2:
  4403. {
  4404. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4405. // output
  4406. {
  4407. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4408. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4409. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  4410. // if output is NULL, init from the input tok embed
  4411. if (model.output == NULL) {
  4412. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4413. ml.n_created--; // artificial tensor
  4414. ml.size_data += ggml_nbytes(model.output);
  4415. }
  4416. }
  4417. for (int i = 0; i < n_layer; ++i) {
  4418. ggml_context * ctx_layer = ctx_for_layer(i);
  4419. ggml_context * ctx_split = ctx_for_layer_split(i);
  4420. auto & layer = model.layers[i];
  4421. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4422. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4423. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4424. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4425. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4426. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4427. // optional bias tensors
  4428. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  4429. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  4430. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  4431. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4432. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4433. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4434. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4435. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4436. // optional bias tensors
  4437. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4438. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP , "bias", i), { n_ff});
  4439. }
  4440. } break;
  4441. case LLM_ARCH_MAMBA:
  4442. {
  4443. const int64_t d_conv = hparams.ssm_d_conv;
  4444. const int64_t d_inner = hparams.ssm_d_inner;
  4445. const int64_t d_state = hparams.ssm_d_state;
  4446. const int64_t dt_rank = hparams.ssm_dt_rank;
  4447. // only an expansion factor of 2 is supported for now
  4448. GGML_ASSERT(2 * n_embd == d_inner);
  4449. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4450. // output
  4451. {
  4452. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4453. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  4454. // if output is NULL, init from the input tok embed, duplicated to allow offloading
  4455. if (model.output == NULL) {
  4456. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4457. ml.n_created--; // artificial tensor
  4458. ml.size_data += ggml_nbytes(model.output);
  4459. }
  4460. }
  4461. for (int i = 0; i < n_layer; ++i) {
  4462. ggml_context * ctx_layer = ctx_for_layer(i);
  4463. ggml_context * ctx_split = ctx_for_layer_split(i);
  4464. auto & layer = model.layers[i];
  4465. // norm
  4466. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4467. layer.ssm_in = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_IN, "weight", i), {n_embd, 2*d_inner});
  4468. layer.ssm_conv1d = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_CONV1D, "weight", i), {d_conv, d_inner});
  4469. layer.ssm_conv1d_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_CONV1D, "bias", i), {d_inner});
  4470. layer.ssm_x = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_X, "weight", i), {d_inner, dt_rank + 2*d_state});
  4471. layer.ssm_dt = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_DT, "weight", i), {dt_rank, d_inner});
  4472. layer.ssm_dt_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_DT, "bias", i), {d_inner});
  4473. // no "weight" suffix for these
  4474. layer.ssm_a = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_A, i), {d_state, d_inner});
  4475. layer.ssm_d = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_D, i), {d_inner});
  4476. // out_proj
  4477. layer.ssm_out = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_OUT, "weight", i), {d_inner, n_embd});
  4478. }
  4479. } break;
  4480. case LLM_ARCH_XVERSE:
  4481. {
  4482. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4483. {
  4484. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4485. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4486. }
  4487. for (int i = 0; i < n_layer; ++i) {
  4488. ggml_context * ctx_layer = ctx_for_layer(i);
  4489. ggml_context * ctx_split = ctx_for_layer_split(i);
  4490. auto & layer = model.layers[i];
  4491. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4492. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4493. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4494. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4495. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4496. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4497. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4498. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4499. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4500. }
  4501. } break;
  4502. case LLM_ARCH_COMMAND_R:
  4503. {
  4504. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4505. // output
  4506. {
  4507. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4508. // init output from the input tok embed
  4509. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4510. ml.n_created--; // artificial tensor
  4511. ml.size_data += ggml_nbytes(model.output);
  4512. }
  4513. for (int i = 0; i < n_layer; ++i) {
  4514. ggml_context * ctx_layer = ctx_for_layer(i);
  4515. ggml_context * ctx_split = ctx_for_layer_split(i);
  4516. auto & layer = model.layers[i];
  4517. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4518. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4519. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4520. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4521. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4522. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4523. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4524. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4525. }
  4526. } break;
  4527. default:
  4528. throw std::runtime_error("unknown architecture");
  4529. }
  4530. }
  4531. ml.done_getting_tensors();
  4532. ml.init_mappings(true, use_mlock ? &model.mlock_mmaps : nullptr);
  4533. model.mappings.reserve(ml.mappings.size());
  4534. // create the backend buffers
  4535. std::vector<std::pair<ggml_context *, llama_buf_map>> ctx_bufs;
  4536. ctx_bufs.reserve(ctx_map.size());
  4537. // Ensure we have enough capacity for the maximum backend buffer we will potentially create
  4538. size_t n_max_backend_buffer = ctx_map.size() * ml.files.size();
  4539. model.bufs.reserve(n_max_backend_buffer);
  4540. for (auto & it : ctx_map) {
  4541. ggml_backend_buffer_type_t buft = it.first;
  4542. ggml_context * ctx = it.second;
  4543. llama_buf_map bufs;
  4544. bufs.reserve(n_max_backend_buffer);
  4545. // only the mmap region containing the tensors in the model is mapped to the backend buffer
  4546. // 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
  4547. // this allows using partial offloading when the model size exceeds the metal buffer size, but not the RAM size
  4548. if (ml.use_mmap && buft == llama_default_buffer_type_cpu(true)) {
  4549. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  4550. void * addr = nullptr;
  4551. size_t first, last;
  4552. ml.get_mapping_range(&first, &last, &addr, idx, ctx);
  4553. if (first >= last) {
  4554. continue;
  4555. }
  4556. ggml_backend_buffer_t buf = ggml_backend_cpu_buffer_from_ptr((char *) addr + first, last - first);
  4557. if (buf == nullptr) {
  4558. throw std::runtime_error("unable to allocate backend CPU buffer");
  4559. }
  4560. model.bufs.push_back(buf);
  4561. bufs.emplace(idx, buf);
  4562. #ifdef GGML_USE_CUDA
  4563. if (n_layer >= n_gpu_layers) {
  4564. ggml_backend_cuda_register_host_buffer(
  4565. ggml_backend_buffer_get_base(buf),
  4566. ggml_backend_buffer_get_size(buf));
  4567. }
  4568. #endif
  4569. }
  4570. }
  4571. #ifdef GGML_USE_METAL
  4572. else if (ml.use_mmap && buft == ggml_backend_metal_buffer_type()) {
  4573. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  4574. const size_t max_size = ggml_get_max_tensor_size(ctx);
  4575. void * addr = nullptr;
  4576. size_t first, last;
  4577. ml.get_mapping_range(&first, &last, &addr, idx, ctx);
  4578. if (first >= last) {
  4579. continue;
  4580. }
  4581. ggml_backend_buffer_t buf = ggml_backend_metal_buffer_from_ptr((char *) addr + first, last - first, max_size);
  4582. if (buf == nullptr) {
  4583. throw std::runtime_error("unable to allocate backend metal buffer");
  4584. }
  4585. model.bufs.push_back(buf);
  4586. bufs.emplace(idx, buf);
  4587. }
  4588. }
  4589. #endif
  4590. else {
  4591. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  4592. if (buf == nullptr) {
  4593. throw std::runtime_error("unable to allocate backend buffer");
  4594. }
  4595. model.bufs.push_back(buf);
  4596. if (use_mlock && ggml_backend_buffer_is_host(buf)) {
  4597. model.mlock_bufs.emplace_back(new llama_mlock);
  4598. auto & mlock_buf = model.mlock_bufs.back();
  4599. mlock_buf->init (ggml_backend_buffer_get_base(buf));
  4600. mlock_buf->grow_to(ggml_backend_buffer_get_size(buf));
  4601. }
  4602. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  4603. bufs.emplace(idx, buf);
  4604. }
  4605. }
  4606. if (bufs.empty()) {
  4607. throw std::runtime_error("failed to allocate buffer");
  4608. }
  4609. for (auto & buf : bufs) {
  4610. // indicate that this buffer contains weights
  4611. // 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
  4612. ggml_backend_buffer_set_usage(buf.second, GGML_BACKEND_BUFFER_USAGE_WEIGHTS);
  4613. }
  4614. ctx_bufs.emplace_back(ctx, bufs);
  4615. }
  4616. if (llama_supports_gpu_offload()) {
  4617. const int n_gpu = std::min(n_gpu_layers, int(hparams.n_layer));
  4618. LLAMA_LOG_INFO("%s: offloading %d repeating layers to GPU\n", __func__, n_gpu);
  4619. if (n_gpu_layers > (int) hparams.n_layer) {
  4620. LLAMA_LOG_INFO("%s: offloading non-repeating layers to GPU\n", __func__);
  4621. }
  4622. const int max_backend_supported_layers = hparams.n_layer + 1;
  4623. const int max_offloadable_layers = hparams.n_layer + 1;
  4624. LLAMA_LOG_INFO("%s: offloaded %d/%d layers to GPU\n", __func__, std::min(n_gpu_layers, max_offloadable_layers), max_backend_supported_layers);
  4625. }
  4626. // print memory requirements
  4627. for (ggml_backend_buffer_t buf : model.bufs) {
  4628. 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);
  4629. }
  4630. // populate tensors_by_name
  4631. for (ggml_context * ctx : model.ctxs) {
  4632. for (auto * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  4633. model.tensors_by_name.emplace_back(ggml_get_name(cur), cur);
  4634. }
  4635. }
  4636. // load tensor data
  4637. for (auto & it : ctx_bufs) {
  4638. ggml_context * ctx = it.first;
  4639. auto & bufs = it.second;
  4640. if (!ml.load_all_data(ctx, bufs, use_mlock ? &model.mlock_mmaps : NULL, progress_callback, progress_callback_user_data)) {
  4641. return false;
  4642. }
  4643. }
  4644. for (auto & mapping : ml.mappings) {
  4645. model.mappings.emplace_back(std::move(mapping));
  4646. }
  4647. // loading time will be recalculate after the first eval, so
  4648. // we take page faults deferred by mmap() into consideration
  4649. model.t_load_us = ggml_time_us() - model.t_start_us;
  4650. return true;
  4651. }
  4652. // Returns 0 on success, -1 on error, and -2 on cancellation via llama_progress_callback
  4653. static int llama_model_load(const std::string & fname, llama_model & model, llama_model_params & params) {
  4654. try {
  4655. llama_model_loader ml(fname, params.use_mmap, params.kv_overrides);
  4656. model.hparams.vocab_only = params.vocab_only;
  4657. try {
  4658. llm_load_arch(ml, model);
  4659. } catch(const std::exception & e) {
  4660. throw std::runtime_error("error loading model architecture: " + std::string(e.what()));
  4661. }
  4662. try {
  4663. llm_load_hparams(ml, model);
  4664. } catch(const std::exception & e) {
  4665. throw std::runtime_error("error loading model hyperparameters: " + std::string(e.what()));
  4666. }
  4667. try {
  4668. llm_load_vocab(ml, model);
  4669. } catch(const std::exception & e) {
  4670. throw std::runtime_error("error loading model vocabulary: " + std::string(e.what()));
  4671. }
  4672. llm_load_print_meta(ml, model);
  4673. if (model.vocab.type != LLAMA_VOCAB_TYPE_NONE &&
  4674. model.hparams.n_vocab != model.vocab.id_to_token.size()) {
  4675. throw std::runtime_error("vocab size mismatch");
  4676. }
  4677. if (params.vocab_only) {
  4678. LLAMA_LOG_INFO("%s: vocab only - skipping tensors\n", __func__);
  4679. return 0;
  4680. }
  4681. #ifdef GGML_USE_KOMPUTE
  4682. if (params.n_gpu_layers > 0 && (
  4683. !(model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON)
  4684. || !(
  4685. model.ftype == LLAMA_FTYPE_ALL_F32 ||
  4686. model.ftype == LLAMA_FTYPE_MOSTLY_F16 ||
  4687. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ||
  4688. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_1
  4689. )
  4690. )) {
  4691. // TODO(cebtenzzre): propagate this error outside of llama_load_model_from_file
  4692. LLAMA_LOG_WARN("%s: disabling Kompute due to unsupported model arch or quantization\n", __func__);
  4693. params.n_gpu_layers = 0;
  4694. }
  4695. #endif
  4696. #ifdef GGML_USE_SYCL
  4697. if (params.split_mode == LLAMA_SPLIT_MODE_NONE) {
  4698. ggml_backend_sycl_set_single_device_mode(params.main_gpu);
  4699. //SYCL use device index (0, 1, 2) directly, uer input device id, then convert to device index.
  4700. params.main_gpu = ggml_backend_sycl_get_device_index(params.main_gpu);
  4701. } else {
  4702. ggml_backend_sycl_set_mul_device_mode();
  4703. }
  4704. #endif
  4705. if (!llm_load_tensors(
  4706. ml, model, params.n_gpu_layers, params.split_mode, params.main_gpu, params.tensor_split, params.use_mlock,
  4707. params.progress_callback, params.progress_callback_user_data
  4708. )) {
  4709. return -2;
  4710. }
  4711. } catch (const std::exception & err) {
  4712. LLAMA_LOG_ERROR("%s: error loading model: %s\n", __func__, err.what());
  4713. return -1;
  4714. }
  4715. return 0;
  4716. }
  4717. //
  4718. // llm_build
  4719. //
  4720. using llm_build_cb = std::function<void(struct ggml_tensor * cur, const char * name, int nl)>;
  4721. enum llm_ffn_op_type {
  4722. LLM_FFN_SILU,
  4723. LLM_FFN_GELU,
  4724. LLM_FFN_RELU,
  4725. LLM_FFN_RELU_SQR,
  4726. };
  4727. enum llm_ffn_gate_type {
  4728. LLM_FFN_SEQ,
  4729. LLM_FFN_PAR, // ffn_gate is parallel to ffn_up
  4730. };
  4731. enum llm_norm_type {
  4732. LLM_NORM,
  4733. LLM_NORM_RMS,
  4734. };
  4735. static struct ggml_tensor * llm_build_inp_embd(
  4736. struct ggml_context * ctx,
  4737. struct llama_context & lctx,
  4738. const llama_hparams & hparams,
  4739. const llama_batch & batch,
  4740. struct ggml_tensor * tok_embd,
  4741. const llm_build_cb & cb) {
  4742. const int64_t n_embd = hparams.n_embd;
  4743. struct ggml_tensor * inpL;
  4744. if (batch.token) {
  4745. lctx.inp_tokens = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, batch.n_tokens);
  4746. cb(lctx.inp_tokens, "inp_tokens", -1);
  4747. ggml_set_input(lctx.inp_tokens);
  4748. inpL = ggml_get_rows(ctx, tok_embd, lctx.inp_tokens);
  4749. } else {
  4750. #ifdef GGML_USE_MPI
  4751. GGML_ASSERT(false && "not implemented");
  4752. #endif
  4753. lctx.inp_embd = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, batch.n_tokens);
  4754. inpL = lctx.inp_embd;
  4755. ggml_set_input(lctx.inp_embd);
  4756. }
  4757. cb(inpL, "inp_embd", -1);
  4758. return inpL;
  4759. }
  4760. static void llm_build_kv_store(
  4761. struct ggml_context * ctx,
  4762. const llama_hparams & hparams,
  4763. const llama_kv_cache & kv,
  4764. struct ggml_cgraph * graph,
  4765. struct ggml_tensor * k_cur,
  4766. struct ggml_tensor * v_cur,
  4767. int64_t n_ctx,
  4768. int32_t n_tokens,
  4769. int32_t kv_head,
  4770. const llm_build_cb & cb,
  4771. int64_t il) {
  4772. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  4773. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  4774. GGML_ASSERT(kv.size == n_ctx);
  4775. // compute the transposed [n_tokens, n_embd] V matrix
  4776. assert(v_cur->ne[0] == n_embd_v_gqa && v_cur->ne[1] == n_tokens);
  4777. struct ggml_tensor * v_cur_t = ggml_transpose(ctx, v_cur);
  4778. cb(v_cur_t, "v_cur_t", il);
  4779. struct ggml_tensor * k_cache_view = ggml_view_1d(ctx, kv.k_l[il], n_tokens*n_embd_k_gqa,
  4780. (ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa))*kv_head);
  4781. cb(k_cache_view, "k_cache_view", il);
  4782. struct ggml_tensor * v_cache_view = ggml_view_2d(ctx, kv.v_l[il], n_tokens, n_embd_v_gqa,
  4783. ( n_ctx)*ggml_element_size(kv.v_l[il]),
  4784. (kv_head)*ggml_element_size(kv.v_l[il]));
  4785. cb(v_cache_view, "v_cache_view", il);
  4786. // important: storing RoPE-ed version of K in the KV cache!
  4787. ggml_build_forward_expand(graph, ggml_cpy(ctx, k_cur, k_cache_view));
  4788. ggml_build_forward_expand(graph, ggml_cpy(ctx, v_cur_t, v_cache_view));
  4789. }
  4790. static struct ggml_tensor * llm_build_norm(
  4791. struct ggml_context * ctx,
  4792. struct ggml_tensor * cur,
  4793. const llama_hparams & hparams,
  4794. struct ggml_tensor * mw,
  4795. struct ggml_tensor * mb,
  4796. llm_norm_type type,
  4797. const llm_build_cb & cb,
  4798. int il) {
  4799. switch (type) {
  4800. case LLM_NORM: cur = ggml_norm (ctx, cur, hparams.f_norm_eps); break;
  4801. case LLM_NORM_RMS: cur = ggml_rms_norm(ctx, cur, hparams.f_norm_rms_eps); break;
  4802. }
  4803. if (mw || mb) {
  4804. cb(cur, "norm", il);
  4805. }
  4806. if (mw) {
  4807. cur = ggml_mul(ctx, cur, mw);
  4808. if (mb) {
  4809. cb(cur, "norm_w", il);
  4810. }
  4811. }
  4812. if (mb) {
  4813. cur = ggml_add(ctx, cur, mb);
  4814. }
  4815. return cur;
  4816. }
  4817. static struct ggml_tensor * llm_build_ffn(
  4818. struct ggml_context * ctx,
  4819. struct ggml_tensor * cur,
  4820. struct ggml_tensor * up,
  4821. struct ggml_tensor * up_b,
  4822. struct ggml_tensor * gate,
  4823. struct ggml_tensor * gate_b,
  4824. struct ggml_tensor * down,
  4825. struct ggml_tensor * down_b,
  4826. struct ggml_tensor * act_scales,
  4827. llm_ffn_op_type type_op,
  4828. llm_ffn_gate_type type_gate,
  4829. const llm_build_cb & cb,
  4830. int il) {
  4831. struct ggml_tensor * tmp = ggml_mul_mat(ctx, up, cur);
  4832. cb(tmp, "ffn_up", il);
  4833. if (up_b) {
  4834. tmp = ggml_add(ctx, tmp, up_b);
  4835. cb(tmp, "ffn_up_b", il);
  4836. }
  4837. if (gate) {
  4838. switch (type_gate) {
  4839. case LLM_FFN_SEQ:
  4840. {
  4841. cur = ggml_mul_mat(ctx, gate, tmp);
  4842. cb(cur, "ffn_gate", il);
  4843. } break;
  4844. case LLM_FFN_PAR:
  4845. {
  4846. cur = ggml_mul_mat(ctx, gate, cur);
  4847. cb(cur, "ffn_gate", il);
  4848. } break;
  4849. }
  4850. if (gate_b) {
  4851. cur = ggml_add(ctx, cur, gate_b);
  4852. cb(cur, "ffn_gate_b", il);
  4853. }
  4854. } else {
  4855. cur = tmp;
  4856. }
  4857. switch (type_op) {
  4858. case LLM_FFN_SILU:
  4859. {
  4860. cur = ggml_silu(ctx, cur);
  4861. cb(cur, "ffn_silu", il);
  4862. } break;
  4863. case LLM_FFN_GELU:
  4864. {
  4865. cur = ggml_gelu(ctx, cur);
  4866. cb(cur, "ffn_gelu", il);
  4867. if (act_scales != NULL) {
  4868. cur = ggml_div(ctx, cur, act_scales);
  4869. cb(cur, "ffn_act", il);
  4870. }
  4871. } break;
  4872. case LLM_FFN_RELU:
  4873. {
  4874. cur = ggml_relu(ctx, cur);
  4875. cb(cur, "ffn_relu", il);
  4876. } break;
  4877. case LLM_FFN_RELU_SQR:
  4878. {
  4879. cur = ggml_relu(ctx, cur);
  4880. cb(cur, "ffn_relu", il);
  4881. cur = ggml_sqr(ctx, cur);
  4882. cb(cur, "ffn_sqr(relu)", il);
  4883. } break;
  4884. }
  4885. if (type_gate == LLM_FFN_PAR) {
  4886. cur = ggml_mul(ctx, cur, tmp);
  4887. cb(cur, "ffn_gate_par", il);
  4888. }
  4889. cur = ggml_mul_mat(ctx, down, cur);
  4890. if (down_b) {
  4891. cb(cur, "ffn_down", il);
  4892. }
  4893. if (down_b) {
  4894. cur = ggml_add(ctx, cur, down_b);
  4895. }
  4896. return cur;
  4897. }
  4898. // if max_alibi_bias > 0 then apply ALiBi
  4899. static struct ggml_tensor * llm_build_kqv(
  4900. struct ggml_context * ctx,
  4901. const llama_model & model,
  4902. const llama_hparams & hparams,
  4903. const llama_kv_cache & kv,
  4904. struct ggml_cgraph * graph,
  4905. struct ggml_tensor * wo,
  4906. struct ggml_tensor * wo_b,
  4907. struct ggml_tensor * q_cur,
  4908. struct ggml_tensor * kq_mask,
  4909. struct ggml_tensor * kq_pos,
  4910. int64_t n_ctx,
  4911. int32_t n_tokens,
  4912. int32_t n_kv,
  4913. float kq_scale,
  4914. const llm_build_cb & cb,
  4915. int il) {
  4916. const int64_t n_head = hparams.n_head;
  4917. const int64_t n_head_kv = hparams.n_head_kv;
  4918. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  4919. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  4920. const int64_t n_embd_head_v = hparams.n_embd_head_v;
  4921. struct ggml_tensor * q = ggml_permute(ctx, q_cur, 0, 2, 1, 3);
  4922. cb(q, "q", il);
  4923. struct ggml_tensor * k =
  4924. ggml_view_3d(ctx, kv.k_l[il],
  4925. n_embd_head_k, n_kv, n_head_kv,
  4926. ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa),
  4927. ggml_row_size(kv.k_l[il]->type, n_embd_head_k),
  4928. 0);
  4929. cb(k, "k", il);
  4930. struct ggml_tensor * kq = ggml_mul_mat(ctx, k, q);
  4931. cb(kq, "kq", il);
  4932. if (model.arch == LLM_ARCH_PHI2) {
  4933. // for this arch, we need to perform the KQ multiplication with F32 precision, otherwise we get NaNs
  4934. // ref: https://github.com/ggerganov/llama.cpp/pull/4490#issuecomment-1859055847
  4935. ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  4936. }
  4937. if (model.arch == LLM_ARCH_GROK) {
  4938. // need to do the following:
  4939. // multiply by attn_output_multiplyer of 0.08838834764831845
  4940. // and then :
  4941. // kq = 30 * tanh(kq / 30)
  4942. // before the softmax below
  4943. //try from phi2
  4944. //ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  4945. kq = ggml_tanh(ctx, ggml_scale(ctx, kq, 0.08838834764831845f/30.0f));
  4946. kq = ggml_scale(ctx, kq, 30);
  4947. }
  4948. #if defined(GGML_USE_KOMPUTE)
  4949. #pragma message("TODO: ALiBi support in ggml_soft_max_ext is not implemented for Kompute")
  4950. #pragma message(" Falling back to ggml_alibi(). Will become an error in Mar 2024")
  4951. #pragma message("ref: https://github.com/ggerganov/llama.cpp/pull/5488")
  4952. if (hparams.f_max_alibi_bias > 0.0f) {
  4953. kq = ggml_scale(ctx, kq, kq_scale);
  4954. cb(kq, "kq_scaled", il);
  4955. kq = ggml_alibi(ctx, kq, /*n_past*/ 0, n_head, hparams.f_max_alibi_bias);
  4956. cb(kq, "kq_scaled_alibi", il);
  4957. kq = ggml_add(ctx, kq, kq_mask);
  4958. cb(kq, "kq_masked", il);
  4959. kq = ggml_soft_max(ctx, kq);
  4960. cb(kq, "kq_soft_max", il);
  4961. } else
  4962. #endif
  4963. {
  4964. kq = ggml_soft_max_ext(ctx, kq, kq_mask, kq_pos, kq_scale, hparams.f_max_alibi_bias);
  4965. cb(kq, "kq_soft_max_ext", il);
  4966. }
  4967. GGML_ASSERT(kv.size == n_ctx);
  4968. // split cached v into n_head heads
  4969. struct ggml_tensor * v =
  4970. ggml_view_3d(ctx, kv.v_l[il],
  4971. n_kv, n_embd_head_v, n_head_kv,
  4972. ggml_element_size(kv.v_l[il])*n_ctx,
  4973. ggml_element_size(kv.v_l[il])*n_ctx*n_embd_head_v,
  4974. 0);
  4975. cb(v, "v", il);
  4976. struct ggml_tensor * kqv = ggml_mul_mat(ctx, v, kq);
  4977. cb(kqv, "kqv", il);
  4978. struct ggml_tensor * kqv_merged = ggml_permute(ctx, kqv, 0, 2, 1, 3);
  4979. cb(kqv_merged, "kqv_merged", il);
  4980. struct ggml_tensor * cur = ggml_cont_2d(ctx, kqv_merged, n_embd_head_k*n_head, n_tokens);
  4981. cb(cur, "kqv_merged_cont", il);
  4982. ggml_build_forward_expand(graph, cur);
  4983. cur = ggml_mul_mat(ctx, wo, cur);
  4984. if (wo_b) {
  4985. cb(cur, "kqv_wo", il);
  4986. }
  4987. if (wo_b) {
  4988. cur = ggml_add(ctx, cur, wo_b);
  4989. }
  4990. return cur;
  4991. }
  4992. static struct ggml_tensor * llm_build_kv(
  4993. struct ggml_context * ctx,
  4994. const llama_model & model,
  4995. const llama_hparams & hparams,
  4996. const llama_kv_cache & kv,
  4997. struct ggml_cgraph * graph,
  4998. struct ggml_tensor * wo,
  4999. struct ggml_tensor * wo_b,
  5000. struct ggml_tensor * k_cur,
  5001. struct ggml_tensor * v_cur,
  5002. struct ggml_tensor * q_cur,
  5003. struct ggml_tensor * kq_mask,
  5004. struct ggml_tensor * kq_pos,
  5005. int64_t n_ctx,
  5006. int32_t n_tokens,
  5007. int32_t kv_head,
  5008. int32_t n_kv,
  5009. float kq_scale,
  5010. const llm_build_cb & cb,
  5011. int il) {
  5012. // these nodes are added to the graph together so that they are not reordered
  5013. // by doing so, the number of splits in the graph is reduced
  5014. ggml_build_forward_expand(graph, q_cur);
  5015. ggml_build_forward_expand(graph, k_cur);
  5016. ggml_build_forward_expand(graph, v_cur);
  5017. llm_build_kv_store(ctx, hparams, kv, graph, k_cur, v_cur, n_ctx, n_tokens, kv_head, cb, il);
  5018. struct ggml_tensor * cur;
  5019. cur = llm_build_kqv(ctx, model, hparams, kv, graph, wo, wo_b,
  5020. q_cur, kq_mask, kq_pos, n_ctx, n_tokens, n_kv, kq_scale, cb, il);
  5021. cb(cur, "kqv_out", il);
  5022. return cur;
  5023. }
  5024. struct llm_build_context {
  5025. const llama_model & model;
  5026. llama_context & lctx;
  5027. const llama_hparams & hparams;
  5028. const llama_cparams & cparams;
  5029. const llama_batch & batch;
  5030. const llama_kv_cache & kv_self;
  5031. const int64_t n_embd;
  5032. const int64_t n_layer;
  5033. const int64_t n_rot;
  5034. const int64_t n_ctx; // user-specified context size (can be different from n_ctx_train)
  5035. const int64_t n_head;
  5036. const int64_t n_head_kv;
  5037. const int64_t n_embd_head_k;
  5038. const int64_t n_embd_k_gqa;
  5039. const int64_t n_embd_head_v;
  5040. const int64_t n_embd_v_gqa;
  5041. const int64_t n_expert;
  5042. const int64_t n_expert_used;
  5043. const float freq_base;
  5044. const float freq_scale;
  5045. const float ext_factor;
  5046. const float attn_factor;
  5047. const float beta_fast;
  5048. const float beta_slow;
  5049. const float norm_eps;
  5050. const float norm_rms_eps;
  5051. const int32_t n_tokens;
  5052. const int32_t n_kv; // size of KV cache to consider (n_kv <= kv_self.size)
  5053. const int32_t n_outputs;
  5054. const int32_t kv_head; // index of where we store new KV data in the cache
  5055. const int32_t n_orig_ctx;
  5056. const enum llama_pooling_type pooling_type;
  5057. const enum llama_rope_type rope_type;
  5058. const llm_build_cb & cb;
  5059. std::vector<uint8_t> & buf_compute_meta;
  5060. struct ggml_context * ctx0 = nullptr;
  5061. // TODO: consider making the entire interface noexcept
  5062. llm_build_context(
  5063. llama_context & lctx,
  5064. const llama_batch & batch,
  5065. const llm_build_cb & cb,
  5066. bool worst_case) :
  5067. model (lctx.model),
  5068. lctx (lctx),
  5069. hparams (model.hparams),
  5070. cparams (lctx.cparams),
  5071. batch (batch),
  5072. kv_self (lctx.kv_self),
  5073. n_embd (hparams.n_embd),
  5074. n_layer (hparams.n_layer),
  5075. n_rot (hparams.n_rot),
  5076. n_ctx (cparams.n_ctx),
  5077. n_head (hparams.n_head),
  5078. n_head_kv (hparams.n_head_kv),
  5079. n_embd_head_k (hparams.n_embd_head_k),
  5080. n_embd_k_gqa (hparams.n_embd_k_gqa()),
  5081. n_embd_head_v (hparams.n_embd_head_v),
  5082. n_embd_v_gqa (hparams.n_embd_v_gqa()),
  5083. n_expert (hparams.n_expert),
  5084. n_expert_used (hparams.n_expert_used),
  5085. freq_base (cparams.rope_freq_base),
  5086. freq_scale (cparams.rope_freq_scale),
  5087. ext_factor (cparams.yarn_ext_factor),
  5088. attn_factor (cparams.yarn_attn_factor),
  5089. beta_fast (cparams.yarn_beta_fast),
  5090. beta_slow (cparams.yarn_beta_slow),
  5091. norm_eps (hparams.f_norm_eps),
  5092. norm_rms_eps (hparams.f_norm_rms_eps),
  5093. n_tokens (batch.n_tokens),
  5094. n_kv (worst_case ? kv_self.size : kv_self.n),
  5095. n_outputs (worst_case ? n_tokens : lctx.n_outputs),
  5096. kv_head (worst_case ? (kv_self.recurrent ? 0 : kv_self.size - n_tokens) : kv_self.head),
  5097. n_orig_ctx (cparams.n_yarn_orig_ctx),
  5098. pooling_type (cparams.pooling_type),
  5099. rope_type (hparams.rope_type),
  5100. cb (cb),
  5101. buf_compute_meta (lctx.buf_compute_meta) {
  5102. // all initializations should be done in init()
  5103. }
  5104. void init() {
  5105. struct ggml_init_params params = {
  5106. /*.mem_size =*/ buf_compute_meta.size(),
  5107. /*.mem_buffer =*/ buf_compute_meta.data(),
  5108. /*.no_alloc =*/ true,
  5109. };
  5110. ctx0 = ggml_init(params);
  5111. lctx.inp_tokens = nullptr;
  5112. lctx.inp_embd = nullptr;
  5113. lctx.inp_pos = nullptr;
  5114. lctx.inp_out_ids = nullptr;
  5115. lctx.inp_KQ_mask = nullptr;
  5116. lctx.inp_KQ_pos = nullptr;
  5117. lctx.inp_K_shift = nullptr;
  5118. lctx.inp_mean = nullptr;
  5119. lctx.inp_cls = nullptr;
  5120. lctx.inp_s_copy = nullptr;
  5121. lctx.inp_s_mask = nullptr;
  5122. lctx.inp_s_seq = nullptr;
  5123. }
  5124. void free() {
  5125. if (ctx0) {
  5126. ggml_free(ctx0);
  5127. ctx0 = nullptr;
  5128. }
  5129. }
  5130. struct ggml_cgraph * build_k_shift() {
  5131. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5132. GGML_ASSERT(kv_self.size == n_ctx);
  5133. lctx.inp_K_shift = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_ctx);
  5134. cb(lctx.inp_K_shift, "K_shift", -1);
  5135. ggml_set_input(lctx.inp_K_shift);
  5136. for (int il = 0; il < n_layer; ++il) {
  5137. struct ggml_tensor * tmp =
  5138. // we rotate only the first n_rot dimensions
  5139. ggml_rope_custom_inplace(ctx0,
  5140. ggml_view_3d(ctx0, kv_self.k_l[il],
  5141. n_embd_head_k, n_head_kv, n_ctx,
  5142. ggml_row_size(kv_self.k_l[il]->type, n_embd_head_k),
  5143. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  5144. 0),
  5145. lctx.inp_K_shift, n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5146. ext_factor, attn_factor, beta_fast, beta_slow);
  5147. cb(tmp, "K_shifted", il);
  5148. ggml_build_forward_expand(gf, tmp);
  5149. }
  5150. return gf;
  5151. }
  5152. struct ggml_cgraph * build_s_copy() {
  5153. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5154. GGML_ASSERT(kv_self.recurrent);
  5155. struct ggml_tensor * state_copy = build_inp_s_copy();
  5156. for (int il = 0; il < n_layer; ++il) {
  5157. struct ggml_tensor * conv_states = ggml_reshape_2d(ctx0, kv_self.k_l[il], hparams.n_embd_k_s(), kv_self.size);
  5158. struct ggml_tensor * ssm_states = ggml_reshape_2d(ctx0, kv_self.v_l[il], hparams.n_embd_v_s(), kv_self.size);
  5159. conv_states = ggml_get_rows(ctx0, conv_states, state_copy);
  5160. ssm_states = ggml_get_rows(ctx0, ssm_states, state_copy);
  5161. // TODO: name the intermediate tensors with cb()
  5162. ggml_build_forward_expand(gf, ggml_cpy(ctx0, conv_states, kv_self.k_l[il]));
  5163. ggml_build_forward_expand(gf, ggml_cpy(ctx0, ssm_states, kv_self.v_l[il]));
  5164. }
  5165. return gf;
  5166. }
  5167. struct ggml_cgraph * build_defrag(const std::vector<uint32_t> & ids) {
  5168. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5169. for (uint32_t i = 0; i < ids.size(); ++i) {
  5170. const uint32_t id = ids[i];
  5171. if (i == id || id == ids.size()) {
  5172. continue;
  5173. }
  5174. uint32_t nm = 1;
  5175. while (i + nm < ids.size() && ids[i + nm] == id + nm) {
  5176. nm++;
  5177. }
  5178. for (int il = 0; il < n_layer; ++il) {
  5179. ggml_tensor * view_k_src = ggml_view_2d(ctx0, kv_self.k_l[il],
  5180. n_embd_k_gqa, nm,
  5181. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  5182. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*i));
  5183. ggml_tensor * view_k_dst = ggml_view_2d(ctx0, kv_self.k_l[il],
  5184. n_embd_k_gqa, nm,
  5185. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  5186. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*id));
  5187. ggml_tensor * view_v_src = ggml_view_2d(ctx0, kv_self.v_l[il],
  5188. nm, n_embd_v_gqa,
  5189. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  5190. ggml_row_size(kv_self.v_l[il]->type, i));
  5191. ggml_tensor * view_v_dst = ggml_view_2d(ctx0, kv_self.v_l[il],
  5192. nm, n_embd_v_gqa,
  5193. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  5194. ggml_row_size(kv_self.v_l[il]->type, id));
  5195. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_k_src, view_k_dst));
  5196. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_v_src, view_v_dst));
  5197. }
  5198. i += nm - 1;
  5199. }
  5200. //LLAMA_LOG_INFO("gf->n_nodes = %d\n", gf->n_nodes);
  5201. return gf;
  5202. }
  5203. struct ggml_tensor * build_inp_pos() {
  5204. lctx.inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  5205. cb(lctx.inp_pos, "inp_pos", -1);
  5206. ggml_set_input(lctx.inp_pos);
  5207. return lctx.inp_pos;
  5208. }
  5209. struct ggml_tensor * build_inp_out_ids() {
  5210. lctx.inp_out_ids = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_outputs);
  5211. cb(lctx.inp_out_ids, "inp_out_ids", -1);
  5212. ggml_set_input(lctx.inp_out_ids);
  5213. return lctx.inp_out_ids;
  5214. }
  5215. struct ggml_tensor * build_inp_KQ_mask(bool causal = true) {
  5216. if (causal) {
  5217. lctx.inp_KQ_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_kv, n_tokens);
  5218. } else {
  5219. lctx.inp_KQ_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, n_tokens);
  5220. }
  5221. cb(lctx.inp_KQ_mask, "KQ_mask", -1);
  5222. ggml_set_input(lctx.inp_KQ_mask);
  5223. return lctx.inp_KQ_mask;
  5224. }
  5225. struct ggml_tensor * build_inp_KQ_pos() {
  5226. lctx.inp_KQ_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, n_kv);
  5227. cb(lctx.inp_KQ_pos, "KQ_pos", -1);
  5228. ggml_set_input(lctx.inp_KQ_pos);
  5229. return lctx.inp_KQ_pos;
  5230. }
  5231. struct ggml_tensor * build_inp_mean() {
  5232. lctx.inp_mean = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, n_tokens);
  5233. cb(lctx.inp_mean, "inp_mean", -1);
  5234. ggml_set_input(lctx.inp_mean);
  5235. return lctx.inp_mean;
  5236. }
  5237. struct ggml_tensor * build_inp_cls() {
  5238. lctx.inp_cls = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  5239. cb(lctx.inp_cls, "inp_cls", -1);
  5240. ggml_set_input(lctx.inp_cls);
  5241. return lctx.inp_cls;
  5242. }
  5243. struct ggml_tensor * build_inp_s_copy() {
  5244. lctx.inp_s_copy = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, kv_self.size);
  5245. cb(lctx.inp_s_copy, "inp_s_copy", -1);
  5246. ggml_set_input(lctx.inp_s_copy);
  5247. return lctx.inp_s_copy;
  5248. }
  5249. struct ggml_tensor * build_inp_s_mask() {
  5250. lctx.inp_s_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, 1, n_kv);
  5251. cb(lctx.inp_s_mask, "inp_s_mask", -1);
  5252. ggml_set_input(lctx.inp_s_mask);
  5253. return lctx.inp_s_mask;
  5254. }
  5255. struct ggml_tensor * build_inp_s_seq() {
  5256. lctx.inp_s_seq = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_kv, n_tokens);
  5257. cb(lctx.inp_s_seq, "inp_s_seq", -1);
  5258. ggml_set_input(lctx.inp_s_seq);
  5259. return lctx.inp_s_seq;
  5260. }
  5261. struct ggml_cgraph * build_llama() {
  5262. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5263. // mutable variable, needed during the last layer of the computation to skip unused tokens
  5264. int32_t n_tokens = this->n_tokens;
  5265. const int64_t n_embd_head = hparams.n_embd_head_v;
  5266. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5267. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5268. struct ggml_tensor * cur;
  5269. struct ggml_tensor * inpL;
  5270. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5271. // inp_pos - contains the positions
  5272. struct ggml_tensor * inp_pos = build_inp_pos();
  5273. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5274. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5275. for (int il = 0; il < n_layer; ++il) {
  5276. struct ggml_tensor * inpSA = inpL;
  5277. // norm
  5278. cur = llm_build_norm(ctx0, inpL, hparams,
  5279. model.layers[il].attn_norm, NULL,
  5280. LLM_NORM_RMS, cb, il);
  5281. cb(cur, "attn_norm", il);
  5282. // self-attention
  5283. {
  5284. // compute Q and K and RoPE them
  5285. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5286. cb(Qcur, "Qcur", il);
  5287. if (model.layers[il].bq) {
  5288. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5289. cb(Qcur, "Qcur", il);
  5290. }
  5291. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5292. cb(Kcur, "Kcur", il);
  5293. if (model.layers[il].bk) {
  5294. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5295. cb(Kcur, "Kcur", il);
  5296. }
  5297. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5298. cb(Vcur, "Vcur", il);
  5299. if (model.layers[il].bv) {
  5300. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  5301. cb(Vcur, "Vcur", il);
  5302. }
  5303. Qcur = ggml_rope_custom(
  5304. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5305. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5306. ext_factor, attn_factor, beta_fast, beta_slow
  5307. );
  5308. cb(Qcur, "Qcur", il);
  5309. Kcur = ggml_rope_custom(
  5310. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5311. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5312. ext_factor, attn_factor, beta_fast, beta_slow
  5313. );
  5314. cb(Kcur, "Kcur", il);
  5315. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5316. model.layers[il].wo, model.layers[il].bo,
  5317. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5318. }
  5319. if (il == n_layer - 1) {
  5320. // skip computing output for unused tokens
  5321. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  5322. n_tokens = n_outputs;
  5323. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  5324. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  5325. }
  5326. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5327. cb(ffn_inp, "ffn_inp", il);
  5328. // feed-forward network
  5329. if (model.layers[il].ffn_gate_inp == nullptr) {
  5330. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5331. model.layers[il].ffn_norm, NULL,
  5332. LLM_NORM_RMS, cb, il);
  5333. cb(cur, "ffn_norm", il);
  5334. cur = llm_build_ffn(ctx0, cur,
  5335. model.layers[il].ffn_up, NULL,
  5336. model.layers[il].ffn_gate, NULL,
  5337. model.layers[il].ffn_down, NULL,
  5338. NULL,
  5339. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5340. cb(cur, "ffn_out", il);
  5341. } else {
  5342. // MoE branch
  5343. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5344. model.layers[il].ffn_norm, NULL,
  5345. LLM_NORM_RMS, cb, il);
  5346. cb(cur, "ffn_norm", il);
  5347. ggml_tensor * logits = ggml_mul_mat(ctx0, model.layers[il].ffn_gate_inp, cur); // [n_tokens, num_experts]
  5348. cb(logits, "ffn_moe_logits", il);
  5349. ggml_tensor * probs = ggml_soft_max(ctx0, logits); // [n_tokens, num_experts]
  5350. cb(probs, "ffn_moe_probs", il);
  5351. // select experts
  5352. ggml_tensor * selected_experts = ggml_top_k(ctx0, probs, n_expert_used); // [n_tokens, num_experts_per_tok]
  5353. cb(selected_experts->src[0], "ffn_moe_argsort", il);
  5354. ggml_tensor * weights = ggml_get_rows(ctx0,
  5355. ggml_reshape_3d(ctx0, probs, 1, n_expert, n_tokens), selected_experts);
  5356. cb(weights, "ffn_moe_weights", il);
  5357. weights = ggml_reshape_2d(ctx0, weights, n_expert_used, n_tokens); // [n_tokens, num_experts_per_tok]
  5358. ggml_tensor * weights_sum = ggml_sum_rows(ctx0, weights);
  5359. cb(weights_sum, "ffn_moe_weights_sum", il);
  5360. weights = ggml_div(ctx0, weights, weights_sum); // [n_tokens, num_experts_per_tok]
  5361. cb(weights, "ffn_moe_weights_norm", il);
  5362. // compute expert outputs
  5363. ggml_tensor * moe_out = nullptr;
  5364. for (int i = 0; i < n_expert_used; ++i) {
  5365. ggml_tensor * cur_expert;
  5366. ggml_tensor * cur_up = ggml_mul_mat_id(ctx0, model.layers[il].ffn_up_exp, n_expert, selected_experts, i, cur);
  5367. cb(cur_up, "ffn_moe_up", il);
  5368. ggml_tensor * cur_gate = ggml_mul_mat_id(ctx0, model.layers[il].ffn_gate_exp, n_expert, selected_experts, i, cur);
  5369. cb(cur_gate, "ffn_moe_gate", il);
  5370. cur_gate = ggml_silu(ctx0, cur_gate);
  5371. cb(cur_gate, "ffn_moe_silu", il);
  5372. cur_expert = ggml_mul(ctx0, cur_up, cur_gate); // [n_tokens, n_embd]
  5373. cb(cur_expert, "ffn_moe_gate_par", il);
  5374. cur_expert = ggml_mul_mat_id(ctx0, model.layers[il].ffn_down_exp, n_expert, selected_experts, i, cur_expert); // [n_tokens, n_embd]
  5375. cb(cur_expert, "ffn_moe_down", il);
  5376. cur_expert = ggml_mul(ctx0, cur_expert,
  5377. ggml_view_2d(ctx0, weights, 1, n_tokens, weights->nb[1], i*weights->nb[0]));
  5378. cb(cur_expert, "ffn_moe_weighted", il);
  5379. if (i == 0) {
  5380. moe_out = cur_expert;
  5381. } else {
  5382. moe_out = ggml_add(ctx0, moe_out, cur_expert);
  5383. cb(moe_out, "ffn_moe_out", il);
  5384. }
  5385. }
  5386. cur = moe_out;
  5387. }
  5388. cur = ggml_add(ctx0, cur, ffn_inp);
  5389. cb(cur, "ffn_out", il);
  5390. ggml_tensor * layer_dir = lctx.cvec.tensor_for(il);
  5391. if (layer_dir != nullptr) {
  5392. cur = ggml_add(ctx0, cur, layer_dir);
  5393. }
  5394. cb(cur, "l_out", il);
  5395. // input for next layer
  5396. inpL = cur;
  5397. }
  5398. cur = inpL;
  5399. cur = llm_build_norm(ctx0, cur, hparams,
  5400. model.output_norm, NULL,
  5401. LLM_NORM_RMS, cb, -1);
  5402. cb(cur, "result_norm", -1);
  5403. // lm_head
  5404. cur = ggml_mul_mat(ctx0, model.output, cur);
  5405. cb(cur, "result_output", -1);
  5406. ggml_build_forward_expand(gf, cur);
  5407. return gf;
  5408. }
  5409. struct ggml_cgraph * build_baichuan() {
  5410. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5411. const int64_t n_embd_head = hparams.n_embd_head_v;
  5412. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5413. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5414. struct ggml_tensor * cur;
  5415. struct ggml_tensor * inpL;
  5416. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5417. // inp_pos - contains the positions
  5418. struct ggml_tensor * inp_pos = model.type == MODEL_7B ? build_inp_pos() : nullptr;
  5419. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5420. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5421. // positions of the tokens in the KV cache
  5422. struct ggml_tensor * KQ_pos = build_inp_KQ_pos();
  5423. for (int il = 0; il < n_layer; ++il) {
  5424. struct ggml_tensor * inpSA = inpL;
  5425. cur = llm_build_norm(ctx0, inpL, hparams,
  5426. model.layers[il].attn_norm, NULL,
  5427. LLM_NORM_RMS, cb, il);
  5428. cb(cur, "attn_norm", il);
  5429. // self-attention
  5430. {
  5431. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5432. cb(Qcur, "Qcur", il);
  5433. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5434. cb(Kcur, "Kcur", il);
  5435. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5436. cb(Vcur, "Vcur", il);
  5437. switch (model.type) {
  5438. case MODEL_7B:
  5439. Qcur = ggml_rope_custom(
  5440. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5441. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5442. ext_factor, attn_factor, beta_fast, beta_slow
  5443. );
  5444. Kcur = ggml_rope_custom(
  5445. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5446. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5447. ext_factor, attn_factor, beta_fast, beta_slow
  5448. );
  5449. break;
  5450. case MODEL_13B:
  5451. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd/n_head, n_head, n_tokens);
  5452. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd/n_head, n_head, n_tokens);
  5453. break;
  5454. default:
  5455. GGML_ASSERT(false);
  5456. }
  5457. cb(Qcur, "Qcur", il);
  5458. cb(Kcur, "Kcur", il);
  5459. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5460. model.layers[il].wo, NULL,
  5461. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5462. }
  5463. if (il == n_layer - 1) {
  5464. // skip computing output for unused tokens
  5465. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  5466. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  5467. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  5468. }
  5469. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5470. cb(ffn_inp, "ffn_inp", il);
  5471. // feed-forward network
  5472. {
  5473. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5474. model.layers[il].ffn_norm, NULL,
  5475. LLM_NORM_RMS, cb, il);
  5476. cb(cur, "ffn_norm", il);
  5477. cur = llm_build_ffn(ctx0, cur,
  5478. model.layers[il].ffn_up, NULL,
  5479. model.layers[il].ffn_gate, NULL,
  5480. model.layers[il].ffn_down, NULL,
  5481. NULL,
  5482. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5483. cb(cur, "ffn_out", il);
  5484. }
  5485. cur = ggml_add(ctx0, cur, ffn_inp);
  5486. cb(cur, "l_out", il);
  5487. // input for next layer
  5488. inpL = cur;
  5489. }
  5490. cur = inpL;
  5491. cur = llm_build_norm(ctx0, cur, hparams,
  5492. model.output_norm, NULL,
  5493. LLM_NORM_RMS, cb, -1);
  5494. cb(cur, "result_norm", -1);
  5495. // lm_head
  5496. cur = ggml_mul_mat(ctx0, model.output, cur);
  5497. cb(cur, "result_output", -1);
  5498. ggml_build_forward_expand(gf, cur);
  5499. return gf;
  5500. }
  5501. struct ggml_cgraph * build_xverse() {
  5502. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5503. const int64_t n_embd_head = hparams.n_embd_head_v;
  5504. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5505. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5506. struct ggml_tensor * cur;
  5507. struct ggml_tensor * inpL;
  5508. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5509. // inp_pos - contains the positions
  5510. struct ggml_tensor * inp_pos = build_inp_pos();
  5511. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5512. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5513. // positions of the tokens in the KV cache
  5514. struct ggml_tensor * KQ_pos = build_inp_KQ_pos();
  5515. for (int il = 0; il < n_layer; ++il) {
  5516. struct ggml_tensor * inpSA = inpL;
  5517. cur = llm_build_norm(ctx0, inpL, hparams,
  5518. model.layers[il].attn_norm, NULL,
  5519. LLM_NORM_RMS, cb, il);
  5520. cb(cur, "attn_norm", il);
  5521. // self-attention
  5522. {
  5523. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5524. cb(Qcur, "Qcur", il);
  5525. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5526. cb(Kcur, "Kcur", il);
  5527. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5528. cb(Vcur, "Vcur", il);
  5529. Qcur = ggml_rope_custom(
  5530. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5531. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5532. ext_factor, attn_factor, beta_fast, beta_slow
  5533. );
  5534. cb(Qcur, "Qcur", il);
  5535. Kcur = ggml_rope_custom(
  5536. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5537. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5538. ext_factor, attn_factor, beta_fast, beta_slow
  5539. );
  5540. cb(Kcur, "Kcur", il);
  5541. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5542. model.layers[il].wo, NULL,
  5543. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5544. }
  5545. if (il == n_layer - 1) {
  5546. // skip computing output for unused tokens
  5547. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  5548. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  5549. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  5550. }
  5551. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5552. cb(ffn_inp, "ffn_inp", il);
  5553. // feed-forward network
  5554. {
  5555. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5556. model.layers[il].ffn_norm, NULL,
  5557. LLM_NORM_RMS, cb, il);
  5558. cb(cur, "ffn_norm", il);
  5559. cur = llm_build_ffn(ctx0, cur,
  5560. model.layers[il].ffn_up, NULL,
  5561. model.layers[il].ffn_gate, NULL,
  5562. model.layers[il].ffn_down, NULL,
  5563. NULL,
  5564. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5565. cb(cur, "ffn_out", il);
  5566. }
  5567. cur = ggml_add(ctx0, cur, ffn_inp);
  5568. cb(cur, "l_out", il);
  5569. // input for next layer
  5570. inpL = cur;
  5571. }
  5572. cur = inpL;
  5573. cur = llm_build_norm(ctx0, cur, hparams, model.output_norm, NULL, LLM_NORM_RMS, cb, -1);
  5574. cb(cur, "result_norm", -1);
  5575. // lm_head
  5576. cur = ggml_mul_mat(ctx0, model.output, cur);
  5577. cb(cur, "result_output", -1);
  5578. ggml_build_forward_expand(gf, cur);
  5579. return gf;
  5580. }
  5581. struct ggml_cgraph * build_falcon() {
  5582. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5583. const int64_t n_embd_head = hparams.n_embd_head_v;
  5584. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5585. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5586. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5587. struct ggml_tensor * cur;
  5588. struct ggml_tensor * inpL;
  5589. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5590. // inp_pos - contains the positions
  5591. struct ggml_tensor * inp_pos = build_inp_pos();
  5592. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5593. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5594. for (int il = 0; il < n_layer; ++il) {
  5595. struct ggml_tensor * attn_norm;
  5596. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  5597. model.layers[il].attn_norm,
  5598. model.layers[il].attn_norm_b,
  5599. LLM_NORM, cb, il);
  5600. cb(attn_norm, "attn_norm", il);
  5601. // self-attention
  5602. {
  5603. if (model.layers[il].attn_norm_2) {
  5604. // Falcon-40B
  5605. cur = llm_build_norm(ctx0, inpL, hparams,
  5606. model.layers[il].attn_norm_2,
  5607. model.layers[il].attn_norm_2_b,
  5608. LLM_NORM, cb, il);
  5609. cb(cur, "attn_norm_2", il);
  5610. } else {
  5611. cur = attn_norm;
  5612. }
  5613. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5614. cb(cur, "wqkv", il);
  5615. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5616. 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)));
  5617. 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)));
  5618. cb(Qcur, "Qcur", il);
  5619. cb(Kcur, "Kcur", il);
  5620. cb(Vcur, "Vcur", il);
  5621. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5622. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  5623. // using mode = 2 for neox mode
  5624. Qcur = ggml_rope_custom(
  5625. ctx0, Qcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5626. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5627. );
  5628. cb(Qcur, "Qcur", il);
  5629. Kcur = ggml_rope_custom(
  5630. ctx0, Kcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5631. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5632. );
  5633. cb(Kcur, "Kcur", il);
  5634. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5635. model.layers[il].wo, NULL,
  5636. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5637. }
  5638. if (il == n_layer - 1) {
  5639. // skip computing output for unused tokens
  5640. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  5641. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  5642. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  5643. attn_norm = ggml_get_rows(ctx0, attn_norm, inp_out_ids);
  5644. }
  5645. struct ggml_tensor * ffn_inp = cur;
  5646. // feed forward
  5647. {
  5648. cur = llm_build_ffn(ctx0, attn_norm, // !! use the attn norm, not the result
  5649. model.layers[il].ffn_up, NULL,
  5650. NULL, NULL,
  5651. model.layers[il].ffn_down, NULL,
  5652. NULL,
  5653. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5654. cb(cur, "ffn_out", il);
  5655. }
  5656. cur = ggml_add(ctx0, cur, ffn_inp);
  5657. cb(cur, "l_out", il);
  5658. cur = ggml_add(ctx0, cur, inpL);
  5659. cb(cur, "l_out", il);
  5660. // input for next layer
  5661. inpL = cur;
  5662. }
  5663. cur = inpL;
  5664. // norm
  5665. cur = llm_build_norm(ctx0, cur, hparams,
  5666. model.output_norm,
  5667. model.output_norm_b,
  5668. LLM_NORM, cb, -1);
  5669. cb(cur, "result_norm", -1);
  5670. cur = ggml_mul_mat(ctx0, model.output, cur);
  5671. cb(cur, "result_output", -1);
  5672. ggml_build_forward_expand(gf, cur);
  5673. return gf;
  5674. }
  5675. struct ggml_cgraph * build_grok() {
  5676. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5677. // mutable variable, needed during the last layer of the computation to skip unused tokens
  5678. int32_t n_tokens = this->n_tokens;
  5679. const int64_t n_embd_head = hparams.n_embd_head_v;
  5680. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5681. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5682. struct ggml_tensor * cur;
  5683. struct ggml_tensor * inpL;
  5684. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5685. // multiply by embedding_multiplier_scale of 78.38367176906169
  5686. inpL = ggml_scale(ctx0, inpL, 78.38367176906169f);
  5687. // inp_pos - contains the positions
  5688. struct ggml_tensor * inp_pos = build_inp_pos();
  5689. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5690. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5691. for (int il = 0; il < n_layer; ++il) {
  5692. struct ggml_tensor * inpSA = inpL;
  5693. // norm
  5694. cur = llm_build_norm(ctx0, inpL, hparams,
  5695. model.layers[il].attn_norm, NULL,
  5696. LLM_NORM_RMS, cb, il);
  5697. cb(cur, "attn_norm", il);
  5698. // self-attention
  5699. {
  5700. // compute Q and K and RoPE them
  5701. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5702. cb(Qcur, "Qcur", il);
  5703. if (model.layers[il].bq) {
  5704. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5705. cb(Qcur, "Qcur", il);
  5706. }
  5707. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5708. cb(Kcur, "Kcur", il);
  5709. if (model.layers[il].bk) {
  5710. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5711. cb(Kcur, "Kcur", il);
  5712. }
  5713. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5714. cb(Vcur, "Vcur", il);
  5715. if (model.layers[il].bv) {
  5716. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  5717. cb(Vcur, "Vcur", il);
  5718. }
  5719. Qcur = ggml_rope_custom(
  5720. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5721. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5722. ext_factor, attn_factor, beta_fast, beta_slow
  5723. );
  5724. cb(Qcur, "Qcur", il);
  5725. Kcur = ggml_rope_custom(
  5726. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5727. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5728. ext_factor, attn_factor, beta_fast, beta_slow
  5729. );
  5730. cb(Kcur, "Kcur", il);
  5731. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5732. model.layers[il].wo, model.layers[il].bo,
  5733. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  5734. }
  5735. if (il == n_layer - 1) {
  5736. // skip computing output for unused tokens
  5737. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  5738. n_tokens = n_outputs;
  5739. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  5740. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  5741. }
  5742. // Grok
  5743. // if attn_out_norm is present then apply it before adding the input
  5744. if (model.layers[il].attn_out_norm) {
  5745. cur = llm_build_norm(ctx0, cur, hparams,
  5746. model.layers[il].attn_out_norm, NULL,
  5747. LLM_NORM_RMS, cb, il);
  5748. cb(cur, "attn_out_norm", il);
  5749. }
  5750. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5751. cb(ffn_inp, "ffn_inp", il);
  5752. // feed-forward network
  5753. // MoE branch
  5754. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5755. model.layers[il].ffn_norm, NULL,
  5756. LLM_NORM_RMS, cb, il);
  5757. cb(cur, "ffn_norm", il);
  5758. ggml_tensor * logits = ggml_mul_mat(ctx0, model.layers[il].ffn_gate_inp, cur); // [n_tokens, num_experts]
  5759. cb(logits, "ffn_moe_logits", il);
  5760. ggml_tensor * probs = ggml_soft_max(ctx0, logits); // [n_tokens, num_experts]
  5761. cb(probs, "ffn_moe_probs", il);
  5762. // select experts
  5763. ggml_tensor * selected_experts = ggml_top_k(ctx0, probs, n_expert_used); // [n_tokens, num_experts_per_tok]
  5764. cb(selected_experts->src[0], "ffn_moe_argsort", il);
  5765. ggml_tensor * weights = ggml_get_rows(ctx0,
  5766. ggml_reshape_3d(ctx0, probs, 1, n_expert, n_tokens), selected_experts);
  5767. cb(weights, "ffn_moe_weights", il);
  5768. weights = ggml_reshape_2d(ctx0, weights, n_expert_used, n_tokens); // [n_tokens, num_experts_per_tok]
  5769. ggml_tensor * weights_sum = ggml_sum_rows(ctx0, weights);
  5770. cb(weights_sum, "ffn_moe_weights_sum", il);
  5771. weights = ggml_div(ctx0, weights, weights_sum); // [n_tokens, num_experts_per_tok]
  5772. cb(weights, "ffn_moe_weights_norm", il);
  5773. // compute expert outputs
  5774. ggml_tensor * moe_out = nullptr;
  5775. for (int i = 0; i < n_expert_used; ++i) {
  5776. ggml_tensor * cur_expert;
  5777. ggml_tensor * cur_up = ggml_mul_mat_id(ctx0, model.layers[il].ffn_up_exp, n_expert, selected_experts, i, cur);
  5778. cb(cur_up, "ffn_moe_up", il);
  5779. ggml_tensor * cur_gate = ggml_mul_mat_id(ctx0, model.layers[il].ffn_gate_exp, n_expert, selected_experts, i, cur);
  5780. cb(cur_gate, "ffn_moe_gate", il);
  5781. //GeLU
  5782. cur_gate = ggml_gelu(ctx0, cur_gate);
  5783. cb(cur_gate, "ffn_moe_gelu", il);
  5784. cur_expert = ggml_mul(ctx0, cur_up, cur_gate); // [n_tokens, n_embd]
  5785. cb(cur_expert, "ffn_moe_gate_par", il);
  5786. cur_expert = ggml_mul_mat_id(ctx0, model.layers[il].ffn_down_exp, n_expert, selected_experts, i, cur_expert); // [n_tokens, n_embd]
  5787. cb(cur_expert, "ffn_moe_down", il);
  5788. cur_expert = ggml_mul(ctx0, cur_expert,
  5789. ggml_view_2d(ctx0, weights, 1, n_tokens, weights->nb[1], i*weights->nb[0]));
  5790. cb(cur_expert, "ffn_moe_weighted", il);
  5791. if (i == 0) {
  5792. moe_out = cur_expert;
  5793. } else {
  5794. moe_out = ggml_add(ctx0, moe_out, cur_expert);
  5795. cb(moe_out, "ffn_moe_out", il);
  5796. }
  5797. }
  5798. cur = moe_out;
  5799. // Grok
  5800. // if layer_out_norm is present then apply it before adding the input
  5801. // Idea: maybe ffn_out_norm is a better name
  5802. if (model.layers[il].layer_out_norm) {
  5803. cur = llm_build_norm(ctx0, cur, hparams,
  5804. model.layers[il].layer_out_norm, NULL,
  5805. LLM_NORM_RMS, cb, il);
  5806. cb(cur, "layer_out_norm", il);
  5807. }
  5808. cur = ggml_add(ctx0, cur, ffn_inp);
  5809. cb(cur, "ffn_out", il);
  5810. ggml_tensor * layer_dir = lctx.cvec.tensor_for(il);
  5811. if (layer_dir != nullptr) {
  5812. cur = ggml_add(ctx0, cur, layer_dir);
  5813. }
  5814. cb(cur, "l_out", il);
  5815. // input for next layer
  5816. inpL = cur;
  5817. }
  5818. cur = inpL;
  5819. cur = llm_build_norm(ctx0, cur, hparams,
  5820. model.output_norm, NULL,
  5821. LLM_NORM_RMS, cb, -1);
  5822. cb(cur, "result_norm", -1);
  5823. // lm_head
  5824. cur = ggml_mul_mat(ctx0, model.output, cur);
  5825. // Grok
  5826. // multiply logits by output_multiplier_scale of 0.5773502691896257
  5827. cur = ggml_scale(ctx0, cur, 0.5773502691896257f);
  5828. cb(cur, "result_output", -1);
  5829. ggml_build_forward_expand(gf, cur);
  5830. return gf;
  5831. }
  5832. struct ggml_cgraph * build_starcoder() {
  5833. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5834. const int64_t n_embd_head = hparams.n_embd_head_v;
  5835. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5836. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5837. struct ggml_tensor * cur;
  5838. struct ggml_tensor * inpL;
  5839. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5840. // inp_pos - contains the positions
  5841. struct ggml_tensor * inp_pos = build_inp_pos();
  5842. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5843. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5844. struct ggml_tensor * pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  5845. cb(pos, "pos_embd", -1);
  5846. inpL = ggml_add(ctx0, inpL, pos);
  5847. cb(inpL, "inpL", -1);
  5848. for (int il = 0; il < n_layer; ++il) {
  5849. cur = llm_build_norm(ctx0, inpL, hparams,
  5850. model.layers[il].attn_norm,
  5851. model.layers[il].attn_norm_b,
  5852. LLM_NORM, cb, il);
  5853. cb(cur, "attn_norm", il);
  5854. // self-attention
  5855. {
  5856. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5857. cb(cur, "wqkv", il);
  5858. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5859. cb(cur, "bqkv", il);
  5860. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5861. 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)));
  5862. 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)));
  5863. cb(Qcur, "Qcur", il);
  5864. cb(Kcur, "Kcur", il);
  5865. cb(Vcur, "Vcur", il);
  5866. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5867. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5868. model.layers[il].wo, model.layers[il].bo,
  5869. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5870. }
  5871. if (il == n_layer - 1) {
  5872. // skip computing output for unused tokens
  5873. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  5874. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  5875. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  5876. }
  5877. // add the input
  5878. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5879. cb(ffn_inp, "ffn_inp", il);
  5880. // FF
  5881. {
  5882. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5883. model.layers[il].ffn_norm,
  5884. model.layers[il].ffn_norm_b,
  5885. LLM_NORM, cb, il);
  5886. cb(cur, "ffn_norm", il);
  5887. cur = llm_build_ffn(ctx0, cur,
  5888. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5889. NULL, NULL,
  5890. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5891. NULL,
  5892. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5893. cb(cur, "ffn_out", il);
  5894. }
  5895. inpL = ggml_add(ctx0, cur, ffn_inp);
  5896. cb(inpL, "l_out", il);
  5897. }
  5898. cur = llm_build_norm(ctx0, inpL, hparams,
  5899. model.output_norm,
  5900. model.output_norm_b,
  5901. LLM_NORM, cb, -1);
  5902. cb(cur, "result_norm", -1);
  5903. cur = ggml_mul_mat(ctx0, model.output, cur);
  5904. cb(cur, "result_output", -1);
  5905. ggml_build_forward_expand(gf, cur);
  5906. return gf;
  5907. }
  5908. struct ggml_cgraph * build_persimmon() {
  5909. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5910. const int64_t n_embd_head = hparams.n_embd_head_v;
  5911. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5912. GGML_ASSERT(n_embd_head/2 == hparams.n_rot);
  5913. struct ggml_tensor * cur;
  5914. struct ggml_tensor * inpL;
  5915. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5916. // inp_pos - contains the positions
  5917. struct ggml_tensor * inp_pos = build_inp_pos();
  5918. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5919. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5920. for (int il = 0; il < n_layer; ++il) {
  5921. struct ggml_tensor * residual = inpL;
  5922. cur = llm_build_norm(ctx0, inpL, hparams,
  5923. model.layers[il].attn_norm,
  5924. model.layers[il].attn_norm_b,
  5925. LLM_NORM, cb, il);
  5926. cb(cur, "attn_norm", il);
  5927. // self attention
  5928. {
  5929. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5930. cb(cur, "wqkv", il);
  5931. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5932. cb(cur, "bqkv", il);
  5933. // split qkv
  5934. GGML_ASSERT(n_head_kv == n_head);
  5935. struct ggml_tensor * tmpqkv = ggml_reshape_4d(ctx0, cur, n_embd_head, 3, n_head, n_tokens);
  5936. cb(tmpqkv, "tmpqkv", il);
  5937. struct ggml_tensor * tmpqkv_perm = ggml_cont(ctx0, ggml_permute(ctx0, tmpqkv, 0, 3, 1, 2));
  5938. cb(tmpqkv_perm, "tmpqkv", il);
  5939. struct ggml_tensor * tmpq = ggml_view_3d(
  5940. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  5941. ggml_element_size(tmpqkv_perm) * n_embd_head,
  5942. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  5943. 0
  5944. );
  5945. cb(tmpq, "tmpq", il);
  5946. struct ggml_tensor * tmpk = ggml_view_3d(
  5947. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  5948. ggml_element_size(tmpqkv_perm) * n_embd_head,
  5949. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  5950. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens
  5951. );
  5952. cb(tmpk, "tmpk", il);
  5953. // Q/K Layernorm
  5954. tmpq = llm_build_norm(ctx0, tmpq, hparams,
  5955. model.layers[il].attn_q_norm,
  5956. model.layers[il].attn_q_norm_b,
  5957. LLM_NORM, cb, il);
  5958. cb(tmpq, "tmpq", il);
  5959. tmpk = llm_build_norm(ctx0, tmpk, hparams,
  5960. model.layers[il].attn_k_norm,
  5961. model.layers[il].attn_k_norm_b,
  5962. LLM_NORM, cb, il);
  5963. cb(tmpk, "tmpk", il);
  5964. // RoPE the first n_rot of q/k, pass the other half, and concat.
  5965. struct ggml_tensor * qrot = ggml_view_3d(
  5966. ctx0, tmpq, n_rot, n_head, n_tokens,
  5967. ggml_element_size(tmpq) * n_embd_head,
  5968. ggml_element_size(tmpq) * n_embd_head * n_head,
  5969. 0
  5970. );
  5971. cb(qrot, "qrot", il);
  5972. struct ggml_tensor * krot = ggml_view_3d(
  5973. ctx0, tmpk, n_rot, n_head, n_tokens,
  5974. ggml_element_size(tmpk) * n_embd_head,
  5975. ggml_element_size(tmpk) * n_embd_head * n_head,
  5976. 0
  5977. );
  5978. cb(krot, "krot", il);
  5979. // get the second half of tmpq, e.g tmpq[n_rot:, :, :]
  5980. struct ggml_tensor * qpass = ggml_view_3d(
  5981. ctx0, tmpq, n_rot, n_head, n_tokens,
  5982. ggml_element_size(tmpq) * n_embd_head,
  5983. ggml_element_size(tmpq) * n_embd_head * n_head,
  5984. ggml_element_size(tmpq) * n_rot
  5985. );
  5986. cb(qpass, "qpass", il);
  5987. struct ggml_tensor * kpass = ggml_view_3d(
  5988. ctx0, tmpk, n_rot, n_head, n_tokens,
  5989. ggml_element_size(tmpk) * n_embd_head,
  5990. ggml_element_size(tmpk) * n_embd_head * n_head,
  5991. ggml_element_size(tmpk) * n_rot
  5992. );
  5993. cb(kpass, "kpass", il);
  5994. struct ggml_tensor * qrotated = ggml_rope_custom(
  5995. ctx0, qrot, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5996. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5997. );
  5998. cb(qrotated, "qrotated", il);
  5999. struct ggml_tensor * krotated = ggml_rope_custom(
  6000. ctx0, krot, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  6001. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  6002. );
  6003. cb(krotated, "krotated", il);
  6004. // ggml currently only supports concatenation on dim=2
  6005. // so we need to permute qrot, qpass, concat, then permute back.
  6006. qrotated = ggml_cont(ctx0, ggml_permute(ctx0, qrotated, 2, 1, 0, 3));
  6007. cb(qrotated, "qrotated", il);
  6008. krotated = ggml_cont(ctx0, ggml_permute(ctx0, krotated, 2, 1, 0, 3));
  6009. cb(krotated, "krotated", il);
  6010. qpass = ggml_cont(ctx0, ggml_permute(ctx0, qpass, 2, 1, 0, 3));
  6011. cb(qpass, "qpass", il);
  6012. kpass = ggml_cont(ctx0, ggml_permute(ctx0, kpass, 2, 1, 0, 3));
  6013. cb(kpass, "kpass", il);
  6014. struct ggml_tensor * Qcur = ggml_concat(ctx0, qrotated, qpass);
  6015. cb(Qcur, "Qcur", il);
  6016. struct ggml_tensor * Kcur = ggml_concat(ctx0, krotated, kpass);
  6017. cb(Kcur, "Kcur", il);
  6018. struct ggml_tensor * Q = ggml_cont(ctx0, ggml_permute(ctx0, Qcur, 2, 1, 0, 3));
  6019. cb(Q, "Q", il);
  6020. Kcur = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 2, 1, 0, 3));
  6021. cb(Kcur, "Kcur", il);
  6022. struct ggml_tensor * Vcur = ggml_view_3d(
  6023. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  6024. ggml_element_size(tmpqkv_perm) * n_embd_head,
  6025. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  6026. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens * 2
  6027. );
  6028. cb(Vcur, "Vcur", il);
  6029. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6030. model.layers[il].wo, model.layers[il].bo,
  6031. Kcur, Vcur, Q, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6032. }
  6033. if (il == n_layer - 1) {
  6034. // skip computing output for unused tokens
  6035. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6036. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6037. residual = ggml_get_rows(ctx0, residual, inp_out_ids);
  6038. }
  6039. struct ggml_tensor * ffn_inp = ggml_add(ctx0, residual, cur);
  6040. cb(ffn_inp, "ffn_inp", il);
  6041. // feed-forward network
  6042. {
  6043. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6044. model.layers[il].ffn_norm,
  6045. model.layers[il].ffn_norm_b,
  6046. LLM_NORM, cb, il);
  6047. cb(cur, "ffn_norm", il);
  6048. cur = llm_build_ffn(ctx0, cur,
  6049. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6050. NULL, NULL,
  6051. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6052. NULL,
  6053. LLM_FFN_RELU_SQR, LLM_FFN_SEQ, cb, il);
  6054. cb(cur, "ffn_out", il);
  6055. }
  6056. cur = ggml_add(ctx0, cur, ffn_inp);
  6057. cb(cur, "l_out", il);
  6058. inpL = cur;
  6059. }
  6060. cur = inpL;
  6061. cur = llm_build_norm(ctx0, cur, hparams,
  6062. model.output_norm,
  6063. model.output_norm_b,
  6064. LLM_NORM, cb, -1);
  6065. cb(cur, "result_norm", -1);
  6066. cur = ggml_mul_mat(ctx0, model.output, cur);
  6067. cb(cur, "result_output", -1);
  6068. ggml_build_forward_expand(gf, cur);
  6069. return gf;
  6070. }
  6071. struct ggml_cgraph * build_refact() {
  6072. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6073. const int64_t n_embd_head = hparams.n_embd_head_v;
  6074. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6075. struct ggml_tensor * cur;
  6076. struct ggml_tensor * inpL;
  6077. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6078. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6079. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6080. // positions of the tokens in the KV cache
  6081. struct ggml_tensor * KQ_pos = build_inp_KQ_pos();
  6082. for (int il = 0; il < n_layer; ++il) {
  6083. struct ggml_tensor * inpSA = inpL;
  6084. cur = llm_build_norm(ctx0, inpL, hparams,
  6085. model.layers[il].attn_norm, NULL,
  6086. LLM_NORM_RMS, cb, il);
  6087. cb(cur, "attn_norm", il);
  6088. // self-attention
  6089. {
  6090. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6091. cb(Qcur, "Qcur", il);
  6092. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6093. cb(Kcur, "Kcur", il);
  6094. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6095. cb(Vcur, "Vcur", il);
  6096. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  6097. cb(Kcur, "Kcur", il);
  6098. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6099. cb(Qcur, "Qcur", il);
  6100. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6101. model.layers[il].wo, NULL,
  6102. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6103. }
  6104. if (il == n_layer - 1) {
  6105. // skip computing output for unused tokens
  6106. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6107. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6108. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  6109. }
  6110. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6111. cb(ffn_inp, "ffn_inp", il);
  6112. // feed-forward network
  6113. {
  6114. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6115. model.layers[il].ffn_norm, NULL,
  6116. LLM_NORM_RMS, cb, il);
  6117. cb(cur, "ffn_norm", il);
  6118. cur = llm_build_ffn(ctx0, cur,
  6119. model.layers[il].ffn_up, NULL,
  6120. model.layers[il].ffn_gate, NULL,
  6121. model.layers[il].ffn_down, NULL,
  6122. NULL,
  6123. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6124. cb(cur, "ffn_out", il);
  6125. }
  6126. cur = ggml_add(ctx0, cur, ffn_inp);
  6127. cb(cur, "l_out", il);
  6128. // input for next layer
  6129. inpL = cur;
  6130. }
  6131. cur = inpL;
  6132. cur = llm_build_norm(ctx0, cur, hparams,
  6133. model.output_norm, NULL,
  6134. LLM_NORM_RMS, cb, -1);
  6135. cb(cur, "result_norm", -1);
  6136. // lm_head
  6137. cur = ggml_mul_mat(ctx0, model.output, cur);
  6138. cb(cur, "result_output", -1);
  6139. ggml_build_forward_expand(gf, cur);
  6140. return gf;
  6141. }
  6142. struct ggml_cgraph * build_bert() {
  6143. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6144. const int64_t n_embd_head = hparams.n_embd_head_v;
  6145. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  6146. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6147. struct ggml_tensor * cur;
  6148. struct ggml_tensor * inpL;
  6149. struct ggml_tensor * inp_pos = build_inp_pos();
  6150. struct ggml_tensor * inp_mean = build_inp_mean();
  6151. struct ggml_tensor * inp_cls = build_inp_cls();
  6152. // construct input embeddings (token, type, position)
  6153. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6154. // token types are hardcoded to zero ("Sentence A")
  6155. struct ggml_tensor * type_row0 = ggml_view_1d(ctx0, model.type_embd, n_embd, 0);
  6156. inpL = ggml_add(ctx0, inpL, type_row0);
  6157. if (model.arch == LLM_ARCH_BERT) {
  6158. inpL = ggml_add(ctx0, ggml_get_rows(ctx0, model.pos_embd, inp_pos), inpL);
  6159. }
  6160. cb(inpL, "inp_embd", -1);
  6161. // embed layer norm
  6162. inpL = llm_build_norm(ctx0, inpL, hparams, model.tok_norm, model.tok_norm_b, LLM_NORM, cb, -1);
  6163. cb(inpL, "inp_norm", -1);
  6164. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6165. struct ggml_tensor * KQ_mask = build_inp_KQ_mask(false);
  6166. // iterate layers
  6167. for (int il = 0; il < n_layer; ++il) {
  6168. struct ggml_tensor * cur = inpL;
  6169. struct ggml_tensor * Qcur;
  6170. struct ggml_tensor * Kcur;
  6171. struct ggml_tensor * Vcur;
  6172. // self-attention
  6173. if (model.arch == LLM_ARCH_BERT) {
  6174. Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, cur), model.layers[il].bq);
  6175. cb(Qcur, "Qcur", il);
  6176. Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, cur), model.layers[il].bk);
  6177. cb(Kcur, "Kcur", il);
  6178. Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, cur), model.layers[il].bv);
  6179. cb(Vcur, "Vcur", il);
  6180. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6181. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  6182. } else {
  6183. // compute Q and K and RoPE them
  6184. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6185. cb(cur, "wqkv", il);
  6186. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6187. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  6188. 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)));
  6189. cb(Qcur, "Qcur", il);
  6190. cb(Kcur, "Kcur", il);
  6191. cb(Vcur, "Vcur", il);
  6192. Qcur = ggml_rope_custom(
  6193. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6194. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6195. ext_factor, attn_factor, beta_fast, beta_slow
  6196. );
  6197. cb(Qcur, "Qcur", il);
  6198. Kcur = ggml_rope_custom(
  6199. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6200. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6201. ext_factor, attn_factor, beta_fast, beta_slow
  6202. );
  6203. cb(Kcur, "Kcur", il);
  6204. }
  6205. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  6206. struct ggml_tensor * k = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 0, 2, 1, 3));
  6207. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  6208. cb(kq, "kq", il);
  6209. kq = ggml_soft_max_ext(ctx0, kq, KQ_mask, nullptr, 1.0f/sqrtf(float(n_embd_head)), hparams.f_max_alibi_bias);
  6210. cb(kq, "kq_soft_max_ext", il);
  6211. struct ggml_tensor * v = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_reshape_2d(ctx0, Vcur, n_embd_gqa, n_tokens)));
  6212. cb(v, "v", il);
  6213. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, ggml_reshape_3d(ctx0, v, n_tokens, n_embd_head, n_head_kv), kq);
  6214. cb(kqv, "kqv", il);
  6215. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  6216. cb(kqv_merged, "kqv_merged", il);
  6217. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  6218. cb(cur, "kqv_merged_cont", il);
  6219. ggml_build_forward_expand(gf, cur);
  6220. cur = ggml_mul_mat(ctx0, model.layers[il].wo, cur);
  6221. if (model.layers[il].bo) {
  6222. cb(cur, "kqv_wo", il);
  6223. }
  6224. if (model.layers[il].bo) {
  6225. cur = ggml_add(ctx0, cur, model.layers[il].bo);
  6226. }
  6227. cb(cur, "kqv_out", il);
  6228. if (il == n_layer - 1 && pooling_type == LLAMA_POOLING_TYPE_NONE) {
  6229. // skip computing output for unused tokens
  6230. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6231. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6232. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  6233. }
  6234. // re-add the layer input
  6235. cur = ggml_add(ctx0, cur, inpL);
  6236. // attention layer norm
  6237. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].attn_out_norm, model.layers[il].attn_out_norm_b, LLM_NORM, cb, il);
  6238. struct ggml_tensor * ffn_inp = cur;
  6239. cb(ffn_inp, "ffn_inp", il);
  6240. // feed-forward network
  6241. if (model.arch == LLM_ARCH_BERT) {
  6242. cur = llm_build_ffn(ctx0, cur,
  6243. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6244. NULL, NULL,
  6245. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6246. NULL,
  6247. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6248. } else {
  6249. cur = llm_build_ffn(ctx0, cur,
  6250. model.layers[il].ffn_up, NULL,
  6251. model.layers[il].ffn_gate, NULL,
  6252. model.layers[il].ffn_down, NULL,
  6253. NULL,
  6254. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6255. }
  6256. cb(cur, "ffn_out", il);
  6257. // attentions bypass the intermediate layer
  6258. cur = ggml_add(ctx0, cur, ffn_inp);
  6259. // output layer norm
  6260. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].layer_out_norm, model.layers[il].layer_out_norm_b, LLM_NORM, cb, il);
  6261. // input for next layer
  6262. inpL = cur;
  6263. }
  6264. // final output
  6265. cur = inpL;
  6266. cb(cur, "result_embd", -1);
  6267. // pooling layer
  6268. switch (pooling_type) {
  6269. case LLAMA_POOLING_TYPE_NONE:
  6270. {
  6271. // nop
  6272. } break;
  6273. case LLAMA_POOLING_TYPE_MEAN:
  6274. {
  6275. cur = ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, cur)), inp_mean);
  6276. cb(cur, "result_embd_pooled", -1);
  6277. } break;
  6278. case LLAMA_POOLING_TYPE_CLS:
  6279. {
  6280. cur = ggml_get_rows(ctx0, cur, inp_cls);
  6281. cb(cur, "result_embd_pooled", -1);
  6282. } break;
  6283. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  6284. {
  6285. GGML_ASSERT(false && "Invalid pooling type");
  6286. } break;
  6287. }
  6288. ggml_build_forward_expand(gf, cur);
  6289. return gf;
  6290. }
  6291. struct ggml_cgraph * build_bloom() {
  6292. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6293. const int64_t n_embd_head = hparams.n_embd_head_v;
  6294. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  6295. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6296. struct ggml_tensor * cur;
  6297. struct ggml_tensor * inpL;
  6298. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6299. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6300. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6301. // positions of the tokens in the KV cache
  6302. struct ggml_tensor * KQ_pos = build_inp_KQ_pos();
  6303. inpL = llm_build_norm(ctx0, inpL, hparams,
  6304. model.tok_norm,
  6305. model.tok_norm_b,
  6306. LLM_NORM, cb, -1);
  6307. cb(inpL, "inp_norm", -1);
  6308. for (int il = 0; il < n_layer; ++il) {
  6309. cur = llm_build_norm(ctx0, inpL, hparams,
  6310. model.layers[il].attn_norm,
  6311. model.layers[il].attn_norm_b,
  6312. LLM_NORM, cb, il);
  6313. cb(cur, "attn_norm", il);
  6314. // self-attention
  6315. {
  6316. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6317. cb(cur, "wqkv", il);
  6318. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6319. cb(cur, "bqkv", il);
  6320. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6321. 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)));
  6322. 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)));
  6323. cb(Qcur, "Qcur", il);
  6324. cb(Kcur, "Kcur", il);
  6325. cb(Vcur, "Vcur", il);
  6326. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6327. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6328. model.layers[il].wo, model.layers[il].bo,
  6329. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6330. }
  6331. if (il == n_layer - 1) {
  6332. // skip computing output for unused tokens
  6333. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6334. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6335. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  6336. }
  6337. // Add the input
  6338. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  6339. cb(ffn_inp, "ffn_inp", il);
  6340. // FF
  6341. {
  6342. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6343. model.layers[il].ffn_norm,
  6344. model.layers[il].ffn_norm_b,
  6345. LLM_NORM, cb, il);
  6346. cb(cur, "ffn_norm", il);
  6347. cur = llm_build_ffn(ctx0, cur,
  6348. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6349. NULL, NULL,
  6350. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6351. NULL,
  6352. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6353. cb(cur, "ffn_out", il);
  6354. }
  6355. inpL = ggml_add(ctx0, cur, ffn_inp);
  6356. cb(inpL, "l_out", il);
  6357. }
  6358. cur = llm_build_norm(ctx0, inpL, hparams,
  6359. model.output_norm,
  6360. model.output_norm_b,
  6361. LLM_NORM, cb, -1);
  6362. cb(cur, "result_norm", -1);
  6363. cur = ggml_mul_mat(ctx0, model.output, cur);
  6364. cb(cur, "result_output", -1);
  6365. ggml_build_forward_expand(gf, cur);
  6366. return gf;
  6367. }
  6368. struct ggml_cgraph * build_mpt() {
  6369. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6370. const int64_t n_embd_head = hparams.n_embd_head_v;
  6371. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  6372. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6373. struct ggml_tensor * cur;
  6374. struct ggml_tensor * inpL;
  6375. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6376. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6377. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6378. // positions of the tokens in the KV cache
  6379. struct ggml_tensor * KQ_pos = build_inp_KQ_pos();
  6380. for (int il = 0; il < n_layer; ++il) {
  6381. struct ggml_tensor * attn_norm;
  6382. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  6383. model.layers[il].attn_norm,
  6384. model.layers[il].attn_norm_b,
  6385. LLM_NORM, cb, il);
  6386. cb(attn_norm, "attn_norm", il);
  6387. // self-attention
  6388. {
  6389. cur = attn_norm;
  6390. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6391. cb(cur, "wqkv", il);
  6392. if (model.layers[il].bqkv){
  6393. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6394. cb(cur, "bqkv", il);
  6395. }
  6396. if (hparams.f_clamp_kqv > 0.0f) {
  6397. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  6398. cb(cur, "wqkv_clamped", il);
  6399. }
  6400. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6401. 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)));
  6402. 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)));
  6403. cb(Qcur, "Qcur", il);
  6404. cb(Kcur, "Kcur", il);
  6405. cb(Vcur, "Vcur", il);
  6406. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6407. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6408. model.layers[il].wo, model.layers[il].bo,
  6409. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6410. }
  6411. if (il == n_layer - 1) {
  6412. // skip computing output for unused tokens
  6413. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6414. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6415. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  6416. }
  6417. // Add the input
  6418. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  6419. cb(ffn_inp, "ffn_inp", il);
  6420. // feed forward
  6421. {
  6422. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6423. model.layers[il].ffn_norm,
  6424. model.layers[il].ffn_norm_b,
  6425. LLM_NORM, cb, il);
  6426. cb(cur, "ffn_norm", il);
  6427. cur = llm_build_ffn(ctx0, cur,
  6428. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6429. NULL, NULL,
  6430. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6431. model.layers[il].ffn_act,
  6432. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6433. cb(cur, "ffn_out", il);
  6434. }
  6435. cur = ggml_add(ctx0, cur, ffn_inp);
  6436. cb(cur, "l_out", il);
  6437. // input for next layer
  6438. inpL = cur;
  6439. }
  6440. cur = inpL;
  6441. cur = llm_build_norm(ctx0, cur, hparams,
  6442. model.output_norm,
  6443. model.output_norm_b,
  6444. LLM_NORM, cb, -1);
  6445. cb(cur, "result_norm", -1);
  6446. cur = ggml_mul_mat(ctx0, model.output, cur);
  6447. cb(cur, "result_output", -1);
  6448. ggml_build_forward_expand(gf, cur);
  6449. return gf;
  6450. }
  6451. struct ggml_cgraph * build_stablelm() {
  6452. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  6453. const int64_t n_embd_head = hparams.n_embd_head_v;
  6454. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6455. struct ggml_tensor * cur;
  6456. struct ggml_tensor * inpL;
  6457. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6458. // inp_pos - contains the positions
  6459. struct ggml_tensor * inp_pos = build_inp_pos();
  6460. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6461. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6462. for (int il = 0; il < n_layer; ++il) {
  6463. struct ggml_tensor * inpSA = inpL;
  6464. // norm
  6465. cur = llm_build_norm(ctx0, inpL, hparams,
  6466. model.layers[il].attn_norm,
  6467. model.layers[il].attn_norm_b,
  6468. LLM_NORM, cb, il);
  6469. cb(cur, "attn_norm", il);
  6470. // self-attention
  6471. {
  6472. // compute Q and K and RoPE them
  6473. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6474. cb(Qcur, "Qcur", il);
  6475. if (model.layers[il].bq) {
  6476. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6477. cb(Qcur, "Qcur", il);
  6478. }
  6479. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6480. cb(Kcur, "Kcur", il);
  6481. if (model.layers[il].bk) {
  6482. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6483. cb(Kcur, "Kcur", il);
  6484. }
  6485. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6486. cb(Vcur, "Vcur", il);
  6487. if (model.layers[il].bv) {
  6488. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6489. cb(Vcur, "Vcur", il);
  6490. }
  6491. Qcur = ggml_rope_custom(
  6492. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6493. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6494. ext_factor, attn_factor, beta_fast, beta_slow
  6495. );
  6496. cb(Qcur, "Qcur", il);
  6497. Kcur = ggml_rope_custom(
  6498. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6499. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6500. ext_factor, attn_factor, beta_fast, beta_slow
  6501. );
  6502. cb(Kcur, "Kcur", il);
  6503. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6504. model.layers[il].wo, NULL,
  6505. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6506. }
  6507. if (il == n_layer - 1) {
  6508. // skip computing output for unused tokens
  6509. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6510. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6511. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  6512. }
  6513. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6514. cb(ffn_inp, "ffn_inp", il);
  6515. // feed-forward network
  6516. {
  6517. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6518. model.layers[il].ffn_norm,
  6519. model.layers[il].ffn_norm_b,
  6520. LLM_NORM, cb, il);
  6521. cb(cur, "ffn_norm", il);
  6522. cur = llm_build_ffn(ctx0, cur,
  6523. model.layers[il].ffn_up, NULL,
  6524. model.layers[il].ffn_gate, NULL,
  6525. model.layers[il].ffn_down, NULL,
  6526. NULL,
  6527. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6528. cb(cur, "ffn_out", il);
  6529. }
  6530. cur = ggml_add(ctx0, cur, ffn_inp);
  6531. cb(cur, "l_out", il);
  6532. // input for next layer
  6533. inpL = cur;
  6534. }
  6535. cur = inpL;
  6536. cur = llm_build_norm(ctx0, cur, hparams,
  6537. model.output_norm,
  6538. model.output_norm_b,
  6539. LLM_NORM, cb, -1);
  6540. cb(cur, "result_norm", -1);
  6541. // lm_head
  6542. cur = ggml_mul_mat(ctx0, model.output, cur);
  6543. cb(cur, "result_output", -1);
  6544. ggml_build_forward_expand(gf, cur);
  6545. return gf;
  6546. }
  6547. struct ggml_cgraph * build_qwen() {
  6548. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6549. const int64_t n_embd_head = hparams.n_embd_head_v;
  6550. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6551. struct ggml_tensor * cur;
  6552. struct ggml_tensor * inpL;
  6553. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6554. // inp_pos - contains the positions
  6555. struct ggml_tensor * inp_pos = build_inp_pos();
  6556. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6557. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6558. for (int il = 0; il < n_layer; ++il) {
  6559. struct ggml_tensor * inpSA = inpL;
  6560. cur = llm_build_norm(ctx0, inpL, hparams,
  6561. model.layers[il].attn_norm, NULL,
  6562. LLM_NORM_RMS, cb, il);
  6563. cb(cur, "attn_norm", il);
  6564. // self-attention
  6565. {
  6566. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6567. cb(cur, "wqkv", il);
  6568. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6569. cb(cur, "bqkv", il);
  6570. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6571. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  6572. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 2*sizeof(float)*(n_embd)));
  6573. cb(Qcur, "Qcur", il);
  6574. cb(Kcur, "Kcur", il);
  6575. cb(Vcur, "Vcur", il);
  6576. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6577. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  6578. // using mode = 2 for neox mode
  6579. Qcur = ggml_rope_custom(
  6580. ctx0, Qcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  6581. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  6582. );
  6583. cb(Qcur, "Qcur", il);
  6584. Kcur = ggml_rope_custom(
  6585. ctx0, Kcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  6586. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  6587. );
  6588. cb(Kcur, "Kcur", il);
  6589. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6590. model.layers[il].wo, NULL,
  6591. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6592. }
  6593. if (il == n_layer - 1) {
  6594. // skip computing output for unused tokens
  6595. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6596. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6597. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  6598. }
  6599. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6600. cb(ffn_inp, "ffn_inp", il);
  6601. // feed-forward forward
  6602. {
  6603. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6604. model.layers[il].ffn_norm, NULL,
  6605. LLM_NORM_RMS, cb, il);
  6606. cb(cur, "ffn_norm", il);
  6607. cur = llm_build_ffn(ctx0, cur,
  6608. model.layers[il].ffn_up, NULL,
  6609. model.layers[il].ffn_gate, NULL,
  6610. model.layers[il].ffn_down, NULL,
  6611. NULL,
  6612. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6613. cb(cur, "ffn_out", il);
  6614. }
  6615. cur = ggml_add(ctx0, cur, ffn_inp);
  6616. cb(cur, "l_out", il);
  6617. // input for next layer
  6618. inpL = cur;
  6619. }
  6620. cur = inpL;
  6621. cur = llm_build_norm(ctx0, cur, hparams,
  6622. model.output_norm, NULL,
  6623. LLM_NORM_RMS, cb, -1);
  6624. cb(cur, "result_norm", -1);
  6625. // lm_head
  6626. cur = ggml_mul_mat(ctx0, model.output, cur);
  6627. cb(cur, "result_output", -1);
  6628. ggml_build_forward_expand(gf, cur);
  6629. return gf;
  6630. }
  6631. struct ggml_cgraph * build_qwen2() {
  6632. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6633. const int64_t n_embd_head = hparams.n_embd_head_v;
  6634. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6635. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6636. struct ggml_tensor * cur;
  6637. struct ggml_tensor * inpL;
  6638. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6639. // inp_pos - contains the positions
  6640. struct ggml_tensor * inp_pos = build_inp_pos();
  6641. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6642. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6643. for (int il = 0; il < n_layer; ++il) {
  6644. struct ggml_tensor * inpSA = inpL;
  6645. // norm
  6646. cur = llm_build_norm(ctx0, inpL, hparams,
  6647. model.layers[il].attn_norm, NULL,
  6648. LLM_NORM_RMS, cb, il);
  6649. cb(cur, "attn_norm", il);
  6650. // self-attention
  6651. {
  6652. // compute Q and K and RoPE them
  6653. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6654. cb(Qcur, "Qcur", il);
  6655. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6656. cb(Qcur, "Qcur", il);
  6657. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6658. cb(Kcur, "Kcur", il);
  6659. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6660. cb(Kcur, "Kcur", il);
  6661. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6662. cb(Vcur, "Vcur", il);
  6663. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6664. cb(Vcur, "Vcur", il);
  6665. // these nodes are added to the graph together so that they are not reordered
  6666. // by doing so, the number of splits in the graph is reduced
  6667. ggml_build_forward_expand(gf, Qcur);
  6668. ggml_build_forward_expand(gf, Kcur);
  6669. ggml_build_forward_expand(gf, Vcur);
  6670. Qcur = ggml_rope_custom(
  6671. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6672. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6673. ext_factor, attn_factor, beta_fast, beta_slow
  6674. );
  6675. cb(Qcur, "Qcur", il);
  6676. Kcur = ggml_rope_custom(
  6677. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6678. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6679. ext_factor, attn_factor, beta_fast, beta_slow
  6680. );
  6681. cb(Kcur, "Kcur", il);
  6682. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6683. model.layers[il].wo, model.layers[il].bo,
  6684. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6685. }
  6686. if (il == n_layer - 1) {
  6687. // skip computing output for unused tokens
  6688. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6689. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6690. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  6691. }
  6692. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6693. cb(ffn_inp, "ffn_inp", il);
  6694. // feed-forward network
  6695. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6696. model.layers[il].ffn_norm, NULL,
  6697. LLM_NORM_RMS, cb, il);
  6698. cb(cur, "ffn_norm", il);
  6699. cur = llm_build_ffn(ctx0, cur,
  6700. model.layers[il].ffn_up, NULL,
  6701. model.layers[il].ffn_gate, NULL,
  6702. model.layers[il].ffn_down, NULL,
  6703. NULL,
  6704. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6705. cb(cur, "ffn_out", il);
  6706. cur = ggml_add(ctx0, cur, ffn_inp);
  6707. cb(cur, "l_out", il);
  6708. // input for next layer
  6709. inpL = cur;
  6710. }
  6711. cur = inpL;
  6712. cur = llm_build_norm(ctx0, cur, hparams,
  6713. model.output_norm, NULL,
  6714. LLM_NORM_RMS, cb, -1);
  6715. cb(cur, "result_norm", -1);
  6716. // lm_head
  6717. cur = ggml_mul_mat(ctx0, model.output, cur);
  6718. cb(cur, "result_output", -1);
  6719. ggml_build_forward_expand(gf, cur);
  6720. return gf;
  6721. }
  6722. struct ggml_cgraph * build_phi2() {
  6723. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6724. const int64_t n_embd_head = hparams.n_embd_head_v;
  6725. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  6726. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6727. struct ggml_tensor * cur;
  6728. struct ggml_tensor * attn_norm_output;
  6729. struct ggml_tensor * ffn_output;
  6730. struct ggml_tensor * inpL;
  6731. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6732. // inp_pos - contains the positions
  6733. struct ggml_tensor * inp_pos = build_inp_pos();
  6734. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6735. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6736. for (int il = 0; il < n_layer; ++il) {
  6737. attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  6738. model.layers[il].attn_norm,
  6739. model.layers[il].attn_norm_b,
  6740. LLM_NORM, cb, il);
  6741. cb(attn_norm_output, "attn_norm", il);
  6742. // self-attention
  6743. {
  6744. struct ggml_tensor * Qcur = nullptr;
  6745. struct ggml_tensor * Kcur = nullptr;
  6746. struct ggml_tensor * Vcur = nullptr;
  6747. if (model.layers[il].wqkv) {
  6748. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, attn_norm_output);
  6749. cb(cur, "wqkv", il);
  6750. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6751. cb(cur, "bqkv", il);
  6752. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6753. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  6754. 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)));
  6755. } else {
  6756. Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  6757. Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  6758. Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  6759. }
  6760. cb(Qcur, "Qcur", il);
  6761. cb(Kcur, "Kcur", il);
  6762. cb(Vcur, "Vcur", il);
  6763. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6764. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  6765. Qcur = ggml_rope_custom(
  6766. ctx0, Qcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  6767. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  6768. );
  6769. cb(Qcur, "Qcur", il);
  6770. // with phi2, we scale the Q to avoid precision issues
  6771. // ref: https://github.com/ml-explore/mlx-examples/blob/08e862336ade809bc37d1035f94b359e7d1a5152/phi2/phi2.py#L64-L66
  6772. Qcur = ggml_scale(ctx0, Qcur, 1.0f/sqrtf(float(n_embd_head)));
  6773. cb(Qcur, "Qcur", il);
  6774. Kcur = ggml_rope_custom(
  6775. ctx0, Kcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  6776. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  6777. );
  6778. cb(Kcur, "Kcur", il);
  6779. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6780. model.layers[il].wo, model.layers[il].bo,
  6781. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  6782. }
  6783. if (il == n_layer - 1) {
  6784. // skip computing output for unused tokens
  6785. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6786. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6787. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  6788. attn_norm_output = ggml_get_rows(ctx0, attn_norm_output, inp_out_ids);
  6789. }
  6790. // FF
  6791. {
  6792. ffn_output = llm_build_ffn(ctx0, attn_norm_output,
  6793. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6794. NULL, NULL,
  6795. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6796. NULL,
  6797. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6798. cb(ffn_output, "ffn_out", il);
  6799. }
  6800. cur = ggml_add(ctx0, cur, ffn_output);
  6801. cb(cur, "l_out", il);
  6802. cur = ggml_add(ctx0, cur, inpL);
  6803. cb(cur, "l_out", il);
  6804. inpL = cur;
  6805. }
  6806. cur = llm_build_norm(ctx0, inpL, hparams,
  6807. model.output_norm,
  6808. model.output_norm_b,
  6809. LLM_NORM, cb, -1);
  6810. cb(cur, "result_norm", -1);
  6811. cur = ggml_mul_mat(ctx0, model.output, cur);
  6812. cb(cur, "result_output_no_bias", -1);
  6813. cur = ggml_add(ctx0, cur, model.output_b);
  6814. cb(cur, "result_output", -1);
  6815. ggml_build_forward_expand(gf, cur);
  6816. return gf;
  6817. }
  6818. struct ggml_cgraph * build_plamo() {
  6819. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  6820. const int64_t n_embd_head = hparams.n_embd_head_v;
  6821. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6822. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6823. struct ggml_tensor * cur;
  6824. struct ggml_tensor * inpL;
  6825. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6826. // inp_pos - contains the positions
  6827. struct ggml_tensor * inp_pos = build_inp_pos();
  6828. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6829. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6830. for (int il = 0; il < n_layer; ++il) {
  6831. // norm
  6832. cur = llm_build_norm(ctx0, inpL, hparams,
  6833. model.layers[il].attn_norm, NULL,
  6834. LLM_NORM_RMS, cb, il);
  6835. cb(cur, "attn_norm", il);
  6836. struct ggml_tensor * attention_norm = cur;
  6837. // self-attention
  6838. {
  6839. // compute Q and K and RoPE them
  6840. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6841. cb(Qcur, "Qcur", il);
  6842. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6843. cb(Kcur, "Kcur", il);
  6844. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6845. cb(Vcur, "Vcur", il);
  6846. Qcur = ggml_rope_custom(
  6847. ctx0, ggml_reshape_3d(ctx0, Qcur, n_rot, n_head, n_tokens), inp_pos,
  6848. n_embd_head, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6849. ext_factor, attn_factor, beta_fast, beta_slow);
  6850. cb(Qcur, "Qcur", il);
  6851. Kcur = ggml_rope_custom(
  6852. ctx0, ggml_reshape_3d(ctx0, Kcur, n_rot, n_head_kv, n_tokens), inp_pos,
  6853. n_embd_head, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6854. ext_factor, attn_factor, beta_fast, beta_slow);
  6855. cb(Kcur, "Kcur", il);
  6856. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6857. model.layers[il].wo, NULL,
  6858. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6859. }
  6860. struct ggml_tensor * sa_out = cur;
  6861. cur = attention_norm;
  6862. if (il == n_layer - 1) {
  6863. // skip computing output for unused tokens
  6864. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6865. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6866. sa_out = ggml_get_rows(ctx0, sa_out, inp_out_ids);
  6867. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  6868. }
  6869. // feed-forward network
  6870. {
  6871. cur = llm_build_ffn(ctx0, cur,
  6872. model.layers[il].ffn_up, NULL,
  6873. model.layers[il].ffn_gate, NULL,
  6874. model.layers[il].ffn_down, NULL,
  6875. NULL,
  6876. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6877. cb(cur, "ffn_out", il);
  6878. }
  6879. cur = ggml_add(ctx0, cur, sa_out);
  6880. cb(cur, "l_out", il);
  6881. cur = ggml_add(ctx0, cur, inpL);
  6882. cb(cur, "l_out", il);
  6883. // input for next layer
  6884. inpL = cur;
  6885. }
  6886. cur = inpL;
  6887. cur = llm_build_norm(ctx0, cur, hparams,
  6888. model.output_norm, NULL,
  6889. LLM_NORM_RMS, cb, -1);
  6890. cb(cur, "result_norm", -1);
  6891. // lm_head
  6892. cur = ggml_mul_mat(ctx0, model.output, cur);
  6893. cb(cur, "result_output", -1);
  6894. ggml_build_forward_expand(gf, cur);
  6895. return gf;
  6896. }
  6897. struct ggml_cgraph * build_gpt2() {
  6898. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6899. const int64_t n_embd_head = hparams.n_embd_head_v;
  6900. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  6901. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6902. struct ggml_tensor * cur;
  6903. struct ggml_tensor * pos;
  6904. struct ggml_tensor * inpL;
  6905. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6906. // inp_pos - contains the positions
  6907. struct ggml_tensor * inp_pos = build_inp_pos();
  6908. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6909. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6910. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  6911. cb(pos, "pos_embd", -1);
  6912. inpL = ggml_add(ctx0, inpL, pos);
  6913. cb(inpL, "inpL", -1);
  6914. for (int il = 0; il < n_layer; ++il) {
  6915. cur = llm_build_norm(ctx0, inpL, hparams,
  6916. model.layers[il].attn_norm,
  6917. model.layers[il].attn_norm_b,
  6918. LLM_NORM, cb, il);
  6919. cb(cur, "attn_norm", il);
  6920. // self-attention
  6921. {
  6922. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6923. cb(cur, "wqkv", il);
  6924. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6925. cb(cur, "bqkv", il);
  6926. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6927. 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)));
  6928. 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)));
  6929. cb(Qcur, "Qcur", il);
  6930. cb(Kcur, "Kcur", il);
  6931. cb(Vcur, "Vcur", il);
  6932. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6933. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6934. model.layers[il].wo, model.layers[il].bo,
  6935. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6936. }
  6937. if (il == n_layer - 1) {
  6938. // skip computing output for unused tokens
  6939. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6940. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6941. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  6942. }
  6943. // add the input
  6944. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  6945. cb(ffn_inp, "ffn_inp", il);
  6946. // FF
  6947. {
  6948. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6949. model.layers[il].ffn_norm,
  6950. model.layers[il].ffn_norm_b,
  6951. LLM_NORM, cb, il);
  6952. cb(cur, "ffn_norm", il);
  6953. cur = llm_build_ffn(ctx0, cur,
  6954. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6955. NULL, NULL,
  6956. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6957. NULL,
  6958. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6959. cb(cur, "ffn_out", il);
  6960. }
  6961. inpL = ggml_add(ctx0, cur, ffn_inp);
  6962. cb(inpL, "l_out", il);
  6963. }
  6964. cur = llm_build_norm(ctx0, inpL, hparams,
  6965. model.output_norm,
  6966. model.output_norm_b,
  6967. LLM_NORM, cb, -1);
  6968. cb(cur, "result_norm", -1);
  6969. cur = ggml_mul_mat(ctx0, model.output, cur);
  6970. cb(cur, "result_output", -1);
  6971. ggml_build_forward_expand(gf, cur);
  6972. return gf;
  6973. }
  6974. struct ggml_cgraph * build_codeshell() {
  6975. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6976. const int64_t n_embd_head = hparams.n_embd_head_v;
  6977. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  6978. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6979. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6980. struct ggml_tensor * cur;
  6981. struct ggml_tensor * inpL;
  6982. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6983. // inp_pos - contains the positions
  6984. struct ggml_tensor * inp_pos = build_inp_pos();
  6985. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6986. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6987. for (int il = 0; il < n_layer; ++il) {
  6988. cur = llm_build_norm(ctx0, inpL, hparams,
  6989. model.layers[il].attn_norm,
  6990. model.layers[il].attn_norm_b,
  6991. LLM_NORM, cb, il);
  6992. cb(cur, "attn_norm", il);
  6993. // self-attention
  6994. {
  6995. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6996. cb(cur, "wqkv", il);
  6997. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6998. cb(cur, "bqkv", il);
  6999. struct ggml_tensor * tmpq = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  7000. 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)));
  7001. 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)));
  7002. cb(tmpq, "tmpq", il);
  7003. cb(tmpk, "tmpk", il);
  7004. cb(Vcur, "Vcur", il);
  7005. struct ggml_tensor * Qcur = ggml_rope_custom(
  7006. ctx0, ggml_reshape_3d(ctx0, tmpq, n_embd_head, n_head, n_tokens), inp_pos,
  7007. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7008. ext_factor, attn_factor, beta_fast, beta_slow
  7009. );
  7010. cb(Qcur, "Qcur", il);
  7011. struct ggml_tensor * Kcur = ggml_rope_custom(
  7012. ctx0, ggml_reshape_3d(ctx0, tmpk, n_embd_head, n_head_kv, n_tokens), inp_pos,
  7013. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7014. ext_factor, attn_factor, beta_fast, beta_slow
  7015. );
  7016. cb(Kcur, "Kcur", il);
  7017. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  7018. model.layers[il].wo, model.layers[il].bo,
  7019. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7020. }
  7021. if (il == n_layer - 1) {
  7022. // skip computing output for unused tokens
  7023. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7024. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7025. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  7026. }
  7027. // add the input
  7028. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  7029. cb(ffn_inp, "ffn_inp", il);
  7030. // FF
  7031. {
  7032. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7033. model.layers[il].ffn_norm,
  7034. model.layers[il].ffn_norm_b,
  7035. LLM_NORM, cb, il);
  7036. cb(cur, "ffn_norm", il);
  7037. cur = llm_build_ffn(ctx0, cur,
  7038. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  7039. NULL, NULL,
  7040. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  7041. NULL,
  7042. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  7043. cb(cur, "ffn_out", il);
  7044. }
  7045. inpL = ggml_add(ctx0, cur, ffn_inp);
  7046. cb(inpL, "l_out", il);
  7047. }
  7048. cur = llm_build_norm(ctx0, inpL, hparams,
  7049. model.output_norm,
  7050. model.output_norm_b,
  7051. LLM_NORM, cb, -1);
  7052. cb(cur, "result_norm", -1);
  7053. cur = ggml_mul_mat(ctx0, model.output, cur);
  7054. cb(cur, "result_output", -1);
  7055. ggml_build_forward_expand(gf, cur);
  7056. return gf;
  7057. }
  7058. struct ggml_cgraph * build_orion() {
  7059. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7060. const int64_t n_embd_head = hparams.n_embd_head_v;
  7061. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7062. GGML_ASSERT(n_embd_head == hparams.n_rot);
  7063. struct ggml_tensor * cur;
  7064. struct ggml_tensor * inpL;
  7065. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7066. // inp_pos - contains the positions
  7067. struct ggml_tensor * inp_pos = build_inp_pos();
  7068. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7069. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7070. for (int il = 0; il < n_layer; ++il) {
  7071. struct ggml_tensor * inpSA = inpL;
  7072. // norm
  7073. cur = llm_build_norm(ctx0, inpL, hparams,
  7074. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  7075. LLM_NORM, cb, il);
  7076. cb(cur, "attn_norm", il);
  7077. // self-attention
  7078. {
  7079. // compute Q and K and RoPE them
  7080. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  7081. cb(Qcur, "Qcur", il);
  7082. // if (model.layers[il].bq) {
  7083. // Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  7084. // cb(Qcur, "Qcur", il);
  7085. // }
  7086. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  7087. cb(Kcur, "Kcur", il);
  7088. // if (model.layers[il].bk) {
  7089. // Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  7090. // cb(Kcur, "Kcur", il);
  7091. // }
  7092. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  7093. cb(Vcur, "Vcur", il);
  7094. // if (model.layers[il].bv) {
  7095. // Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  7096. // cb(Vcur, "Vcur", il);
  7097. // }
  7098. Qcur = ggml_rope_custom(
  7099. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  7100. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7101. ext_factor, attn_factor, beta_fast, beta_slow
  7102. );
  7103. cb(Qcur, "Qcur", il);
  7104. Kcur = ggml_rope_custom(
  7105. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  7106. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7107. ext_factor, attn_factor, beta_fast, beta_slow
  7108. );
  7109. cb(Kcur, "Kcur", il);
  7110. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  7111. model.layers[il].wo, NULL,
  7112. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7113. }
  7114. if (il == n_layer - 1) {
  7115. // skip computing output for unused tokens
  7116. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7117. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7118. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  7119. }
  7120. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  7121. cb(ffn_inp, "ffn_inp", il);
  7122. // feed-forward network
  7123. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7124. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  7125. LLM_NORM, cb, il);
  7126. cb(cur, "ffn_norm", il);
  7127. cur = llm_build_ffn(ctx0, cur,
  7128. model.layers[il].ffn_up, NULL,
  7129. model.layers[il].ffn_gate, NULL,
  7130. model.layers[il].ffn_down, NULL,
  7131. NULL,
  7132. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  7133. cb(cur, "ffn_out", il);
  7134. cur = ggml_add(ctx0, cur, ffn_inp);
  7135. cb(cur, "l_out", il);
  7136. // input for next layer
  7137. inpL = cur;
  7138. }
  7139. cur = inpL;
  7140. cur = llm_build_norm(ctx0, cur, hparams,
  7141. model.output_norm, model.output_norm_b,
  7142. LLM_NORM, cb, -1);
  7143. cb(cur, "result_norm", -1);
  7144. // lm_head
  7145. cur = ggml_mul_mat(ctx0, model.output, cur);
  7146. cb(cur, "result_output", -1);
  7147. ggml_build_forward_expand(gf, cur);
  7148. return gf;
  7149. }
  7150. struct ggml_cgraph * build_internlm2() {
  7151. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7152. const int64_t n_embd_head = hparams.n_embd_head_v;
  7153. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7154. GGML_ASSERT(n_embd_head == hparams.n_rot);
  7155. struct ggml_tensor * cur;
  7156. struct ggml_tensor * inpL;
  7157. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7158. // inp_pos - contains the positions
  7159. struct ggml_tensor * inp_pos = build_inp_pos();
  7160. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7161. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7162. for (int il = 0; il < n_layer; ++il) {
  7163. struct ggml_tensor * inpSA = inpL;
  7164. // norm
  7165. cur = llm_build_norm(ctx0, inpL, hparams,
  7166. model.layers[il].attn_norm, NULL,
  7167. LLM_NORM_RMS, cb, il);
  7168. cb(cur, "attn_norm", il);
  7169. // self-attention
  7170. {
  7171. // compute Q and K and RoPE them
  7172. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  7173. cb(Qcur, "Qcur", il);
  7174. if (model.layers[il].bq) {
  7175. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  7176. cb(Qcur, "Qcur", il);
  7177. }
  7178. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  7179. cb(Kcur, "Kcur", il);
  7180. if (model.layers[il].bk) {
  7181. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  7182. cb(Kcur, "Kcur", il);
  7183. }
  7184. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  7185. cb(Vcur, "Vcur", il);
  7186. if (model.layers[il].bv) {
  7187. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  7188. cb(Vcur, "Vcur", il);
  7189. }
  7190. Qcur = ggml_rope_custom(
  7191. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  7192. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7193. ext_factor, attn_factor, beta_fast, beta_slow
  7194. );
  7195. cb(Qcur, "Qcur", il);
  7196. Kcur = ggml_rope_custom(
  7197. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  7198. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7199. ext_factor, attn_factor, beta_fast, beta_slow
  7200. );
  7201. cb(Kcur, "Kcur", il);
  7202. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  7203. model.layers[il].wo, model.layers[il].bo,
  7204. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7205. }
  7206. if (il == n_layer - 1) {
  7207. // skip computing output for unused tokens
  7208. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7209. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7210. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  7211. }
  7212. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  7213. cb(ffn_inp, "ffn_inp", il);
  7214. // feed-forward network
  7215. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7216. model.layers[il].ffn_norm, NULL,
  7217. LLM_NORM_RMS, cb, il);
  7218. cb(cur, "ffn_norm", il);
  7219. cur = llm_build_ffn(ctx0, cur,
  7220. model.layers[il].ffn_up, NULL,
  7221. model.layers[il].ffn_gate, NULL,
  7222. model.layers[il].ffn_down, NULL,
  7223. NULL,
  7224. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  7225. cb(cur, "ffn_out", il);
  7226. cur = ggml_add(ctx0, cur, ffn_inp);
  7227. cb(cur, "l_out", il);
  7228. // input for next layer
  7229. inpL = cur;
  7230. }
  7231. cur = inpL;
  7232. cur = llm_build_norm(ctx0, cur, hparams,
  7233. model.output_norm, NULL,
  7234. LLM_NORM_RMS, cb, -1);
  7235. cb(cur, "result_norm", -1);
  7236. // lm_head
  7237. cur = ggml_mul_mat(ctx0, model.output, cur);
  7238. cb(cur, "result_output", -1);
  7239. ggml_build_forward_expand(gf, cur);
  7240. return gf;
  7241. }
  7242. // ref: https://arxiv.org/abs/2203.03466
  7243. // https://github.com/ggerganov/llama.cpp/issues/5276#issuecomment-1925774738
  7244. // based on the original build_llama() function
  7245. struct ggml_cgraph * build_minicpm() {
  7246. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7247. const int64_t n_embd_head = hparams.n_embd_head_v;
  7248. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7249. GGML_ASSERT(n_embd_head == hparams.n_rot);
  7250. const int64_t n_embd = hparams.n_embd;
  7251. //TODO: if the model varies, these parameters need to be read from the model
  7252. const int64_t n_embd_base = 256;
  7253. const float scale_embd = 12.0f;
  7254. const float scale_depth = 1.4f;
  7255. struct ggml_tensor * cur;
  7256. struct ggml_tensor * inpL;
  7257. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7258. // scale the input embeddings
  7259. inpL = ggml_scale(ctx0, inpL, scale_embd);
  7260. cb(inpL, "inp_scaled", -1);
  7261. // inp_pos - contains the positions
  7262. struct ggml_tensor * inp_pos = build_inp_pos();
  7263. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7264. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7265. for (int il = 0; il < n_layer; ++il) {
  7266. struct ggml_tensor * inpSA = inpL;
  7267. // norm
  7268. cur = llm_build_norm(ctx0, inpL, hparams,
  7269. model.layers[il].attn_norm, NULL,
  7270. LLM_NORM_RMS, cb, il);
  7271. cb(cur, "attn_norm", il);
  7272. // self-attention
  7273. {
  7274. // compute Q and K and RoPE them
  7275. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  7276. cb(Qcur, "Qcur", il);
  7277. if (model.layers[il].bq) {
  7278. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  7279. cb(Qcur, "Qcur", il);
  7280. }
  7281. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  7282. cb(Kcur, "Kcur", il);
  7283. if (model.layers[il].bk) {
  7284. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  7285. cb(Kcur, "Kcur", il);
  7286. }
  7287. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  7288. cb(Vcur, "Vcur", il);
  7289. if (model.layers[il].bv) {
  7290. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  7291. cb(Vcur, "Vcur", il);
  7292. }
  7293. Qcur = ggml_rope_custom(
  7294. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  7295. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7296. ext_factor, attn_factor, beta_fast, beta_slow
  7297. );
  7298. cb(Qcur, "Qcur", il);
  7299. Kcur = ggml_rope_custom(
  7300. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  7301. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7302. ext_factor, attn_factor, beta_fast, beta_slow
  7303. );
  7304. cb(Kcur, "Kcur", il);
  7305. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  7306. model.layers[il].wo, model.layers[il].bo,
  7307. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7308. }
  7309. if (il == n_layer - 1) {
  7310. // skip computing output for unused tokens
  7311. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7312. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7313. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  7314. }
  7315. // scale_res - scale the hidden states for residual connection
  7316. const float scale_res = scale_depth/sqrtf(float(n_layer));
  7317. cur = ggml_scale(ctx0, cur, scale_res);
  7318. cb(cur, "hidden_scaled", -1);
  7319. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  7320. cb(ffn_inp, "ffn_inp", il);
  7321. // feed-forward network
  7322. {
  7323. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7324. model.layers[il].ffn_norm, NULL,
  7325. LLM_NORM_RMS, cb, il);
  7326. cb(cur, "ffn_norm", il);
  7327. cur = llm_build_ffn(ctx0, cur,
  7328. model.layers[il].ffn_up, NULL,
  7329. model.layers[il].ffn_gate, NULL,
  7330. model.layers[il].ffn_down, NULL,
  7331. NULL,
  7332. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  7333. cb(cur, "ffn_out", il);
  7334. }
  7335. // scale the hidden states for residual connection
  7336. cur = ggml_scale(ctx0, cur, scale_res);
  7337. cb(cur, "hidden_scaled_ffn", -1);
  7338. cur = ggml_add(ctx0, cur, ffn_inp);
  7339. cb(cur, "l_out", il);
  7340. // input for next layer
  7341. inpL = cur;
  7342. }
  7343. cur = inpL;
  7344. cur = llm_build_norm(ctx0, cur, hparams,
  7345. model.output_norm, NULL,
  7346. LLM_NORM_RMS, cb, -1);
  7347. cb(cur, "result_norm", -1);
  7348. // lm_head scaling
  7349. const float scale_lmhead = float(n_embd_base)/float(n_embd);
  7350. cur = ggml_scale(ctx0, cur, scale_lmhead);
  7351. cb(cur, "lmhead_scaling", -1);
  7352. // lm_head
  7353. cur = ggml_mul_mat(ctx0, model.tok_embd, cur);
  7354. cb(cur, "result_output", -1);
  7355. ggml_build_forward_expand(gf, cur);
  7356. return gf;
  7357. }
  7358. struct ggml_cgraph * build_gemma() {
  7359. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7360. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  7361. struct ggml_tensor * cur;
  7362. struct ggml_tensor * inpL;
  7363. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7364. inpL = ggml_scale(ctx0, inpL, sqrtf(n_embd));
  7365. cb(inpL, "inp_scaled", -1);
  7366. // inp_pos - contains the positions
  7367. struct ggml_tensor * inp_pos = build_inp_pos();
  7368. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7369. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7370. for (int il = 0; il < n_layer; ++il) {
  7371. // norm
  7372. cur = llm_build_norm(ctx0, inpL, hparams,
  7373. model.layers[il].attn_norm, NULL,
  7374. LLM_NORM_RMS, cb, il);
  7375. cb(cur, "attn_norm", il);
  7376. // self-attention
  7377. {
  7378. // compute Q and K and RoPE them
  7379. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  7380. cb(Qcur, "Qcur", il);
  7381. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  7382. cb(Kcur, "Kcur", il);
  7383. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  7384. cb(Vcur, "Vcur", il);
  7385. Qcur = ggml_rope_custom(
  7386. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head_k, n_head, n_tokens), inp_pos,
  7387. n_embd_head_k, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7388. ext_factor, attn_factor, beta_fast, beta_slow);
  7389. cb(Qcur, "Qcur", il);
  7390. Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head_k)));
  7391. cb(Qcur, "Qcur_scaled", il);
  7392. Kcur = ggml_rope_custom(
  7393. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head_k, n_head_kv, n_tokens), inp_pos,
  7394. n_embd_head_k, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7395. ext_factor, attn_factor, beta_fast, beta_slow);
  7396. cb(Kcur, "Kcur", il);
  7397. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  7398. model.layers[il].wo, NULL,
  7399. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  7400. }
  7401. if (il == n_layer - 1) {
  7402. // skip computing output for unused tokens
  7403. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7404. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7405. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  7406. }
  7407. struct ggml_tensor * sa_out = ggml_add(ctx0, cur, inpL);
  7408. cb(sa_out, "sa_out", il);
  7409. cur = llm_build_norm(ctx0, sa_out, hparams,
  7410. model.layers[il].ffn_norm, NULL,
  7411. LLM_NORM_RMS, cb, il);
  7412. cb(cur, "ffn_norm", il);
  7413. // feed-forward network
  7414. {
  7415. cur = llm_build_ffn(ctx0, cur,
  7416. model.layers[il].ffn_up, NULL,
  7417. model.layers[il].ffn_gate, NULL,
  7418. model.layers[il].ffn_down, NULL,
  7419. NULL,
  7420. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  7421. cb(cur, "ffn_out", il);
  7422. }
  7423. cur = ggml_add(ctx0, cur, sa_out);
  7424. cb(cur, "l_out", il);
  7425. // input for next layer
  7426. inpL = cur;
  7427. }
  7428. cur = inpL;
  7429. cur = llm_build_norm(ctx0, cur, hparams,
  7430. model.output_norm, NULL,
  7431. LLM_NORM_RMS, cb, -1);
  7432. cb(cur, "result_norm", -1);
  7433. // lm_head
  7434. cur = ggml_mul_mat(ctx0, model.output, cur);
  7435. cb(cur, "result_output", -1);
  7436. ggml_build_forward_expand(gf, cur);
  7437. return gf;
  7438. }
  7439. struct ggml_cgraph * build_starcoder2() {
  7440. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7441. const int64_t n_embd_head = hparams.n_embd_head_v;
  7442. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7443. GGML_ASSERT(n_embd_head == hparams.n_rot);
  7444. struct ggml_tensor * cur;
  7445. struct ggml_tensor * inpL;
  7446. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7447. // inp_pos - contains the positions
  7448. struct ggml_tensor * inp_pos = build_inp_pos();
  7449. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7450. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7451. for (int il = 0; il < n_layer; ++il) {
  7452. struct ggml_tensor * inpSA = inpL;
  7453. // norm
  7454. cur = llm_build_norm(ctx0, inpL, hparams,
  7455. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  7456. LLM_NORM, cb, il);
  7457. cb(cur, "attn_norm", il);
  7458. // self-attention
  7459. {
  7460. // compute Q and K and RoPE them
  7461. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  7462. cb(Qcur, "Qcur", il);
  7463. if (model.layers[il].bq) {
  7464. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  7465. cb(Qcur, "Qcur", il);
  7466. }
  7467. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  7468. cb(Kcur, "Kcur", il);
  7469. if (model.layers[il].bk) {
  7470. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  7471. cb(Kcur, "Kcur", il);
  7472. }
  7473. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  7474. cb(Vcur, "Vcur", il);
  7475. if (model.layers[il].bv) {
  7476. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  7477. cb(Vcur, "Vcur", il);
  7478. }
  7479. Qcur = ggml_rope_custom(
  7480. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  7481. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7482. ext_factor, attn_factor, beta_fast, beta_slow
  7483. );
  7484. cb(Qcur, "Qcur", il);
  7485. Kcur = ggml_rope_custom(
  7486. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  7487. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7488. ext_factor, attn_factor, beta_fast, beta_slow
  7489. );
  7490. cb(Kcur, "Kcur", il);
  7491. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  7492. model.layers[il].wo, model.layers[il].bo,
  7493. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7494. }
  7495. if (il == n_layer - 1) {
  7496. // skip computing output for unused tokens
  7497. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7498. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7499. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  7500. }
  7501. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  7502. cb(ffn_inp, "ffn_inp", il);
  7503. // feed-forward network
  7504. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7505. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  7506. LLM_NORM, cb, il);
  7507. cb(cur, "ffn_norm", il);
  7508. cur = llm_build_ffn(ctx0, cur,
  7509. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  7510. NULL, NULL,
  7511. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  7512. NULL,
  7513. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  7514. cb(cur, "ffn_out", il);
  7515. cur = ggml_add(ctx0, cur, ffn_inp);
  7516. cb(cur, "l_out", il);
  7517. // input for next layer
  7518. inpL = cur;
  7519. }
  7520. cur = inpL;
  7521. cur = llm_build_norm(ctx0, cur, hparams,
  7522. model.output_norm, model.output_norm_b,
  7523. LLM_NORM, cb, -1);
  7524. cb(cur, "result_norm", -1);
  7525. // lm_head
  7526. cur = ggml_mul_mat(ctx0, model.output, cur);
  7527. cb(cur, "result_output", -1);
  7528. ggml_build_forward_expand(gf, cur);
  7529. return gf;
  7530. }
  7531. struct ggml_cgraph * build_mamba() {
  7532. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7533. const int64_t d_model = n_embd;
  7534. const int64_t d_conv = hparams.ssm_d_conv;
  7535. const int64_t d_inner = hparams.ssm_d_inner;
  7536. GGML_ASSERT(2 * d_model == d_inner);
  7537. const int64_t d_state = hparams.ssm_d_state;
  7538. const int64_t dt_rank = hparams.ssm_dt_rank;
  7539. struct ggml_tensor * cur;
  7540. struct ggml_tensor * inpL;
  7541. // {n_embd, n_tokens}
  7542. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7543. struct ggml_tensor * state_mask = build_inp_s_mask();
  7544. struct ggml_tensor * state_seq = build_inp_s_seq();
  7545. for (int il = 0; il < n_layer; ++il) {
  7546. // (ab)using the KV cache to store the states
  7547. struct ggml_tensor * conv_states = ggml_reshape_2d(ctx0, kv_self.k_l[il], hparams.n_embd_k_s(), kv_self.size);
  7548. struct ggml_tensor * ssm_states = ggml_reshape_2d(ctx0, kv_self.v_l[il], hparams.n_embd_v_s(), kv_self.size);
  7549. // clear states of sequences which are starting at the beginning of this batch
  7550. {
  7551. conv_states = ggml_mul(ctx0,
  7552. ggml_view_2d(ctx0, conv_states, conv_states->ne[0], n_kv, conv_states->nb[1], kv_head*conv_states->nb[1]),
  7553. state_mask);
  7554. ssm_states = ggml_mul(ctx0,
  7555. ggml_view_2d(ctx0, ssm_states, ssm_states->ne[0], n_kv, ssm_states->nb[1], kv_head*ssm_states->nb[1]),
  7556. state_mask);
  7557. }
  7558. conv_states = ggml_reshape_3d(ctx0, conv_states, d_conv - 1, d_inner, n_kv);
  7559. ssm_states = ggml_reshape_3d(ctx0, ssm_states, d_state, d_inner, n_kv);
  7560. // norm
  7561. cur = llm_build_norm(ctx0, inpL, hparams,
  7562. model.layers[il].attn_norm, NULL,
  7563. LLM_NORM_RMS, cb, il);
  7564. cb(cur, "attn_norm", il);
  7565. // {n_embd, 2*d_inner} * {n_embd, n_tokens} => {2*d_inner, n_tokens}
  7566. struct ggml_tensor * xz = ggml_mul_mat(ctx0, model.layers[il].ssm_in, cur);
  7567. // split the above in two
  7568. // => {d_inner, n_tokens}
  7569. struct ggml_tensor * x = ggml_view_2d(ctx0, xz, d_inner, xz->ne[1], xz->nb[1], 0);
  7570. struct ggml_tensor * z = ggml_view_2d(ctx0, xz, d_inner, xz->ne[1], xz->nb[1], ggml_element_size(xz)*d_inner);
  7571. // conv
  7572. {
  7573. // Custom operator which is needed only to ease simultaneous sequence processing.
  7574. // For a single sequence, the equivalent is to concatenate the columns of conv_states and x,
  7575. // then make a self-overlapping view of that over d_conv columns at each stride in the 3rd dimension,
  7576. // then element-wise multiply that with the conv1d weigth,
  7577. // then sum the elements of each row,
  7578. // (the last two steps are a dot product over rows (also doable with mul_mat))
  7579. // then permute away the ne[0] dimension,
  7580. // and then you're left with the resulting x tensor.
  7581. // The new conv_states is the last (d_conv - 1) columns
  7582. // of the last 3rd dimensional "layer" of the self-overlapping view.
  7583. // For simultaneous sequences, it's more complicated.
  7584. struct ggml_tensor * x_conv = ggml_ssm_conv(ctx0, conv_states, x, model.layers[il].ssm_conv1d, state_seq);
  7585. // store last (d_conv - 1) columns of the conv_state part of x_conv back into the KV cache
  7586. ggml_build_forward_expand(gf,
  7587. ggml_cpy(ctx0,
  7588. 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)),
  7589. 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))));
  7590. // extract x from x_conv
  7591. x = ggml_view_2d(ctx0, x_conv, d_inner, n_tokens, d_inner*ggml_element_size(x_conv), 0);
  7592. // bias
  7593. x = ggml_add(ctx0, x, model.layers[il].ssm_conv1d_b);
  7594. x = ggml_silu(ctx0, x);
  7595. }
  7596. // ssm
  7597. {
  7598. // {d_inner, dt_rank + 2*d_state} * {d_inner, n_tokens} => {dt_rank + 2*d_state, n_tokens}
  7599. struct ggml_tensor * x_db = ggml_mul_mat(ctx0, model.layers[il].ssm_x, x);
  7600. // split
  7601. struct ggml_tensor * dt = ggml_view_2d(ctx0, x_db, dt_rank, n_tokens, x_db->nb[1], 0);
  7602. 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);
  7603. 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));
  7604. // {dt_rank, d_inner} * {dt_rank, n_tokens} => {d_inner, n_tokens}
  7605. dt = ggml_mul_mat(ctx0, model.layers[il].ssm_dt, dt);
  7606. dt = ggml_add(ctx0, dt, model.layers[il].ssm_dt_b);
  7607. // Custom operator to optimize the parallel associative scan
  7608. // as described in the Annex D of the Mamba paper.
  7609. // => {d_inner, n_tokens} and {d_state, d_inner, n_kv} combined,
  7610. // because only a single tensor can be returned.
  7611. struct ggml_tensor * y_ssm_states = ggml_ssm_scan(ctx0, ssm_states, x, dt, model.layers[il].ssm_a, B, C, state_seq);
  7612. // store last states (the second part of y_ssm_states)
  7613. ggml_build_forward_expand(gf,
  7614. ggml_cpy(ctx0,
  7615. ggml_view_1d(ctx0, y_ssm_states, d_state*d_inner*n_kv, d_inner*n_tokens*ggml_element_size(y_ssm_states)),
  7616. 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))));
  7617. struct ggml_tensor * y = ggml_view_2d(ctx0, y_ssm_states, d_inner, n_tokens, d_inner*ggml_element_size(y_ssm_states), 0);
  7618. if (il == n_layer - 1) {
  7619. // skip computing output for unused tokens
  7620. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7621. x = ggml_get_rows(ctx0, x, inp_out_ids);
  7622. y = ggml_get_rows(ctx0, y, inp_out_ids);
  7623. z = ggml_get_rows(ctx0, z, inp_out_ids);
  7624. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  7625. }
  7626. // {d_inner, n_tokens} * {d_inner} => {d_inner, n_tokens}
  7627. y = ggml_add(ctx0, y, ggml_mul(ctx0, x, model.layers[il].ssm_d));
  7628. y = ggml_mul(ctx0, y, ggml_silu(ctx0, z));
  7629. // {d_inner, n_embd} * {d_inner, n_tokens} => {n_embd, n_tokens}
  7630. cur = ggml_mul_mat(ctx0, model.layers[il].ssm_out, y);
  7631. }
  7632. // residual
  7633. cur = ggml_add(ctx0, cur, inpL);
  7634. cb(cur, "l_out", il);
  7635. // input for next layer
  7636. inpL = cur;
  7637. }
  7638. // final rmsnorm
  7639. cur = llm_build_norm(ctx0, inpL, hparams,
  7640. model.output_norm, NULL,
  7641. LLM_NORM_RMS, cb, -1);
  7642. cb(cur, "result_norm", -1);
  7643. // lm_head
  7644. cur = ggml_mul_mat(ctx0, model.output, cur);
  7645. cb(cur, "result_output", -1);
  7646. ggml_build_forward_expand(gf, cur);
  7647. return gf;
  7648. }
  7649. struct ggml_cgraph * build_command_r() {
  7650. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7651. const int64_t n_embd_head = hparams.n_embd_head_v;
  7652. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7653. const float f_logit_scale = hparams.f_logit_scale;
  7654. struct ggml_tensor * cur;
  7655. struct ggml_tensor * inpL;
  7656. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7657. // inp_pos - contains the positions
  7658. struct ggml_tensor * inp_pos = build_inp_pos();
  7659. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7660. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7661. for (int il = 0; il < n_layer; ++il) {
  7662. // norm
  7663. cur = llm_build_norm(ctx0, inpL, hparams,
  7664. model.layers[il].attn_norm, NULL,
  7665. LLM_NORM, cb, il);
  7666. cb(cur, "attn_norm", il);
  7667. struct ggml_tensor * ffn_inp = cur;
  7668. // self-attention
  7669. {
  7670. // compute Q and K and RoPE them
  7671. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  7672. cb(Qcur, "Qcur", il);
  7673. if (model.layers[il].bq) {
  7674. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  7675. cb(Qcur, "Qcur", il);
  7676. }
  7677. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  7678. cb(Kcur, "Kcur", il);
  7679. if (model.layers[il].bk) {
  7680. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  7681. cb(Kcur, "Kcur", il);
  7682. }
  7683. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  7684. cb(Vcur, "Vcur", il);
  7685. if (model.layers[il].bv) {
  7686. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  7687. cb(Vcur, "Vcur", il);
  7688. }
  7689. Qcur = ggml_rope_custom(
  7690. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  7691. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7692. ext_factor, attn_factor, beta_fast, beta_slow
  7693. );
  7694. cb(Qcur, "Qcur", il);
  7695. Kcur = ggml_rope_custom(
  7696. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  7697. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7698. ext_factor, attn_factor, beta_fast, beta_slow
  7699. );
  7700. cb(Kcur, "Kcur", il);
  7701. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  7702. model.layers[il].wo, model.layers[il].bo,
  7703. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7704. }
  7705. if (il == n_layer - 1) {
  7706. // skip computing output for unused tokens
  7707. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7708. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7709. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  7710. ffn_inp = ggml_get_rows(ctx0, ffn_inp, inp_out_ids);
  7711. }
  7712. struct ggml_tensor * attn_out = cur;
  7713. // feed-forward network
  7714. {
  7715. cur = llm_build_ffn(ctx0, ffn_inp,
  7716. model.layers[il].ffn_up, NULL,
  7717. model.layers[il].ffn_gate, NULL,
  7718. model.layers[il].ffn_down, NULL,
  7719. NULL,
  7720. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  7721. cb(cur, "ffn_out", il);
  7722. }
  7723. // add together residual + FFN + self-attention
  7724. cur = ggml_add(ctx0, cur, inpL);
  7725. cur = ggml_add(ctx0, cur, attn_out);
  7726. cb(cur, "l_out", il);
  7727. // input for next layer
  7728. inpL = cur;
  7729. }
  7730. cur = inpL;
  7731. cur = llm_build_norm(ctx0, cur, hparams,
  7732. model.output_norm, NULL,
  7733. LLM_NORM, cb, -1);
  7734. cb(cur, "result_norm", -1);
  7735. // lm_head
  7736. cur = ggml_mul_mat(ctx0, model.output, cur);
  7737. if (f_logit_scale) {
  7738. cur = ggml_scale(ctx0, cur, f_logit_scale);
  7739. }
  7740. cb(cur, "result_output", -1);
  7741. ggml_build_forward_expand(gf, cur);
  7742. return gf;
  7743. }
  7744. };
  7745. static struct ggml_cgraph * llama_build_graph_defrag(llama_context & lctx, const std::vector<uint32_t> & ids) {
  7746. llama_batch dummy;
  7747. dummy.n_tokens = 0;
  7748. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  7749. struct llm_build_context llm(lctx, dummy, cb, false);
  7750. llm.init();
  7751. struct ggml_cgraph * result = llm.build_defrag(ids);
  7752. llm.free();
  7753. return result;
  7754. }
  7755. static struct ggml_cgraph * llama_build_graph_k_shift(llama_context & lctx) {
  7756. llama_batch dummy;
  7757. dummy.n_tokens = 0;
  7758. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  7759. struct llm_build_context llm(lctx, dummy, cb, false);
  7760. llm.init();
  7761. struct ggml_cgraph * result = llm.build_k_shift();
  7762. llm.free();
  7763. return result;
  7764. }
  7765. static struct ggml_cgraph * llama_build_graph_s_copy(llama_context & lctx) {
  7766. llama_batch dummy;
  7767. dummy.n_tokens = 0;
  7768. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  7769. struct llm_build_context llm(lctx, dummy, cb, false);
  7770. llm.init();
  7771. struct ggml_cgraph * result = llm.build_s_copy();
  7772. llm.free();
  7773. return result;
  7774. }
  7775. static struct ggml_cgraph * llama_build_graph(
  7776. llama_context & lctx,
  7777. const llama_batch & batch,
  7778. bool worst_case) {
  7779. const auto & model = lctx.model;
  7780. // this callback allows us to apply custom logic to each tensor (e.g. ggml-alloc, offloading, etc.)
  7781. llm_build_cb cb = [&](struct ggml_tensor * cur, const char * name, int il) {
  7782. if (il >= 0) {
  7783. ggml_format_name(cur, "%s-%d", name, il);
  7784. } else {
  7785. ggml_set_name(cur, name);
  7786. }
  7787. if (!lctx.cparams.offload_kqv) {
  7788. if (strcmp(name, "kqv_merged_cont") == 0) {
  7789. // all nodes between the KV store and the attention output are run on the CPU
  7790. ggml_backend_sched_set_tensor_backend(lctx.sched, cur, lctx.backend_cpu);
  7791. }
  7792. }
  7793. // norm may be automatically assigned to the backend of the previous layer, increasing data transfer between backends
  7794. // FIXME: fix in ggml_backend_sched
  7795. const bool full_offload = lctx.model.n_gpu_layers > (int)lctx.model.hparams.n_layer;
  7796. if (batch.n_tokens < 32 || full_offload) {
  7797. if (il != -1 && strcmp(name, "norm") == 0) {
  7798. for (auto * backend : lctx.backends) {
  7799. if (ggml_backend_buft_supports_backend(lctx.model.buft_layer[il].buft, backend)) {
  7800. ggml_backend_sched_set_tensor_backend(lctx.sched, cur, backend);
  7801. break;
  7802. }
  7803. }
  7804. }
  7805. }
  7806. };
  7807. struct ggml_cgraph * result = NULL;
  7808. struct llm_build_context llm(lctx, batch, cb, worst_case);
  7809. llm.init();
  7810. switch (model.arch) {
  7811. case LLM_ARCH_LLAMA:
  7812. {
  7813. result = llm.build_llama();
  7814. } break;
  7815. case LLM_ARCH_BAICHUAN:
  7816. {
  7817. result = llm.build_baichuan();
  7818. } break;
  7819. case LLM_ARCH_FALCON:
  7820. {
  7821. result = llm.build_falcon();
  7822. } break;
  7823. case LLM_ARCH_GROK:
  7824. {
  7825. result = llm.build_grok();
  7826. } break;
  7827. case LLM_ARCH_STARCODER:
  7828. {
  7829. result = llm.build_starcoder();
  7830. } break;
  7831. case LLM_ARCH_PERSIMMON:
  7832. {
  7833. result = llm.build_persimmon();
  7834. } break;
  7835. case LLM_ARCH_REFACT:
  7836. {
  7837. result = llm.build_refact();
  7838. } break;
  7839. case LLM_ARCH_BERT:
  7840. case LLM_ARCH_NOMIC_BERT:
  7841. {
  7842. result = llm.build_bert();
  7843. } break;
  7844. case LLM_ARCH_BLOOM:
  7845. {
  7846. result = llm.build_bloom();
  7847. } break;
  7848. case LLM_ARCH_MPT:
  7849. {
  7850. result = llm.build_mpt();
  7851. } break;
  7852. case LLM_ARCH_STABLELM:
  7853. {
  7854. result = llm.build_stablelm();
  7855. } break;
  7856. case LLM_ARCH_QWEN:
  7857. {
  7858. result = llm.build_qwen();
  7859. } break;
  7860. case LLM_ARCH_QWEN2:
  7861. {
  7862. result = llm.build_qwen2();
  7863. } break;
  7864. case LLM_ARCH_PHI2:
  7865. {
  7866. result = llm.build_phi2();
  7867. } break;
  7868. case LLM_ARCH_PLAMO:
  7869. {
  7870. result = llm.build_plamo();
  7871. } break;
  7872. case LLM_ARCH_GPT2:
  7873. {
  7874. result = llm.build_gpt2();
  7875. } break;
  7876. case LLM_ARCH_CODESHELL:
  7877. {
  7878. result = llm.build_codeshell();
  7879. } break;
  7880. case LLM_ARCH_ORION:
  7881. {
  7882. result = llm.build_orion();
  7883. } break;
  7884. case LLM_ARCH_INTERNLM2:
  7885. {
  7886. result = llm.build_internlm2();
  7887. } break;
  7888. case LLM_ARCH_MINICPM:
  7889. {
  7890. result = llm.build_minicpm();
  7891. } break;
  7892. case LLM_ARCH_GEMMA:
  7893. {
  7894. result = llm.build_gemma();
  7895. } break;
  7896. case LLM_ARCH_STARCODER2:
  7897. {
  7898. result = llm.build_starcoder2();
  7899. } break;
  7900. case LLM_ARCH_MAMBA:
  7901. {
  7902. result = llm.build_mamba();
  7903. } break;
  7904. case LLM_ARCH_XVERSE:
  7905. {
  7906. result = llm.build_xverse();
  7907. } break;
  7908. case LLM_ARCH_COMMAND_R:
  7909. {
  7910. result = llm.build_command_r();
  7911. } break;
  7912. default:
  7913. GGML_ASSERT(false);
  7914. }
  7915. llm.free();
  7916. return result;
  7917. }
  7918. static void llama_set_k_shift(llama_context & lctx) {
  7919. const int64_t kv_size = lctx.kv_self.size;
  7920. assert(ggml_backend_buffer_is_host(lctx.inp_K_shift->buffer));
  7921. int32_t * data = (int32_t *) lctx.inp_K_shift->data;
  7922. for (int i = 0; i < kv_size; ++i) {
  7923. data[i] = lctx.kv_self.cells[i].delta;
  7924. }
  7925. }
  7926. static void llama_set_s_copy(llama_context & lctx) {
  7927. const int64_t kv_size = lctx.kv_self.size;
  7928. assert(ggml_backend_buffer_is_host(lctx.inp_s_copy->buffer));
  7929. int32_t * data = (int32_t *) lctx.inp_s_copy->data;
  7930. for (int i = 0; i < kv_size; ++i) {
  7931. data[i] = lctx.kv_self.cells[i].src;
  7932. }
  7933. }
  7934. static void llama_set_inputs(llama_context & lctx, const llama_batch & batch) {
  7935. //
  7936. // set input data
  7937. //
  7938. const auto & hparams = lctx.model.hparams;
  7939. const auto & cparams = lctx.cparams;
  7940. const auto & kv_self = lctx.kv_self;
  7941. if (batch.token) {
  7942. const int64_t n_tokens = batch.n_tokens;
  7943. ggml_backend_tensor_set(lctx.inp_tokens, batch.token, 0, n_tokens*ggml_element_size(lctx.inp_tokens));
  7944. }
  7945. if (batch.embd) {
  7946. const int64_t n_embd = hparams.n_embd;
  7947. const int64_t n_tokens = batch.n_tokens;
  7948. ggml_backend_tensor_set(lctx.inp_embd, batch.embd, 0, n_tokens*n_embd*ggml_element_size(lctx.inp_embd));
  7949. }
  7950. if (batch.pos && lctx.inp_pos) {
  7951. const int64_t n_tokens = batch.n_tokens;
  7952. ggml_backend_tensor_set(lctx.inp_pos, batch.pos, 0, n_tokens*ggml_element_size(lctx.inp_pos));
  7953. }
  7954. if (hparams.causal_attn || cparams.pooling_type == LLAMA_POOLING_TYPE_NONE) {
  7955. GGML_ASSERT(lctx.inp_out_ids && "every model that can must skip unused outputs");
  7956. const int64_t n_tokens = batch.n_tokens;
  7957. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_out_ids->buffer));
  7958. int32_t * data = (int32_t *) lctx.inp_out_ids->data;
  7959. if (lctx.n_outputs == n_tokens) {
  7960. for (int i = 0; i < n_tokens; ++i) {
  7961. data[i] = i;
  7962. }
  7963. } else if (batch.logits) {
  7964. int32_t n_outputs = 0;
  7965. for (int i = 0; i < n_tokens; ++i) {
  7966. if (batch.logits[i]) {
  7967. data[n_outputs++] = i;
  7968. }
  7969. }
  7970. // the graph needs to have been passed the correct number of outputs
  7971. GGML_ASSERT(lctx.n_outputs == n_outputs);
  7972. } else if (lctx.n_outputs == 1) {
  7973. // only keep last output
  7974. data[0] = n_tokens - 1;
  7975. } else {
  7976. GGML_ASSERT(lctx.n_outputs == 0);
  7977. }
  7978. }
  7979. GGML_ASSERT(
  7980. // (!a || b) is a logical implication (a -> b)
  7981. // !hparams.causal_attn -> !cparams.causal_attn
  7982. (hparams.causal_attn || !cparams.causal_attn) &&
  7983. "causal attention with embedding models is not supported"
  7984. );
  7985. if (lctx.inp_KQ_mask) {
  7986. // NOTE: hparams.causal_attn indicates the model is capable of generation and uses the kv cache.
  7987. if (cparams.causal_attn) {
  7988. const int64_t n_kv = kv_self.n;
  7989. const int64_t n_tokens = batch.n_tokens;
  7990. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  7991. float * data = (float *) lctx.inp_KQ_mask->data;
  7992. // For causal attention, use only the previous KV cells
  7993. // of the correct sequence for each token of the batch.
  7994. // It's assumed that if a token in the batch has multiple sequences, they are equivalent.
  7995. for (int h = 0; h < 1; ++h) {
  7996. for (int j = 0; j < n_tokens; ++j) {
  7997. const llama_pos pos = batch.pos[j];
  7998. const llama_seq_id seq_id = batch.seq_id[j][0];
  7999. for (int i = 0; i < n_kv; ++i) {
  8000. float f;
  8001. if (!lctx.kv_self.cells[i].has_seq_id(seq_id) || lctx.kv_self.cells[i].pos > pos) {
  8002. f = -INFINITY;
  8003. } else {
  8004. f = 0.0f;
  8005. }
  8006. data[h*(n_kv*n_tokens) + j*n_kv + i] = f;
  8007. }
  8008. }
  8009. }
  8010. } else {
  8011. // when using kv cache, the mask needs to match the kv cache size
  8012. const int64_t n_tokens = batch.n_tokens;
  8013. const int64_t n_stride = hparams.causal_attn ? kv_self.n : n_tokens;
  8014. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  8015. float * data = (float *) lctx.inp_KQ_mask->data;
  8016. for (int h = 0; h < 1; ++h) {
  8017. for (int j = 0; j < n_tokens; ++j) {
  8018. const llama_seq_id seq_id = batch.seq_id[j][0];
  8019. for (int i = 0; i < n_tokens; ++i) {
  8020. float f = -INFINITY;
  8021. for (int s = 0; s < batch.n_seq_id[i]; ++s) {
  8022. if (batch.seq_id[i][s] == seq_id) {
  8023. f = 0.0f;
  8024. break;
  8025. }
  8026. }
  8027. data[h*(n_tokens*n_tokens) + j*n_stride + i] = f;
  8028. }
  8029. for (int i = n_tokens; i < n_stride; ++i) {
  8030. data[h*(n_tokens*n_tokens) + j*n_stride + i] = -INFINITY;
  8031. }
  8032. }
  8033. }
  8034. }
  8035. }
  8036. if (hparams.need_kq_pos) {
  8037. const int64_t n_kv = kv_self.n;
  8038. GGML_ASSERT(lctx.inp_KQ_pos);
  8039. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_pos->buffer));
  8040. float * data = (float *) lctx.inp_KQ_pos->data;
  8041. for (int i = 0; i < n_kv; ++i) {
  8042. data[i] = float(lctx.kv_self.cells[i].pos);
  8043. }
  8044. }
  8045. if (cparams.pooling_type == LLAMA_POOLING_TYPE_MEAN) {
  8046. const int64_t n_tokens = batch.n_tokens;
  8047. GGML_ASSERT(lctx.inp_mean);
  8048. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_mean->buffer));
  8049. float * data = (float *) lctx.inp_mean->data;
  8050. memset(lctx.inp_mean->data, 0, n_tokens * n_tokens * ggml_element_size(lctx.inp_mean));
  8051. std::vector<uint64_t> sum(n_tokens, 0);
  8052. for (int i = 0; i < n_tokens; ++i) {
  8053. const llama_seq_id seq_id = batch.seq_id[i][0];
  8054. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == MEAN");
  8055. sum[seq_id] += 1;
  8056. }
  8057. std::vector<float> div(n_tokens, 0.0f);
  8058. for (int i = 0; i < n_tokens; ++i) {
  8059. const uint64_t s = sum[i];
  8060. if (s > 0) {
  8061. div[i] = 1.0f/float(s);
  8062. }
  8063. }
  8064. for (int i = 0; i < n_tokens; ++i) {
  8065. const llama_seq_id seq_id = batch.seq_id[i][0];
  8066. data[seq_id*n_tokens + i] = div[seq_id];
  8067. }
  8068. }
  8069. if (cparams.pooling_type == LLAMA_POOLING_TYPE_CLS) {
  8070. const int64_t n_tokens = batch.n_tokens;
  8071. GGML_ASSERT(lctx.inp_cls);
  8072. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_cls->buffer));
  8073. uint32_t * data = (uint32_t *) lctx.inp_cls->data;
  8074. memset(lctx.inp_cls->data, 0, n_tokens * ggml_element_size(lctx.inp_cls));
  8075. for (int i = 0; i < n_tokens; ++i) {
  8076. const llama_seq_id seq_id = batch.seq_id[i][0];
  8077. const llama_pos pos = batch.pos[i];
  8078. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == CLS");
  8079. if (pos == 0) {
  8080. data[seq_id] = i;
  8081. }
  8082. }
  8083. }
  8084. if (kv_self.recurrent) {
  8085. const int64_t n_kv = kv_self.n;
  8086. if (lctx.inp_s_mask) {
  8087. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_s_mask->buffer));
  8088. float * data = (float *) lctx.inp_s_mask->data;
  8089. // states which are not affected by the current batch are left untouched
  8090. for (int i = 0; i < n_kv; ++i) {
  8091. llama_seq_id seq_id = i + lctx.kv_self.head;
  8092. llama_kv_cell & kv_cell = lctx.kv_self.cells[seq_id];
  8093. bool has_self_seq = kv_cell.has_seq_id(seq_id);
  8094. data[i] = (float) has_self_seq;
  8095. // ensure current sequences will be kept
  8096. if (!has_self_seq && kv_cell.pos >= 0) {
  8097. kv_cell.seq_id.insert(seq_id);
  8098. }
  8099. }
  8100. }
  8101. // For Mamba (and other recurrent architectures),
  8102. // update the correct state(s)/sequence(s) for each token of the batch.
  8103. // Like with the KQ_mask, if a token in the batch has multiple sequences,
  8104. // they are assumed to be equivalent (not here, but in ggml_ssm_scan and ggml_ssm_conv).
  8105. if (lctx.inp_s_seq) {
  8106. const int64_t n_tokens = batch.n_tokens;
  8107. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_s_seq->buffer));
  8108. int32_t * data = (int32_t *) lctx.inp_s_seq->data;
  8109. for (int j = 0; j < n_tokens; ++j) {
  8110. const int32_t n_seq = batch.n_seq_id[j];
  8111. GGML_ASSERT(0 < n_seq); // a token should be part of at least 1 sequence
  8112. for (int i = 0; i < n_kv; ++i) {
  8113. if (i < n_seq) {
  8114. // for this type of model, the head is the minimum seq_id of the batch
  8115. data[j*n_kv + i] = batch.seq_id[j][i] - kv_self.head;
  8116. } else {
  8117. data[j*n_kv + i] = -1;
  8118. }
  8119. }
  8120. }
  8121. }
  8122. }
  8123. }
  8124. // Make sure enough space is available for outputs.
  8125. // Returns max number of outputs for which space was reserved.
  8126. static size_t llama_output_reserve(llama_context & lctx, size_t n_outputs) {
  8127. const auto & cparams = lctx.cparams;
  8128. const auto & hparams = lctx.model.hparams;
  8129. const size_t n_outputs_max = std::max(n_outputs, (size_t) cparams.n_seq_max);
  8130. const auto n_batch = cparams.n_batch;
  8131. const auto n_vocab = hparams.n_vocab;
  8132. const auto n_embd = hparams.n_embd;
  8133. // TODO: use a per-batch flag for logits presence instead
  8134. const bool has_logits = cparams.causal_attn;
  8135. const bool has_embd = cparams.embeddings && (hparams.causal_attn || cparams.pooling_type == LLAMA_POOLING_TYPE_NONE);
  8136. const size_t logits_size = has_logits ? n_vocab*n_outputs_max : 0;
  8137. const size_t embd_size = has_embd ? n_embd*n_outputs_max : 0;
  8138. if (lctx.output_ids.empty()) {
  8139. // init, never resized afterwards
  8140. lctx.output_ids.resize(n_batch);
  8141. }
  8142. const size_t prev_size = lctx.buf_output ? ggml_backend_buffer_get_size(lctx.buf_output) : 0;
  8143. const size_t new_size = (logits_size + embd_size) * sizeof(float);
  8144. // alloc only when more than the current capacity is required
  8145. // TODO: also consider shrinking the buffer
  8146. if (!lctx.buf_output || prev_size < new_size) {
  8147. if (lctx.buf_output) {
  8148. #ifndef NDEBUG
  8149. // This doesn't happen often, but may be annoying in some cases (like the HellaSwag benchmark)
  8150. 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);
  8151. #endif
  8152. ggml_backend_buffer_free(lctx.buf_output);
  8153. lctx.buf_output = nullptr;
  8154. lctx.logits = nullptr;
  8155. lctx.embd = nullptr;
  8156. }
  8157. lctx.buf_output = ggml_backend_buft_alloc_buffer(llama_default_buffer_type_cpu(true), new_size);
  8158. if (lctx.buf_output == nullptr) {
  8159. LLAMA_LOG_ERROR("%s: failed to allocate output buffer of size %.2f MiB\n", __func__, new_size / (1024.0 * 1024.0));
  8160. return 0;
  8161. }
  8162. }
  8163. float * output_base = (float *) ggml_backend_buffer_get_base(lctx.buf_output);
  8164. lctx.logits = has_logits ? output_base : nullptr;
  8165. lctx.embd = has_embd ? output_base + logits_size : nullptr;
  8166. lctx.output_size = n_outputs_max;
  8167. lctx.logits_size = logits_size;
  8168. lctx.embd_size = embd_size;
  8169. // set all ids as invalid (negative)
  8170. std::fill(lctx.output_ids.begin(), lctx.output_ids.end(), -1);
  8171. ggml_backend_buffer_clear(lctx.buf_output, 0);
  8172. lctx.n_outputs = 0;
  8173. return n_outputs_max;
  8174. }
  8175. static void llama_graph_compute(
  8176. llama_context & lctx,
  8177. ggml_cgraph * gf,
  8178. int n_threads) {
  8179. #ifdef GGML_USE_MPI
  8180. const int64_t n_layer = lctx.model.hparams.n_layer;
  8181. ggml_mpi_graph_compute_pre(lctx.ctx_mpi, gf, n_layer);
  8182. #endif
  8183. #ifdef GGML_USE_METAL
  8184. if (ggml_backend_is_metal(lctx.backend_metal)) {
  8185. ggml_backend_metal_set_n_cb(lctx.backend_metal, n_threads);
  8186. }
  8187. #endif
  8188. if (lctx.backend_cpu != nullptr) {
  8189. ggml_backend_cpu_set_n_threads(lctx.backend_cpu, n_threads);
  8190. ggml_backend_cpu_set_abort_callback(lctx.backend_cpu, lctx.abort_callback, lctx.abort_callback_data);
  8191. }
  8192. ggml_backend_sched_graph_compute_async(lctx.sched, gf);
  8193. // fprintf(stderr, "splits: %d\n", ggml_backend_sched_get_n_splits(lctx.sched));
  8194. #ifdef GGML_USE_MPI
  8195. ggml_mpi_graph_compute_post(lctx.ctx_mpi, gf, n_layer);
  8196. #endif
  8197. }
  8198. // decode a batch of tokens by evaluating the transformer
  8199. //
  8200. // - lctx: llama context
  8201. // - batch: batch to evaluate
  8202. //
  8203. // return 0 on success
  8204. // return positive int on warning
  8205. // return negative int on error
  8206. //
  8207. static int llama_decode_internal(
  8208. llama_context & lctx,
  8209. llama_batch batch_all) { // TODO: rename back to batch
  8210. const uint32_t n_tokens_all = batch_all.n_tokens;
  8211. if (n_tokens_all == 0) {
  8212. LLAMA_LOG_ERROR("%s: n_tokens == 0", __func__);
  8213. return -1;
  8214. }
  8215. const auto & model = lctx.model;
  8216. const auto & hparams = model.hparams;
  8217. const auto & cparams = lctx.cparams;
  8218. GGML_ASSERT((!batch_all.token && batch_all.embd) || (batch_all.token && !batch_all.embd)); // NOLINT
  8219. GGML_ASSERT(n_tokens_all <= cparams.n_batch);
  8220. GGML_ASSERT((cparams.causal_attn || cparams.n_ubatch >= n_tokens_all) && "non-causal attention requires n_ubatch >= n_tokens");
  8221. if (lctx.t_compute_start_us == 0) {
  8222. lctx.t_compute_start_us = ggml_time_us();
  8223. }
  8224. lctx.n_queued_tokens += n_tokens_all;
  8225. #ifdef GGML_USE_MPI
  8226. // TODO: needs fix after #3228
  8227. GGML_ASSERT(false && "not implemented");
  8228. //ggml_mpi_eval_init(lctx.ctx_mpi, &n_tokens, &n_past, &n_threads);
  8229. #endif
  8230. auto & kv_self = lctx.kv_self;
  8231. const int64_t n_embd = hparams.n_embd;
  8232. const int64_t n_vocab = hparams.n_vocab;
  8233. uint32_t n_outputs = 0;
  8234. uint32_t n_outputs_prev = 0;
  8235. const auto n_ubatch = cparams.n_ubatch;
  8236. std::vector<llama_pos> pos;
  8237. std::vector<int32_t> n_seq_id;
  8238. std::vector<llama_seq_id *> seq_id_arr;
  8239. std::vector<std::vector<llama_seq_id>> seq_id;
  8240. // count outputs
  8241. if (batch_all.logits) {
  8242. for (uint32_t i = 0; i < n_tokens_all; ++i) {
  8243. n_outputs += batch_all.logits[i] != 0;
  8244. }
  8245. } else if (lctx.logits_all || (cparams.embeddings && cparams.pooling_type != LLAMA_POOLING_TYPE_NONE)) {
  8246. n_outputs = n_tokens_all;
  8247. } else {
  8248. // keep last output only
  8249. n_outputs = 1;
  8250. }
  8251. // reserve output buffer
  8252. if (llama_output_reserve(lctx, n_outputs) < n_outputs) {
  8253. LLAMA_LOG_ERROR("%s: could not reserve space for batch with %u outputs\n", __func__, n_outputs);
  8254. return -2;
  8255. };
  8256. // set output mappings
  8257. if (batch_all.logits) {
  8258. int32_t i_logits = 0;
  8259. for (uint32_t i = 0; i < n_tokens_all; ++i) {
  8260. if (batch_all.logits[i]) {
  8261. lctx.output_ids[i] = i_logits++;
  8262. }
  8263. }
  8264. } else {
  8265. for (uint32_t i = 0; i < n_outputs; ++i) {
  8266. lctx.output_ids[i] = i;
  8267. }
  8268. }
  8269. for (uint32_t cur_token = 0; cur_token < n_tokens_all; cur_token += n_ubatch) {
  8270. const uint32_t n_tokens = std::min(n_ubatch, n_tokens_all - cur_token);
  8271. llama_batch u_batch = {
  8272. /* .n_tokens = */ (int32_t) n_tokens,
  8273. /* .token = */ batch_all.token ? batch_all.token + cur_token : nullptr,
  8274. /* .embd = */ batch_all.embd ? batch_all.embd + cur_token*n_embd : nullptr,
  8275. /* .pos = */ batch_all.pos ? batch_all.pos + cur_token : nullptr,
  8276. /* .n_seq_id = */ batch_all.n_seq_id ? batch_all.n_seq_id + cur_token : nullptr,
  8277. /* .seq_id = */ batch_all.seq_id ? batch_all.seq_id + cur_token : nullptr,
  8278. /* .logits = */ batch_all.logits ? batch_all.logits + cur_token : nullptr,
  8279. /* .all_pos_0 = */ batch_all.all_pos_0 + (llama_pos) cur_token*batch_all.all_pos_1,
  8280. /* .all_pos_1 = */ batch_all.all_pos_1,
  8281. /* .all_seq_id = */ batch_all.all_seq_id,
  8282. };
  8283. // count the outputs in this u_batch
  8284. {
  8285. int32_t n_outputs_new = 0;
  8286. if (u_batch.logits) {
  8287. for (uint32_t i = 0; i < n_tokens; i++) {
  8288. n_outputs_new += u_batch.logits[i] != 0;
  8289. }
  8290. } else if (n_outputs == n_tokens_all) {
  8291. n_outputs_new = n_tokens;
  8292. } else {
  8293. // keep last output only
  8294. if (cur_token + n_tokens >= n_tokens_all) {
  8295. n_outputs_new = 1;
  8296. }
  8297. }
  8298. // needs to happen before the graph is built
  8299. lctx.n_outputs = n_outputs_new;
  8300. }
  8301. int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  8302. GGML_ASSERT(n_threads > 0);
  8303. // helpers for smoother batch API transition
  8304. // after deprecating the llama_eval calls, these will be removed
  8305. if (u_batch.pos == nullptr) {
  8306. pos.resize(n_tokens);
  8307. for (uint32_t i = 0; i < n_tokens; i++) {
  8308. pos[i] = u_batch.all_pos_0 + i*u_batch.all_pos_1;
  8309. }
  8310. u_batch.pos = pos.data();
  8311. }
  8312. if (u_batch.seq_id == nullptr) {
  8313. n_seq_id.resize(n_tokens);
  8314. seq_id.resize(n_tokens);
  8315. seq_id_arr.resize(n_tokens);
  8316. for (uint32_t i = 0; i < n_tokens; i++) {
  8317. n_seq_id[i] = 1;
  8318. seq_id[i].resize(1);
  8319. seq_id[i][0] = u_batch.all_seq_id;
  8320. seq_id_arr[i] = seq_id[i].data();
  8321. }
  8322. u_batch.n_seq_id = n_seq_id.data();
  8323. u_batch.seq_id = seq_id_arr.data();
  8324. }
  8325. // non-causal masks do not use the KV cache
  8326. if (hparams.causal_attn) {
  8327. llama_kv_cache_update(&lctx);
  8328. // if we have enough unused cells before the current head ->
  8329. // better to start searching from the beginning of the cache, hoping to fill it
  8330. if (kv_self.head > kv_self.used + 2*n_tokens) {
  8331. kv_self.head = 0;
  8332. }
  8333. if (!llama_kv_cache_find_slot(kv_self, u_batch)) {
  8334. return 1;
  8335. }
  8336. if (!kv_self.recurrent) {
  8337. // a heuristic, to avoid attending the full cache if it is not yet utilized
  8338. // after enough generations, the benefit from this heuristic disappears
  8339. // if we start defragmenting the cache, the benefit from this will be more important
  8340. kv_self.n = std::min(kv_self.size, std::max(32u, GGML_PAD(llama_kv_cache_cell_max(kv_self), 32)));
  8341. //kv_self.n = llama_kv_cache_cell_max(kv_self);
  8342. }
  8343. }
  8344. //printf("kv_self.n = %5d, kv_self.used = %5d, kv_self.head = %5d\n", kv_self.n, kv_self.used, kv_self.head);
  8345. ggml_backend_sched_reset(lctx.sched);
  8346. ggml_backend_sched_set_eval_callback(lctx.sched, lctx.cparams.cb_eval, lctx.cparams.cb_eval_user_data);
  8347. ggml_cgraph * gf = llama_build_graph(lctx, u_batch, false);
  8348. // the output is always the last tensor in the graph
  8349. struct ggml_tensor * res = gf->nodes[gf->n_nodes - 1];
  8350. struct ggml_tensor * embd = gf->nodes[gf->n_nodes - 2];
  8351. if (lctx.n_outputs == 0) {
  8352. // no output
  8353. res = nullptr;
  8354. embd = nullptr;
  8355. } else if (!hparams.causal_attn) {
  8356. res = nullptr; // do not extract logits for embedding models such as BERT
  8357. // token or sequence embeddings
  8358. embd = gf->nodes[gf->n_nodes - 1];
  8359. GGML_ASSERT(strcmp(embd->name, "result_embd") == 0 || strcmp(embd->name, "result_embd_pooled") == 0);
  8360. } else if (cparams.embeddings) {
  8361. // the embeddings could be in the second to last tensor, or any of the previous tensors
  8362. int i_embd = gf->n_nodes - 2;
  8363. for (int i = 3; strcmp(embd->name, "result_norm") != 0; ++i) {
  8364. i_embd = gf->n_nodes - i;
  8365. if (i_embd < 0) { break; }
  8366. embd = gf->nodes[i_embd];
  8367. }
  8368. GGML_ASSERT(i_embd >= 0 && "missing result_norm tensor");
  8369. // TODO: use a per-batch flag to know when to skip logits while keeping embeddings
  8370. if (!cparams.causal_attn) {
  8371. res = nullptr; // do not extract logits when not needed
  8372. // skip computing logits
  8373. // TODO: is this safe?
  8374. gf->n_nodes = i_embd + 1;
  8375. }
  8376. } else {
  8377. embd = nullptr; // do not extract embeddings when not needed
  8378. GGML_ASSERT(strcmp(res->name, "result_output") == 0 && "missing result_output tensor");
  8379. }
  8380. // 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);
  8381. // for big prompts, if BLAS is enabled, it is better to use only one thread
  8382. // otherwise, the threads are spin-lock waiting for the BLAS calls and are degrading the performance
  8383. // TODO: this is mostly important for Apple Silicon where CBLAS is still performing very well
  8384. // we still need some threads to process all non-mul_mat ops, but not too much to avoid interfering
  8385. // with the BLAS calls. need a better solution
  8386. // MoE Special Case: This logic applies when hparams.n_expert == 0, i.e. the model is NOT an MoE model. When an MoE is
  8387. // being processed then Accelerate/BLAS will not be involved, so capping would limit performance.
  8388. if (n_tokens >= 32 && hparams.n_expert == 0 && ggml_cpu_has_blas() && !ggml_cpu_has_gpublas()) {
  8389. n_threads = std::min(4, n_threads);
  8390. }
  8391. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  8392. llama_set_inputs(lctx, u_batch);
  8393. llama_graph_compute(lctx, gf, n_threads);
  8394. // update the kv ring buffer
  8395. {
  8396. kv_self.head += n_tokens;
  8397. // Ensure kv cache head points to a valid index.
  8398. if (kv_self.head >= kv_self.size) {
  8399. kv_self.head = 0;
  8400. }
  8401. }
  8402. #ifdef GGML_PERF
  8403. // print timing information per ggml operation (for debugging purposes)
  8404. // requires GGML_PERF to be defined
  8405. ggml_graph_print(gf);
  8406. #endif
  8407. // plot the computation graph in dot format (for debugging purposes)
  8408. //if (n_past%100 == 0) {
  8409. // ggml_graph_dump_dot(gf, NULL, "llama.dot");
  8410. //}
  8411. // extract logits
  8412. if (res) {
  8413. ggml_backend_t backend_res = ggml_backend_sched_get_tensor_backend(lctx.sched, res);
  8414. GGML_ASSERT(backend_res != nullptr);
  8415. GGML_ASSERT(lctx.logits != nullptr);
  8416. float * logits_out = lctx.logits + n_outputs_prev*n_vocab;
  8417. const int32_t n_outputs_new = lctx.n_outputs;
  8418. if (n_outputs_new) {
  8419. GGML_ASSERT( n_outputs_prev + n_outputs_new <= n_outputs);
  8420. GGML_ASSERT((n_outputs_prev + n_outputs_new)*n_vocab <= (int64_t) lctx.logits_size);
  8421. ggml_backend_tensor_get_async(backend_res, res, logits_out, 0, n_outputs_new*n_vocab*sizeof(float));
  8422. }
  8423. }
  8424. // extract embeddings
  8425. if (embd) {
  8426. ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend(lctx.sched, embd);
  8427. GGML_ASSERT(backend_embd != nullptr);
  8428. switch (cparams.pooling_type) {
  8429. case LLAMA_POOLING_TYPE_NONE:
  8430. {
  8431. // extract token embeddings
  8432. GGML_ASSERT(lctx.embd != nullptr);
  8433. float * embd_out = lctx.embd + n_outputs_prev*n_embd;
  8434. const int32_t n_outputs_new = lctx.n_outputs;
  8435. if (n_outputs_new) {
  8436. GGML_ASSERT( n_outputs_prev + n_outputs_new <= n_outputs);
  8437. GGML_ASSERT((n_outputs_prev + n_outputs_new)*n_embd <= (int64_t) lctx.embd_size);
  8438. ggml_backend_tensor_get_async(backend_embd, embd, embd_out, 0, n_outputs_new*n_embd*sizeof(float));
  8439. }
  8440. } break;
  8441. case LLAMA_POOLING_TYPE_CLS:
  8442. case LLAMA_POOLING_TYPE_MEAN:
  8443. {
  8444. GGML_ASSERT(strcmp(embd->name, "result_embd_pooled") == 0);
  8445. // extract sequence embeddings
  8446. auto & embd_seq_out = lctx.embd_seq;
  8447. embd_seq_out.clear();
  8448. for (uint32_t i = 0; i < n_tokens; i++) {
  8449. const llama_seq_id seq_id = u_batch.seq_id[i][0];
  8450. if (embd_seq_out.find(seq_id) != embd_seq_out.end()) {
  8451. continue;
  8452. }
  8453. embd_seq_out[seq_id].resize(n_embd);
  8454. ggml_backend_tensor_get_async(backend_embd, embd, embd_seq_out[seq_id].data(), (n_embd*seq_id)*sizeof(float), n_embd*sizeof(float));
  8455. }
  8456. } break;
  8457. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  8458. {
  8459. GGML_ASSERT(false && "unknown pooling type");
  8460. } break;
  8461. }
  8462. }
  8463. n_outputs_prev += lctx.n_outputs;
  8464. }
  8465. // wait for the computation to finish (automatically done when obtaining the model output)
  8466. //llama_synchronize(&lctx);
  8467. // decide if we need to defrag the kv cache
  8468. if (cparams.causal_attn && cparams.defrag_thold >= 0.0f) {
  8469. const float fragmentation = kv_self.n >= 128 ? 1.0f - float(kv_self.used)/float(kv_self.n) : 0.0f;
  8470. // queue defragmentation for next llama_kv_cache_update
  8471. if (fragmentation > cparams.defrag_thold) {
  8472. //LLAMA_LOG_INFO("fragmentation: %.2f\n", fragmentation);
  8473. llama_kv_cache_defrag(kv_self);
  8474. }
  8475. }
  8476. return 0;
  8477. }
  8478. // find holes from the beginning of the KV cache and fill them by moving data from the end of the cache
  8479. static void llama_kv_cache_defrag_internal(struct llama_context & lctx) {
  8480. auto & kv_self = lctx.kv_self;
  8481. const auto & hparams = lctx.model.hparams;
  8482. const uint32_t n_layer = hparams.n_layer;
  8483. const uint32_t n_kv = llama_kv_cache_cell_max(kv_self);
  8484. const uint32_t n_used = kv_self.used;
  8485. assert(n_used <= n_kv);
  8486. //const int64_t t_start = ggml_time_us();
  8487. // number of cells moved
  8488. uint32_t n_moves = 0;
  8489. // each move requires 6*n_layer tensors (see build_defrag)
  8490. // - source view, destination view, copy operation
  8491. // - x2 for keys and values
  8492. const uint32_t max_moves = LLAMA_MAX_NODES/(6*n_layer);
  8493. // determine which KV cells to move where
  8494. //
  8495. // cell i moves to ids[i]
  8496. //
  8497. // if ids[i] == i || ids[i] == n_kv, then cell i is not moved
  8498. //
  8499. std::vector<uint32_t> ids(n_kv, n_kv);
  8500. for (uint32_t i0 = 0; i0 < n_used; ++i0) {
  8501. const auto & cell0 = kv_self.cells[i0];
  8502. if (!cell0.is_empty()) {
  8503. ids[i0] = i0;
  8504. continue;
  8505. }
  8506. // found a hole - fill it with data from the end of the cache
  8507. uint32_t nh = 1;
  8508. // determine the size of the hole
  8509. while (i0 + nh < n_used && kv_self.cells[i0 + nh].is_empty()) {
  8510. nh++;
  8511. }
  8512. uint32_t nf = 0;
  8513. uint32_t is = n_kv - 1;
  8514. // starting from the end, find nh non-empty cells
  8515. for (; is > i0; --is) {
  8516. const auto & cell1 = kv_self.cells[is];
  8517. if (cell1.is_empty() || ids[is] != n_kv) {
  8518. continue;
  8519. }
  8520. // non-empty cell which is not yet moved
  8521. nf++;
  8522. if (nf == nh) {
  8523. break;
  8524. }
  8525. }
  8526. // this can only happen if `n_used` is not accurate, which would be a bug
  8527. GGML_ASSERT(nf == nh && "KV defrag bug: nf != nh");
  8528. nf = 0;
  8529. uint32_t i1 = is;
  8530. // are we moving a continuous block of memory?
  8531. bool cont = false;
  8532. // should we stop searching for the next move?
  8533. bool stop = false;
  8534. // go back and move the nf cells to the hole
  8535. for (; i1 < n_kv; ++i1) {
  8536. auto & cell1 = kv_self.cells[i1];
  8537. if (cell1.is_empty() || ids[i1] != n_kv) {
  8538. if (n_moves == max_moves) {
  8539. stop = true;
  8540. break;
  8541. }
  8542. cont = false;
  8543. continue;
  8544. }
  8545. // this cell goes to (i0 + nf)
  8546. ids[i1] = i0 + nf;
  8547. // move the cell meta data
  8548. kv_self.cells[i0 + nf] = cell1;
  8549. // clear the old cell and move the head there
  8550. cell1 = llama_kv_cell();
  8551. kv_self.head = n_used;
  8552. if (!cont) {
  8553. n_moves++;
  8554. cont = true;
  8555. }
  8556. nf++;
  8557. if (nf == nh) {
  8558. break;
  8559. }
  8560. }
  8561. if (stop || n_moves == max_moves) {
  8562. break;
  8563. }
  8564. //LLAMA_LOG_INFO("(tmp log) KV defrag: move [%u, %u) to [%u, %u)\n", is, i1 + 1, i0, i0 + nh);
  8565. i0 += nh - 1;
  8566. }
  8567. if (n_moves == 0) {
  8568. return;
  8569. }
  8570. //LLAMA_LOG_INFO("(tmp log) KV defrag cell moves: %u\n", n_moves);
  8571. //LLAMA_LOG_INFO("expected gf nodes: %u\n", 6*n_moves*n_layer);
  8572. #if 0
  8573. // CPU defrag
  8574. //
  8575. // TODO: optimizations are possible:
  8576. // - multiple threads
  8577. // - avoid copying to the host memory when already there
  8578. //
  8579. // likely not worth the effort, as we have ggml_graph based defrag
  8580. //
  8581. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  8582. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  8583. const uint32_t kv_size = kv_self.size;
  8584. std::vector<uint8_t> buf_k;
  8585. std::vector<uint8_t> buf_v;
  8586. for (uint32_t il = 0; il < n_layer; ++il) {
  8587. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  8588. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_size);
  8589. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  8590. const size_t v_size = ggml_row_size (kv_self.v_l[il]->type, n_embd_v_gqa*kv_size);
  8591. buf_k.resize(k_size);
  8592. buf_v.resize(v_size);
  8593. ggml_backend_tensor_get(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  8594. ggml_backend_tensor_get(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  8595. // batch move [i, i+nm) to [id, id+nm)
  8596. // note: cells can move only to a lower index
  8597. for (uint32_t i = 0; i < n_kv; ++i) {
  8598. const uint32_t id = ids[i];
  8599. if (i == id || id == n_kv) {
  8600. continue;
  8601. }
  8602. uint32_t nm = 1;
  8603. while (i + nm < n_kv && ids[i + nm] == id + nm) {
  8604. nm++;
  8605. }
  8606. // move keys
  8607. {
  8608. const int64_t os = i*k_size_row;
  8609. const int64_t od = id*k_size_row;
  8610. memcpy(buf_k.data() + od, buf_k.data() + os, nm*k_size_row);
  8611. }
  8612. // move values (note: they are transposed)
  8613. {
  8614. const int64_t os = i;
  8615. const int64_t od = id;
  8616. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  8617. 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);
  8618. }
  8619. }
  8620. i += nm - 1;
  8621. }
  8622. ggml_backend_tensor_set(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  8623. ggml_backend_tensor_set(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  8624. }
  8625. #else
  8626. // ggml_graph defrag
  8627. ggml_backend_sched_reset(lctx.sched);
  8628. ggml_cgraph * gf = llama_build_graph_defrag(lctx, ids);
  8629. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  8630. #endif
  8631. //const int64_t t_end = ggml_time_us();
  8632. //LLAMA_LOG_INFO("(tmp log) KV defrag time: %.3f ms\n", (t_end - t_start)/1000.0);
  8633. }
  8634. static void llama_kv_cache_update_internal(struct llama_context & lctx) {
  8635. bool need_reserve = false;
  8636. // apply K-shift if needed
  8637. if (lctx.model.hparams.rope_type != LLAMA_ROPE_TYPE_NONE && lctx.kv_self.has_shift) {
  8638. {
  8639. ggml_backend_sched_reset(lctx.sched);
  8640. ggml_cgraph * gf = llama_build_graph_k_shift(lctx);
  8641. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  8642. llama_set_k_shift(lctx);
  8643. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  8644. need_reserve = true;
  8645. }
  8646. {
  8647. auto & kv_self = lctx.kv_self;
  8648. kv_self.has_shift = false;
  8649. for (uint32_t i = 0; i < kv_self.size; ++i) {
  8650. kv_self.cells[i].delta = 0;
  8651. }
  8652. }
  8653. }
  8654. if (lctx.kv_self.recurrent && lctx.kv_self.do_copy) {
  8655. {
  8656. ggml_backend_sched_reset(lctx.sched);
  8657. ggml_cgraph * gf = llama_build_graph_s_copy(lctx);
  8658. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  8659. llama_set_s_copy(lctx);
  8660. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  8661. need_reserve = true;
  8662. }
  8663. {
  8664. auto & kv_self = lctx.kv_self;
  8665. kv_self.do_copy = false;
  8666. for (uint32_t i = 0; i < kv_self.size; ++i) {
  8667. kv_self.cells[i].src = i;
  8668. }
  8669. }
  8670. }
  8671. // defragment the KV cache if needed
  8672. if (lctx.kv_self.do_defrag) {
  8673. llama_kv_cache_defrag_internal(lctx);
  8674. need_reserve = true;
  8675. lctx.kv_self.do_defrag = false;
  8676. }
  8677. // reserve a worst case graph again
  8678. if (need_reserve) {
  8679. // TODO: extract to a function
  8680. // build worst-case graph
  8681. int n_tokens = (int)std::min(lctx.cparams.n_ctx, lctx.cparams.n_ubatch);
  8682. int n_past = lctx.cparams.n_ctx - n_tokens;
  8683. 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
  8684. ggml_cgraph * gf = llama_build_graph(lctx, llama_batch_get_one(&token, n_tokens, n_past, 0), true);
  8685. // initialize scheduler with the worst-case graph
  8686. ggml_backend_sched_reset(lctx.sched);
  8687. if (!ggml_backend_sched_reserve(lctx.sched, gf)) {
  8688. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  8689. }
  8690. }
  8691. }
  8692. //
  8693. // tokenizer
  8694. //
  8695. static enum llama_vocab_type llama_vocab_get_type(const llama_vocab & vocab) {
  8696. return vocab.type;
  8697. }
  8698. static bool llama_is_normal_token(const llama_vocab & vocab, llama_token id) {
  8699. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  8700. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL;
  8701. }
  8702. static bool llama_is_unknown_token(const llama_vocab & vocab, llama_token id) {
  8703. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  8704. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_UNKNOWN;
  8705. }
  8706. static bool llama_is_control_token(const llama_vocab & vocab, llama_token id) {
  8707. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  8708. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_CONTROL;
  8709. }
  8710. static bool llama_is_byte_token(const llama_vocab & vocab, llama_token id) {
  8711. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  8712. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_BYTE;
  8713. }
  8714. static bool llama_is_user_defined_token(const llama_vocab& vocab, llama_token id) {
  8715. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  8716. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_USER_DEFINED;
  8717. }
  8718. static uint8_t llama_token_to_byte(const llama_vocab& vocab, llama_token id) {
  8719. GGML_ASSERT(llama_vocab_get_type(vocab) != LLAMA_VOCAB_TYPE_NONE);
  8720. GGML_ASSERT(llama_is_byte_token(vocab, id));
  8721. const auto& token_data = vocab.id_to_token.at(id);
  8722. switch (llama_vocab_get_type(vocab)) {
  8723. case LLAMA_VOCAB_TYPE_SPM: {
  8724. auto buf = token_data.text.substr(3, 2);
  8725. return strtol(buf.c_str(), NULL, 16);
  8726. }
  8727. case LLAMA_VOCAB_TYPE_BPE: {
  8728. GGML_ASSERT(false);
  8729. return unicode_utf8_to_byte(token_data.text);
  8730. }
  8731. case LLAMA_VOCAB_TYPE_WPM: {
  8732. GGML_ASSERT(false);
  8733. }
  8734. default:
  8735. GGML_ASSERT(false);
  8736. }
  8737. }
  8738. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch) {
  8739. GGML_ASSERT(llama_vocab_get_type(vocab) != LLAMA_VOCAB_TYPE_NONE);
  8740. static const char * hex = "0123456789ABCDEF";
  8741. switch (llama_vocab_get_type(vocab)) {
  8742. case LLAMA_VOCAB_TYPE_SPM: {
  8743. const char buf[7] = { '<', '0', 'x', hex[ch >> 4], hex[ch & 15], '>', 0 };
  8744. auto token = vocab.token_to_id.find(buf);
  8745. if (token != vocab.token_to_id.end()) {
  8746. return (*token).second;
  8747. }
  8748. // Try to fall back to just the byte as a string
  8749. const char buf2[2] = { (char)ch, 0 };
  8750. return vocab.token_to_id.at(buf2);
  8751. }
  8752. case LLAMA_VOCAB_TYPE_WPM:
  8753. case LLAMA_VOCAB_TYPE_BPE: {
  8754. return vocab.token_to_id.at(unicode_byte_to_utf8(ch));
  8755. }
  8756. default:
  8757. GGML_ASSERT(false);
  8758. }
  8759. }
  8760. static void llama_escape_whitespace(std::string & text) {
  8761. replace_all(text, " ", "\xe2\x96\x81");
  8762. }
  8763. static void llama_unescape_whitespace(std::string & word) {
  8764. replace_all(word, "\xe2\x96\x81", " ");
  8765. }
  8766. struct llm_symbol {
  8767. using index = int;
  8768. index prev;
  8769. index next;
  8770. const char * text;
  8771. size_t n;
  8772. };
  8773. static_assert(std::is_trivially_copyable<llm_symbol>::value, "llm_symbol is not trivially copyable");
  8774. // SPM tokenizer
  8775. // original implementation:
  8776. // https://github.com/ggerganov/llama.cpp/commit/074bea2eb1f1349a0118239c4152914aecaa1be4
  8777. struct llm_bigram_spm {
  8778. struct comparator {
  8779. bool operator()(llm_bigram_spm & l, llm_bigram_spm & r) {
  8780. return (l.score < r.score) || (l.score == r.score && l.left > r.left);
  8781. }
  8782. };
  8783. using queue_storage = std::vector<llm_bigram_spm>;
  8784. using queue = std::priority_queue<llm_bigram_spm, queue_storage, comparator>;
  8785. llm_symbol::index left;
  8786. llm_symbol::index right;
  8787. float score;
  8788. size_t size;
  8789. };
  8790. struct llm_tokenizer_spm {
  8791. llm_tokenizer_spm(const llama_vocab & vocab) : vocab(vocab) {}
  8792. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  8793. // split string into utf8 chars
  8794. int index = 0;
  8795. size_t offs = 0;
  8796. while (offs < text.size()) {
  8797. llm_symbol sym;
  8798. size_t len = utf8_len(text[offs]);
  8799. sym.text = text.c_str() + offs;
  8800. sym.n = std::min(len, text.size() - offs);
  8801. offs += sym.n;
  8802. sym.prev = index - 1;
  8803. sym.next = offs == text.size() ? -1 : index + 1;
  8804. index++;
  8805. symbols.emplace_back(sym);
  8806. }
  8807. // seed the work queue with all possible 2-character tokens.
  8808. for (size_t i = 1; i < symbols.size(); ++i) {
  8809. try_add_bigram(i - 1, i);
  8810. }
  8811. // keep substituting the highest frequency pairs for as long as we can.
  8812. while (!work_queue.empty()) {
  8813. auto bigram = work_queue.top();
  8814. work_queue.pop();
  8815. auto & left_sym = symbols[bigram.left];
  8816. auto & right_sym = symbols[bigram.right];
  8817. // if one of the symbols already got merged, skip it.
  8818. if (left_sym.n == 0 || right_sym.n == 0 ||
  8819. left_sym.n + right_sym.n != bigram.size) {
  8820. continue;
  8821. }
  8822. // merge the right sym into the left one
  8823. left_sym.n += right_sym.n;
  8824. right_sym.n = 0;
  8825. //LLAMA_LOG_INFO("left = '%*s' size = %zu\n", (int) left_sym.n, left_sym.text, bigram.size);
  8826. // remove the right sym from the chain
  8827. left_sym.next = right_sym.next;
  8828. if (right_sym.next >= 0) {
  8829. symbols[right_sym.next].prev = bigram.left;
  8830. }
  8831. // find more substitutions
  8832. try_add_bigram(left_sym.prev, bigram.left);
  8833. try_add_bigram(bigram.left, left_sym.next);
  8834. }
  8835. for (int i = 0; i != -1; i = symbols[i].next) {
  8836. auto & symbol = symbols[i];
  8837. resegment(symbol, output);
  8838. }
  8839. }
  8840. private:
  8841. void resegment(llm_symbol & symbol, std::vector<llama_vocab::id> & output) {
  8842. auto text = std::string(symbol.text, symbol.n);
  8843. auto token = vocab.token_to_id.find(text);
  8844. // Do we need to support is_unused?
  8845. if (token != vocab.token_to_id.end()) {
  8846. output.push_back((*token).second);
  8847. return;
  8848. }
  8849. const auto p = rev_merge.find(text);
  8850. if (p == rev_merge.end()) {
  8851. // output any symbols that did not form tokens as bytes.
  8852. output.reserve(output.size() + symbol.n);
  8853. for (int j = 0; j < (int)symbol.n; ++j) {
  8854. llama_vocab::id token_id = llama_byte_to_token(vocab, symbol.text[j]);
  8855. output.push_back(token_id);
  8856. }
  8857. return;
  8858. }
  8859. resegment(symbols[p->second.first], output);
  8860. resegment(symbols[p->second.second], output);
  8861. }
  8862. void try_add_bigram(int left, int right) {
  8863. if (left == -1 || right == -1) {
  8864. return;
  8865. }
  8866. const std::string text = std::string(symbols[left].text, symbols[left].n + symbols[right].n);
  8867. auto token = vocab.token_to_id.find(text);
  8868. if (token == vocab.token_to_id.end()) {
  8869. return;
  8870. }
  8871. if (static_cast<size_t>((*token).second) >= vocab.id_to_token.size()) {
  8872. return;
  8873. }
  8874. const auto & tok_data = vocab.id_to_token[(*token).second];
  8875. llm_bigram_spm bigram;
  8876. bigram.left = left;
  8877. bigram.right = right;
  8878. bigram.score = tok_data.score;
  8879. bigram.size = text.size();
  8880. work_queue.push(bigram);
  8881. // Do we need to support is_unused?
  8882. rev_merge[text] = std::make_pair(left, right);
  8883. }
  8884. const llama_vocab & vocab;
  8885. std::vector<llm_symbol> symbols;
  8886. llm_bigram_spm::queue work_queue;
  8887. std::map<std::string, std::pair<int, int>> rev_merge;
  8888. };
  8889. // BPE tokenizer
  8890. // adapted from https://github.com/cmp-nct/ggllm.cpp [MIT License]
  8891. // tried to simplify unicode stuff, so most likely does not work 100% correctly!
  8892. // TODO: there are a lot of common parts between spm and bpe tokenizers, should be refactored and reused
  8893. struct llm_bigram_bpe {
  8894. struct comparator {
  8895. bool operator()(const llm_bigram_bpe & l, const llm_bigram_bpe & r) const {
  8896. return l.rank > r.rank || (l.rank == r.rank && l.left > r.left);
  8897. }
  8898. };
  8899. using queue_storage = std::vector<llm_bigram_bpe>;
  8900. using queue = std::priority_queue<llm_bigram_bpe, queue_storage, comparator>;
  8901. llm_symbol::index left;
  8902. llm_symbol::index right;
  8903. std::string text;
  8904. int rank;
  8905. size_t size;
  8906. };
  8907. struct llm_tokenizer_bpe {
  8908. llm_tokenizer_bpe(const llama_vocab & vocab): vocab(vocab) {}
  8909. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  8910. int final_prev_index = -1;
  8911. auto word_collection = bpe_gpt2_preprocess(text);
  8912. symbols_final.clear();
  8913. for (auto & word : word_collection) {
  8914. work_queue = llm_bigram_bpe::queue();
  8915. symbols.clear();
  8916. int index = 0;
  8917. size_t offset = 0;
  8918. while (offset < word.size()) {
  8919. llm_symbol sym;
  8920. size_t char_len = std::min(word.size() - offset, (size_t) ::utf8_len(word[offset]));
  8921. sym.text = word.c_str() + offset;
  8922. sym.n = char_len;
  8923. offset += sym.n;
  8924. sym.prev = index - 1;
  8925. sym.next = offset == word.size() ? -1 : index + 1;
  8926. index++;
  8927. symbols.emplace_back(sym);
  8928. }
  8929. for (size_t i = 1; i < symbols.size(); ++i) {
  8930. add_new_bigram(i - 1, i);
  8931. }
  8932. // build token(s)
  8933. while (!work_queue.empty()) {
  8934. auto bigram = work_queue.top();
  8935. work_queue.pop();
  8936. auto & left_symbol = symbols[bigram.left];
  8937. auto & right_symbol = symbols[bigram.right];
  8938. if (left_symbol.n == 0 || right_symbol.n == 0) {
  8939. continue;
  8940. }
  8941. std::string left_token = std::string(left_symbol.text, left_symbol.n);
  8942. std::string right_token = std::string(right_symbol.text, right_symbol.n);
  8943. if (left_token + right_token != bigram.text) {
  8944. continue; // Skip this bigram if it's outdated
  8945. }
  8946. // merge the right sym into the left one
  8947. left_symbol.n += right_symbol.n;
  8948. right_symbol.n = 0;
  8949. // remove the right sym from the chain
  8950. left_symbol.next = right_symbol.next;
  8951. if (right_symbol.next >= 0) {
  8952. symbols[right_symbol.next].prev = bigram.left;
  8953. }
  8954. add_new_bigram(left_symbol.prev, bigram.left); // left side of current symbol
  8955. add_new_bigram(bigram.left, left_symbol.next); // right side of current symbol
  8956. }
  8957. // add the fnished tokens to the final list keeping correct order for next and prev
  8958. for (auto & sym : symbols) {
  8959. if (sym.n > 0) {
  8960. sym.prev = final_prev_index;
  8961. sym.next = -1;
  8962. if (final_prev_index != -1) {
  8963. symbols_final[final_prev_index].next = symbols_final.size();
  8964. }
  8965. symbols_final.emplace_back(sym);
  8966. final_prev_index = symbols_final.size() - 1;
  8967. }
  8968. }
  8969. }
  8970. symbols = symbols_final;
  8971. if (!symbols.empty()) {
  8972. for (int i = 0; i != -1; i = symbols[i].next) {
  8973. auto & symbol = symbols[i];
  8974. if (symbol.n == 0) {
  8975. continue;
  8976. }
  8977. const std::string str = std::string(symbol.text, symbol.n);
  8978. const auto token = vocab.token_to_id.find(str);
  8979. if (token == vocab.token_to_id.end()) {
  8980. for (auto j = str.begin(); j != str.end(); ++j) {
  8981. std::string byte_str(1, *j);
  8982. auto token_multibyte = vocab.token_to_id.find(byte_str);
  8983. if (token_multibyte == vocab.token_to_id.end()) {
  8984. throw std::runtime_error("ERROR: byte not found in vocab");
  8985. }
  8986. output.push_back((*token_multibyte).second);
  8987. }
  8988. } else {
  8989. output.push_back((*token).second);
  8990. }
  8991. }
  8992. }
  8993. }
  8994. private:
  8995. void add_new_bigram(int left, int right) {
  8996. if (left == -1 || right == -1) {
  8997. return;
  8998. }
  8999. std::string left_token = std::string(symbols[left].text, symbols[left].n);
  9000. std::string right_token = std::string(symbols[right].text, symbols[right].n);
  9001. int rank_found = -1;
  9002. rank_found = vocab.find_bpe_rank(left_token, right_token);
  9003. if (rank_found < 0) {
  9004. return;
  9005. }
  9006. llm_bigram_bpe bigram;
  9007. bigram.left = left;
  9008. bigram.right = right;
  9009. bigram.text = left_token + right_token;
  9010. bigram.size = left_token.size() + right_token.size();
  9011. bigram.rank = rank_found;
  9012. work_queue.push(bigram);
  9013. }
  9014. std::vector<std::string> bpe_gpt2_preprocess(const std::string & text) {
  9015. std::vector<std::string> bpe_words;
  9016. std::vector<std::string> bpe_encoded_words;
  9017. std::string token = "";
  9018. // GPT2 system regex: 's|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+
  9019. bool collecting_numeric = false;
  9020. bool collecting_letter = false;
  9021. bool collecting_special = false;
  9022. bool collecting_whitespace_lookahead = false;
  9023. bool collecting = false;
  9024. std::vector<std::string> text_utf;
  9025. text_utf.reserve(text.size());
  9026. bpe_words.reserve(text.size());
  9027. bpe_encoded_words.reserve(text.size());
  9028. const auto cpts = unicode_cpts_from_utf8(text);
  9029. for (size_t i = 0; i < cpts.size(); ++i)
  9030. text_utf.emplace_back(unicode_cpt_to_utf8(cpts[i]));
  9031. for (int i = 0; i < (int)text_utf.size(); i++) {
  9032. const std::string & utf_char = text_utf[i];
  9033. bool split_condition = false;
  9034. int bytes_remain = text_utf.size() - i;
  9035. // forward backward lookups
  9036. const std::string & utf_char_next = (i + 1 < (int)text_utf.size()) ? text_utf[i + 1] : "";
  9037. const std::string & utf_char_next_next = (i + 2 < (int)text_utf.size()) ? text_utf[i + 2] : "";
  9038. // handling contractions
  9039. if (!split_condition && bytes_remain >= 2) {
  9040. // 's|'t|'m|'d
  9041. if (utf_char == "\'" && (utf_char_next == "s" || utf_char_next == "t" || utf_char_next == "m" || utf_char_next == "d")) {
  9042. split_condition = true;
  9043. }
  9044. if (split_condition) {
  9045. if (token.size()) {
  9046. bpe_words.emplace_back(token); // push previous content as token
  9047. }
  9048. token = utf_char + utf_char_next;
  9049. bpe_words.emplace_back(token);
  9050. token = "";
  9051. i++;
  9052. continue;
  9053. }
  9054. }
  9055. if (!split_condition && bytes_remain >= 3) {
  9056. // 're|'ve|'ll
  9057. if (utf_char == "\'" && (
  9058. (utf_char_next == "r" && utf_char_next_next == "e") ||
  9059. (utf_char_next == "v" && utf_char_next_next == "e") ||
  9060. (utf_char_next == "l" && utf_char_next_next == "l"))
  9061. ) {
  9062. split_condition = true;
  9063. }
  9064. if (split_condition) {
  9065. // current token + next token can be defined
  9066. if (token.size()) {
  9067. bpe_words.emplace_back(token); // push previous content as token
  9068. }
  9069. token = utf_char + utf_char_next + utf_char_next_next;
  9070. bpe_words.emplace_back(token); // the contraction
  9071. token = "";
  9072. i += 2;
  9073. continue;
  9074. }
  9075. }
  9076. if (!split_condition && !collecting) {
  9077. if (unicode_cpt_type(utf_char) == CODEPOINT_TYPE_LETTER || (!token.size() && utf_char == " " && unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_LETTER)) {
  9078. collecting_letter = true;
  9079. collecting = true;
  9080. }
  9081. else if (unicode_cpt_type(utf_char) == CODEPOINT_TYPE_DIGIT || (!token.size() && utf_char == " " && unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  9082. collecting_numeric = true;
  9083. collecting = true;
  9084. }
  9085. else if (
  9086. ((unicode_cpt_type(utf_char) != CODEPOINT_TYPE_LETTER && unicode_cpt_type(utf_char) != CODEPOINT_TYPE_DIGIT) && (unicode_cpt_type(utf_char) != CODEPOINT_TYPE_WHITESPACE)) ||
  9087. (!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)
  9088. ) {
  9089. collecting_special = true;
  9090. collecting = true;
  9091. }
  9092. else if (unicode_cpt_type(utf_char) == CODEPOINT_TYPE_WHITESPACE && unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_WHITESPACE) {
  9093. collecting_whitespace_lookahead = true;
  9094. collecting = true;
  9095. }
  9096. else if (unicode_cpt_type(utf_char) == CODEPOINT_TYPE_WHITESPACE) {
  9097. split_condition = true;
  9098. }
  9099. }
  9100. else if (!split_condition && collecting) {
  9101. if (collecting_letter && unicode_cpt_type(utf_char) != CODEPOINT_TYPE_LETTER) {
  9102. split_condition = true;
  9103. }
  9104. else if (collecting_numeric && unicode_cpt_type(utf_char) != CODEPOINT_TYPE_DIGIT) {
  9105. split_condition = true;
  9106. }
  9107. 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)) {
  9108. split_condition = true;
  9109. }
  9110. else if (collecting_whitespace_lookahead && (unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_LETTER || unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  9111. split_condition = true;
  9112. }
  9113. }
  9114. if (utf_char_next == "") {
  9115. split_condition = true; // final
  9116. token += utf_char;
  9117. }
  9118. if (split_condition) {
  9119. if (token.size()) {
  9120. bpe_words.emplace_back(token);
  9121. }
  9122. token = utf_char;
  9123. collecting = false;
  9124. collecting_letter = false;
  9125. collecting_numeric = false;
  9126. collecting_special = false;
  9127. collecting_whitespace_lookahead = false;
  9128. }
  9129. else {
  9130. token += utf_char;
  9131. }
  9132. }
  9133. for (std::string & word : bpe_words) {
  9134. std::string encoded_token = "";
  9135. for (char & c : word) {
  9136. encoded_token += unicode_byte_to_utf8(c);
  9137. }
  9138. bpe_encoded_words.emplace_back(encoded_token);
  9139. }
  9140. return bpe_encoded_words;
  9141. }
  9142. const llama_vocab & vocab;
  9143. std::vector<llm_symbol> symbols;
  9144. std::vector<llm_symbol> symbols_final;
  9145. llm_bigram_bpe::queue work_queue;
  9146. };
  9147. struct llm_tokenizer_wpm {
  9148. llm_tokenizer_wpm(const llama_vocab & vocab): vocab(vocab) {}
  9149. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  9150. auto * token_map = &vocab.token_to_id;
  9151. // normalize and split by whitespace
  9152. std::vector<std::string> words = preprocess(text);
  9153. // bos token prepended already
  9154. // find the longest tokens that form the words
  9155. for (const std::string &word : words) {
  9156. // skip empty words
  9157. if (word.size() == 0) {
  9158. continue;
  9159. }
  9160. // prepend phantom space
  9161. std::string word1 = "\xe2\x96\x81" + word;
  9162. int n = word1.size();
  9163. // we're at the start of a new word
  9164. int i = 0;
  9165. bool match_any = false;
  9166. // move through character position in word
  9167. while (i < n) {
  9168. // loop through possible match length
  9169. bool match = false;
  9170. for (int j = n; j > i; j--) {
  9171. auto it = token_map->find(word1.substr(i, j - i));
  9172. if (it != token_map->end()) {
  9173. output.push_back(it->second);
  9174. match = true;
  9175. match_any = true;
  9176. i = j;
  9177. break;
  9178. }
  9179. }
  9180. // must be an unknown character
  9181. if (!match) {
  9182. i++;
  9183. }
  9184. }
  9185. // we didn't find any matches for this word
  9186. if (!match_any) {
  9187. output.push_back(vocab.special_unk_id);
  9188. }
  9189. }
  9190. // append eos token
  9191. output.push_back(vocab.special_eos_id);
  9192. }
  9193. std::vector<std::string> preprocess(const std::string & text) {
  9194. std::vector<uint32_t> cpts_nfd = unicode_cpts_normalize_nfd(unicode_cpts_from_utf8(text));
  9195. // strip accents, strip control, uniformize whitespace,
  9196. // to lowercase, pad chinese characters, pad punctuation
  9197. std::string new_str = "";
  9198. for (uint32_t code : cpts_nfd) {
  9199. int type = unicode_cpt_type(code);
  9200. if (type == CODEPOINT_TYPE_ACCENT_MARK || type == CODEPOINT_TYPE_CONTROL) {
  9201. continue;
  9202. }
  9203. code = unicode_tolower(code);
  9204. if (type == CODEPOINT_TYPE_WHITESPACE) {
  9205. code = ' ';
  9206. }
  9207. std::string s = unicode_cpt_to_utf8(code);
  9208. if (type == CODEPOINT_TYPE_PUNCTUATION || is_ascii_punct(code) || is_chinese_char(code)) {
  9209. new_str += " ";
  9210. new_str += s;
  9211. new_str += " ";
  9212. } else {
  9213. new_str += s;
  9214. }
  9215. }
  9216. // split by whitespace
  9217. uint64_t l = 0;
  9218. uint64_t r = 0;
  9219. std::vector<std::string> words;
  9220. while (r < new_str.size()) {
  9221. // if is whitespace
  9222. if (isspace(new_str[r], std::locale::classic())) {
  9223. if (r > l) words.push_back(new_str.substr(l, (r - l)));
  9224. l = r + 1;
  9225. r = l;
  9226. } else {
  9227. r += 1;
  9228. }
  9229. }
  9230. if (r > l) {
  9231. words.push_back(new_str.substr(l, (r - l)));
  9232. }
  9233. return words;
  9234. }
  9235. bool is_ascii_punct(uint32_t code) {
  9236. if (code > 0xFF) {
  9237. return false;
  9238. }
  9239. auto c = char(static_cast<unsigned char>(code));
  9240. return ispunct(c, std::locale::classic());
  9241. }
  9242. bool is_chinese_char(uint32_t cpt) {
  9243. if ((cpt >= 0x4E00 && cpt <= 0x9FFF) ||
  9244. (cpt >= 0x3400 && cpt <= 0x4DBF) ||
  9245. (cpt >= 0x20000 && cpt <= 0x2A6DF) ||
  9246. (cpt >= 0x2A700 && cpt <= 0x2B73F) ||
  9247. (cpt >= 0x2B740 && cpt <= 0x2B81F) ||
  9248. (cpt >= 0x2B920 && cpt <= 0x2CEAF) || // this should be 0x2B820 but in hf rust code it is 0x2B920
  9249. (cpt >= 0xF900 && cpt <= 0xFAFF) ||
  9250. (cpt >= 0x2F800 && cpt <= 0x2FA1F) ||
  9251. (cpt >= 0x3000 && cpt <= 0x303F) ||
  9252. (cpt >= 0xFF00 && cpt <= 0xFFEF)) {
  9253. return true; // NOLINT
  9254. }
  9255. return false;
  9256. }
  9257. const llama_vocab & vocab;
  9258. };
  9259. typedef enum FRAGMENT_BUFFER_VARIANT_TYPE {
  9260. FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN,
  9261. FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT
  9262. } FRAGMENT_BUFFER_VARIANT_TYPE;
  9263. struct fragment_buffer_variant {
  9264. fragment_buffer_variant(llama_vocab::id _token)
  9265. :
  9266. type(FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN),
  9267. token(_token),
  9268. raw_text(_dummy),
  9269. offset(0),
  9270. length(0) {}
  9271. fragment_buffer_variant(const std::string & _raw_text, int64_t _offset, int64_t _length)
  9272. :
  9273. type(FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT),
  9274. token((llama_vocab::id) - 1),
  9275. raw_text(_raw_text),
  9276. offset(_offset),
  9277. length(_length){
  9278. GGML_ASSERT(_offset >= 0);
  9279. GGML_ASSERT(_length >= 1);
  9280. GGML_ASSERT(offset + length <= raw_text.length());
  9281. }
  9282. const FRAGMENT_BUFFER_VARIANT_TYPE type;
  9283. const llama_vocab::id token;
  9284. const std::string _dummy;
  9285. const std::string & raw_text;
  9286. const uint64_t offset;
  9287. const uint64_t length;
  9288. };
  9289. // #define PRETOKENIZERDEBUG
  9290. static void tokenizer_st_partition(const llama_vocab & vocab, std::forward_list<fragment_buffer_variant> & buffer) {
  9291. // for each special token
  9292. for (const auto & st: vocab.special_tokens_cache) {
  9293. const auto & special_token = st.first;
  9294. const auto & special_id = st.second;
  9295. // for each text fragment
  9296. std::forward_list<fragment_buffer_variant>::iterator it = buffer.begin();
  9297. while (it != buffer.end()) {
  9298. auto & fragment = (*it);
  9299. // if a fragment is text ( not yet processed )
  9300. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  9301. auto * raw_text = &(fragment.raw_text);
  9302. auto raw_text_base_offset = fragment.offset;
  9303. auto raw_text_base_length = fragment.length;
  9304. // loop over the text
  9305. while (true) {
  9306. // find the first occurrence of a given special token in this fragment
  9307. // passing offset argument only limit the "search area" but match coordinates
  9308. // are still relative to the source full raw_text
  9309. auto match = raw_text->find(special_token, raw_text_base_offset);
  9310. // no occurrences found, stop processing this fragment for a given special token
  9311. if (match == std::string::npos) break;
  9312. // check if match is within bounds of offset <-> length
  9313. if (match + special_token.length() > raw_text_base_offset + raw_text_base_length) break;
  9314. #ifdef PRETOKENIZERDEBUG
  9315. 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());
  9316. #endif
  9317. auto source = std::distance(buffer.begin(), it);
  9318. // if match is further than base offset
  9319. // then we have some text to the left of it
  9320. if (match > raw_text_base_offset) {
  9321. // left
  9322. const int64_t left_reminder_offset = raw_text_base_offset + 0;
  9323. const int64_t left_reminder_length = match - raw_text_base_offset;
  9324. buffer.emplace_after(it, (*raw_text), left_reminder_offset, left_reminder_length);
  9325. #ifdef PRETOKENIZERDEBUG
  9326. 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());
  9327. #endif
  9328. it++;
  9329. }
  9330. // special token
  9331. buffer.emplace_after(it, special_id);
  9332. it++;
  9333. // right
  9334. if (match + special_token.length() < raw_text_base_offset + raw_text_base_length) {
  9335. const int64_t right_reminder_offset = match + special_token.length();
  9336. const int64_t right_reminder_length = raw_text_base_length - ((match - raw_text_base_offset) + special_token.length());
  9337. buffer.emplace_after(it, (*raw_text), right_reminder_offset, right_reminder_length);
  9338. #ifdef PRETOKENIZERDEBUG
  9339. 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());
  9340. #endif
  9341. it++;
  9342. if (source == 0) {
  9343. buffer.erase_after(buffer.before_begin());
  9344. } else {
  9345. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  9346. }
  9347. // repeat for the right side
  9348. raw_text_base_offset = right_reminder_offset;
  9349. raw_text_base_length = right_reminder_length;
  9350. #ifdef PRETOKENIZERDEBUG
  9351. 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());
  9352. #endif
  9353. } else {
  9354. if (source == 0) {
  9355. buffer.erase_after(buffer.before_begin());
  9356. } else {
  9357. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  9358. }
  9359. break;
  9360. }
  9361. }
  9362. }
  9363. it++;
  9364. }
  9365. }
  9366. }
  9367. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special) {
  9368. std::vector<llama_vocab::id> output;
  9369. // OG tokenizer behavior:
  9370. //
  9371. // tokenizer.encode('', add_bos=True) returns [1]
  9372. // tokenizer.encode('', add_bos=False) returns []
  9373. if (bos && vocab.special_bos_id != -1) {
  9374. output.push_back(vocab.special_bos_id);
  9375. }
  9376. if (raw_text.empty()) {
  9377. return output;
  9378. }
  9379. std::forward_list<fragment_buffer_variant> fragment_buffer;
  9380. fragment_buffer.emplace_front(raw_text, 0, raw_text.length());
  9381. if (special) tokenizer_st_partition(vocab, fragment_buffer);
  9382. switch (vocab.type) {
  9383. case LLAMA_VOCAB_TYPE_SPM:
  9384. {
  9385. for (const auto & fragment : fragment_buffer) {
  9386. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  9387. // without adding this leading whitespace, we do not get the same results as the original tokenizer
  9388. // TODO: It's likely possible to get rid of this string copy entirely
  9389. // by modifying llm_tokenizer_x to operate with string offsets like pre-tokenizer
  9390. // and passing 'add space prefix' as bool argument
  9391. //
  9392. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  9393. if (&fragment == &fragment_buffer.front()) {
  9394. if (vocab.add_space_prefix) {
  9395. raw_text = " " + raw_text; // prefix with space if the first token is not special
  9396. }
  9397. }
  9398. #ifdef PRETOKENIZERDEBUG
  9399. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  9400. #endif
  9401. llm_tokenizer_spm tokenizer(vocab);
  9402. llama_escape_whitespace(raw_text);
  9403. tokenizer.tokenize(raw_text, output);
  9404. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  9405. output.push_back(fragment.token);
  9406. }
  9407. }
  9408. } break;
  9409. case LLAMA_VOCAB_TYPE_BPE:
  9410. {
  9411. for (const auto & fragment : fragment_buffer) {
  9412. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  9413. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  9414. #ifdef PRETOKENIZERDEBUG
  9415. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  9416. #endif
  9417. llm_tokenizer_bpe tokenizer(vocab);
  9418. tokenizer.tokenize(raw_text, output);
  9419. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  9420. output.push_back(fragment.token);
  9421. }
  9422. }
  9423. } break;
  9424. case LLAMA_VOCAB_TYPE_WPM:
  9425. {
  9426. for (const auto & fragment : fragment_buffer) {
  9427. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  9428. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  9429. #ifdef PRETOKENIZERDEBUG
  9430. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  9431. #endif
  9432. llm_tokenizer_wpm tokenizer(vocab);
  9433. tokenizer.tokenize(raw_text, output);
  9434. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  9435. output.push_back(fragment.token);
  9436. }
  9437. }
  9438. } break;
  9439. case LLAMA_VOCAB_TYPE_NONE:
  9440. GGML_ASSERT(false);
  9441. }
  9442. return output;
  9443. }
  9444. //
  9445. // grammar - internal
  9446. //
  9447. struct llama_partial_utf8 {
  9448. uint32_t value; // bit value so far (unshifted)
  9449. int n_remain; // num bytes remaining; -1 indicates invalid sequence
  9450. };
  9451. struct llama_grammar {
  9452. const std::vector<std::vector<llama_grammar_element>> rules;
  9453. std::vector<std::vector<const llama_grammar_element *>> stacks;
  9454. // buffer for partially generated UTF-8 sequence from accepted tokens
  9455. llama_partial_utf8 partial_utf8;
  9456. };
  9457. struct llama_grammar_candidate {
  9458. size_t index;
  9459. const uint32_t * code_points;
  9460. llama_partial_utf8 partial_utf8;
  9461. };
  9462. // Decodes a UTF-8 string which may end in an incomplete sequence. Adds a terminating 0 for use as
  9463. // pointer. If an invalid sequence is encountered, returns `llama_partial_utf8.n_remain == -1`.
  9464. static std::pair<std::vector<uint32_t>, llama_partial_utf8> decode_utf8(
  9465. const std::string & src,
  9466. llama_partial_utf8 partial_start) {
  9467. static const int lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 3, 4 };
  9468. const char * pos = src.c_str();
  9469. std::vector<uint32_t> code_points;
  9470. // common english strings have the same number of codepoints and bytes. `+ 1` for the terminating 0.
  9471. code_points.reserve(src.size() + 1);
  9472. uint32_t value = partial_start.value;
  9473. int n_remain = partial_start.n_remain;
  9474. // continue previous decode, if applicable
  9475. while (*pos != 0 && n_remain > 0) {
  9476. uint8_t next_byte = static_cast<uint8_t>(*pos);
  9477. if ((next_byte >> 6) != 2) {
  9478. // invalid sequence, abort
  9479. code_points.push_back(0);
  9480. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, -1 });
  9481. }
  9482. value = (value << 6) + (next_byte & 0x3F);
  9483. ++pos;
  9484. --n_remain;
  9485. }
  9486. if (partial_start.n_remain > 0 && n_remain == 0) {
  9487. code_points.push_back(value);
  9488. }
  9489. // decode any subsequent utf-8 sequences, which may end in an incomplete one
  9490. while (*pos != 0) {
  9491. uint8_t first_byte = static_cast<uint8_t>(*pos);
  9492. uint8_t highbits = first_byte >> 4;
  9493. n_remain = lookup[highbits] - 1;
  9494. if (n_remain < 0) {
  9495. // invalid sequence, abort
  9496. code_points.clear();
  9497. code_points.push_back(0);
  9498. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, n_remain });
  9499. }
  9500. uint8_t mask = (1 << (7 - n_remain)) - 1;
  9501. value = first_byte & mask;
  9502. ++pos;
  9503. while (*pos != 0 && n_remain > 0) {
  9504. value = (value << 6) + (static_cast<uint8_t>(*pos) & 0x3F);
  9505. ++pos;
  9506. --n_remain;
  9507. }
  9508. if (n_remain == 0) {
  9509. code_points.push_back(value);
  9510. }
  9511. }
  9512. code_points.push_back(0);
  9513. return std::make_pair(std::move(code_points), llama_partial_utf8{ value, n_remain });
  9514. }
  9515. // returns true iff pos points to the end of one of the definitions of a rule
  9516. static bool llama_grammar_is_end_of_sequence(const llama_grammar_element * pos) {
  9517. switch (pos->type) {
  9518. case LLAMA_GRETYPE_END: return true; // NOLINT
  9519. case LLAMA_GRETYPE_ALT: return true; // NOLINT
  9520. default: return false;
  9521. }
  9522. }
  9523. // returns true iff chr satisfies the char range at pos (regular or inverse range)
  9524. // asserts that pos is pointing to a char range element
  9525. static std::pair<bool, const llama_grammar_element *> llama_grammar_match_char(
  9526. const llama_grammar_element * pos,
  9527. const uint32_t chr) {
  9528. bool found = false;
  9529. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  9530. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT); // NOLINT
  9531. do {
  9532. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  9533. // inclusive range, e.g. [a-z]
  9534. found = found || (pos->value <= chr && chr <= pos[1].value);
  9535. pos += 2;
  9536. } else {
  9537. // exact char match, e.g. [a] or "a"
  9538. found = found || pos->value == chr;
  9539. pos += 1;
  9540. }
  9541. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  9542. return std::make_pair(found == is_positive_char, pos);
  9543. }
  9544. // returns true iff some continuation of the given partial UTF-8 sequence could satisfy the char
  9545. // range at pos (regular or inverse range)
  9546. // asserts that pos is pointing to a char range element
  9547. static bool llama_grammar_match_partial_char(
  9548. const llama_grammar_element * pos,
  9549. const llama_partial_utf8 partial_utf8) {
  9550. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  9551. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT);
  9552. uint32_t partial_value = partial_utf8.value;
  9553. int n_remain = partial_utf8.n_remain;
  9554. // invalid sequence or 7-bit char split across 2 bytes (overlong)
  9555. if (n_remain < 0 || (n_remain == 1 && partial_value < 2)) {
  9556. return false;
  9557. }
  9558. // range of possible code points this partial UTF-8 sequence could complete to
  9559. uint32_t low = partial_value << (n_remain * 6);
  9560. uint32_t high = low | ((1 << (n_remain * 6)) - 1);
  9561. if (low == 0) {
  9562. if (n_remain == 2) {
  9563. low = 1 << 11;
  9564. } else if (n_remain == 3) {
  9565. low = 1 << 16;
  9566. }
  9567. }
  9568. do {
  9569. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  9570. // inclusive range, e.g. [a-z]
  9571. if (pos->value <= high && low <= pos[1].value) {
  9572. return is_positive_char;
  9573. }
  9574. pos += 2;
  9575. } else {
  9576. // exact char match, e.g. [a] or "a"
  9577. if (low <= pos->value && pos->value <= high) {
  9578. return is_positive_char;
  9579. }
  9580. pos += 1;
  9581. }
  9582. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  9583. return !is_positive_char;
  9584. }
  9585. // transforms a grammar pushdown stack into N possible stacks, all ending
  9586. // at a character range (terminal element)
  9587. static void llama_grammar_advance_stack(
  9588. const std::vector<std::vector<llama_grammar_element>> & rules,
  9589. const std::vector<const llama_grammar_element *> & stack,
  9590. std::vector<std::vector<const llama_grammar_element *>> & new_stacks) {
  9591. if (stack.empty()) {
  9592. new_stacks.emplace_back(stack);
  9593. return;
  9594. }
  9595. const llama_grammar_element * pos = stack.back();
  9596. switch (pos->type) {
  9597. case LLAMA_GRETYPE_RULE_REF: {
  9598. const size_t rule_id = static_cast<size_t>(pos->value);
  9599. const llama_grammar_element * subpos = rules[rule_id].data();
  9600. do {
  9601. // init new stack without the top (pos)
  9602. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  9603. if (!llama_grammar_is_end_of_sequence(pos + 1)) {
  9604. // if this rule ref is followed by another element, add that to stack
  9605. new_stack.push_back(pos + 1);
  9606. }
  9607. if (!llama_grammar_is_end_of_sequence(subpos)) {
  9608. // if alternate is nonempty, add to stack
  9609. new_stack.push_back(subpos);
  9610. }
  9611. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  9612. while (!llama_grammar_is_end_of_sequence(subpos)) {
  9613. // scan to end of alternate def
  9614. subpos++;
  9615. }
  9616. if (subpos->type == LLAMA_GRETYPE_ALT) {
  9617. // there's another alternate def of this rule to process
  9618. subpos++;
  9619. } else {
  9620. break;
  9621. }
  9622. } while (true);
  9623. break;
  9624. }
  9625. case LLAMA_GRETYPE_CHAR:
  9626. case LLAMA_GRETYPE_CHAR_NOT:
  9627. new_stacks.emplace_back(stack);
  9628. break;
  9629. default:
  9630. // end of alternate (LLAMA_GRETYPE_END, LLAMA_GRETYPE_ALT) or middle of char range
  9631. // (LLAMA_GRETYPE_CHAR_ALT, LLAMA_GRETYPE_CHAR_RNG_UPPER); stack should never be left on
  9632. // those
  9633. GGML_ASSERT(false);
  9634. }
  9635. }
  9636. // takes a set of possible pushdown stacks on a grammar, which are required to
  9637. // be positioned at a character range (see `llama_grammar_advance_stack`), and
  9638. // produces the N possible stacks if the given char is accepted at those
  9639. // positions
  9640. static std::vector<std::vector<const llama_grammar_element *>> llama_grammar_accept(
  9641. const std::vector<std::vector<llama_grammar_element>> & rules,
  9642. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  9643. const uint32_t chr) {
  9644. std::vector<std::vector<const llama_grammar_element *>> new_stacks;
  9645. for (const auto & stack : stacks) {
  9646. if (stack.empty()) {
  9647. continue;
  9648. }
  9649. auto match = llama_grammar_match_char(stack.back(), chr);
  9650. if (match.first) {
  9651. const llama_grammar_element * pos = match.second;
  9652. // update top of stack to next element, if any
  9653. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  9654. if (!llama_grammar_is_end_of_sequence(pos)) {
  9655. new_stack.push_back(pos);
  9656. }
  9657. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  9658. }
  9659. }
  9660. return new_stacks;
  9661. }
  9662. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  9663. const std::vector<std::vector<llama_grammar_element>> & rules,
  9664. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  9665. const std::vector<llama_grammar_candidate> & candidates);
  9666. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates_for_stack(
  9667. const std::vector<std::vector<llama_grammar_element>> & rules,
  9668. const std::vector<const llama_grammar_element *> & stack,
  9669. const std::vector<llama_grammar_candidate> & candidates) {
  9670. std::vector<llama_grammar_candidate> rejects;
  9671. if (stack.empty()) {
  9672. for (const auto & tok : candidates) {
  9673. if (*tok.code_points != 0 || tok.partial_utf8.n_remain != 0) {
  9674. rejects.push_back(tok);
  9675. }
  9676. }
  9677. return rejects;
  9678. }
  9679. const llama_grammar_element * stack_pos = stack.back();
  9680. std::vector<llama_grammar_candidate> next_candidates;
  9681. for (const auto & tok : candidates) {
  9682. if (*tok.code_points == 0) {
  9683. // reached end of full codepoints in token, reject iff it ended in a partial sequence
  9684. // that cannot satisfy this position in grammar
  9685. if (tok.partial_utf8.n_remain != 0 &&
  9686. !llama_grammar_match_partial_char(stack_pos, tok.partial_utf8)) {
  9687. rejects.push_back(tok);
  9688. }
  9689. } else if (llama_grammar_match_char(stack_pos, *tok.code_points).first) {
  9690. next_candidates.push_back({ tok.index, tok.code_points + 1, tok.partial_utf8 });
  9691. } else {
  9692. rejects.push_back(tok);
  9693. }
  9694. }
  9695. const auto * stack_pos_after = llama_grammar_match_char(stack_pos, 0).second;
  9696. // update top of stack to next element, if any
  9697. std::vector<const llama_grammar_element *> stack_after(stack.begin(), stack.end() - 1);
  9698. if (!llama_grammar_is_end_of_sequence(stack_pos_after)) {
  9699. stack_after.push_back(stack_pos_after);
  9700. }
  9701. std::vector<std::vector<const llama_grammar_element *>> next_stacks;
  9702. llama_grammar_advance_stack(rules, stack_after, next_stacks);
  9703. auto next_rejects = llama_grammar_reject_candidates(rules, next_stacks, next_candidates);
  9704. for (const auto & tok : next_rejects) {
  9705. rejects.push_back({ tok.index, tok.code_points - 1, tok.partial_utf8 });
  9706. }
  9707. return rejects;
  9708. }
  9709. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  9710. const std::vector<std::vector<llama_grammar_element>> & rules,
  9711. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  9712. const std::vector<llama_grammar_candidate> & candidates) {
  9713. GGML_ASSERT(!stacks.empty()); // REVIEW
  9714. if (candidates.empty()) {
  9715. return std::vector<llama_grammar_candidate>();
  9716. }
  9717. auto rejects = llama_grammar_reject_candidates_for_stack(rules, stacks.front(), candidates);
  9718. for (size_t i = 1, size = stacks.size(); i < size; ++i) {
  9719. rejects = llama_grammar_reject_candidates_for_stack(rules, stacks[i], rejects);
  9720. }
  9721. return rejects;
  9722. }
  9723. //
  9724. // grammar - external
  9725. //
  9726. struct llama_grammar * llama_grammar_init(
  9727. const llama_grammar_element ** rules,
  9728. size_t n_rules,
  9729. size_t start_rule_index) {
  9730. const llama_grammar_element * pos;
  9731. // copy rule definitions into vectors
  9732. std::vector<std::vector<llama_grammar_element>> vec_rules(n_rules);
  9733. for (size_t i = 0; i < n_rules; i++) {
  9734. for (pos = rules[i]; pos->type != LLAMA_GRETYPE_END; pos++) {
  9735. vec_rules[i].push_back(*pos);
  9736. }
  9737. vec_rules[i].push_back({LLAMA_GRETYPE_END, 0});
  9738. }
  9739. // loop over alternates of start rule to build initial stacks
  9740. std::vector<std::vector<const llama_grammar_element *>> stacks;
  9741. pos = vec_rules[start_rule_index].data();
  9742. do {
  9743. std::vector<const llama_grammar_element *> stack;
  9744. if (!llama_grammar_is_end_of_sequence(pos)) {
  9745. // if alternate is nonempty, add to stack
  9746. stack.push_back(pos);
  9747. }
  9748. llama_grammar_advance_stack(vec_rules, stack, stacks);
  9749. while (!llama_grammar_is_end_of_sequence(pos)) {
  9750. // scan to end of alternate def
  9751. pos++;
  9752. }
  9753. if (pos->type == LLAMA_GRETYPE_ALT) {
  9754. // there's another alternate def of this rule to process
  9755. pos++;
  9756. } else {
  9757. break;
  9758. }
  9759. } while (true);
  9760. return new llama_grammar{ std::move(vec_rules), std::move(stacks), {} };
  9761. }
  9762. void llama_grammar_free(struct llama_grammar * grammar) {
  9763. delete grammar;
  9764. }
  9765. struct llama_grammar * llama_grammar_copy(const struct llama_grammar * grammar) {
  9766. llama_grammar * result = new llama_grammar{ grammar->rules, grammar->stacks, grammar->partial_utf8 };
  9767. // redirect elements in stacks to point to new rules
  9768. for (size_t is = 0; is < result->stacks.size(); is++) {
  9769. for (size_t ie = 0; ie < result->stacks[is].size(); ie++) {
  9770. for (size_t ir0 = 0; ir0 < grammar->rules.size(); ir0++) {
  9771. for (size_t ir1 = 0; ir1 < grammar->rules[ir0].size(); ir1++) {
  9772. if (grammar->stacks[is][ie] == &grammar->rules[ir0][ir1]) {
  9773. result->stacks[is][ie] = &result->rules[ir0][ir1];
  9774. }
  9775. }
  9776. }
  9777. }
  9778. }
  9779. return result;
  9780. }
  9781. //
  9782. // sampling
  9783. //
  9784. void llama_set_rng_seed(struct llama_context * ctx, uint32_t seed) {
  9785. if (seed == LLAMA_DEFAULT_SEED) {
  9786. seed = time(NULL);
  9787. }
  9788. ctx->rng.seed(seed);
  9789. }
  9790. void llama_sample_softmax(struct llama_context * ctx, llama_token_data_array * candidates) {
  9791. GGML_ASSERT(candidates->size > 0);
  9792. const int64_t t_start_sample_us = ggml_time_us();
  9793. // Sort the logits in descending order
  9794. if (!candidates->sorted) {
  9795. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  9796. return a.logit > b.logit;
  9797. });
  9798. candidates->sorted = true;
  9799. }
  9800. float max_l = candidates->data[0].logit;
  9801. float cum_sum = 0.0f;
  9802. for (size_t i = 0; i < candidates->size; ++i) {
  9803. float p = expf(candidates->data[i].logit - max_l);
  9804. candidates->data[i].p = p;
  9805. cum_sum += p;
  9806. }
  9807. for (size_t i = 0; i < candidates->size; ++i) {
  9808. candidates->data[i].p /= cum_sum;
  9809. }
  9810. if (ctx) {
  9811. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9812. }
  9813. }
  9814. void llama_sample_top_k(struct llama_context * ctx, llama_token_data_array * candidates, int32_t k, size_t min_keep) {
  9815. // TODO: move bucket sort to separate function so that top_p/tail_free/typical/softmax first is equally fast
  9816. // if (k >= (int32_t)candidates->size) {
  9817. // return;
  9818. // }
  9819. const int64_t t_start_sample_us = ggml_time_us();
  9820. if (k <= 0) {
  9821. k = candidates->size;
  9822. }
  9823. k = std::max(k, (int) min_keep);
  9824. k = std::min(k, (int) candidates->size);
  9825. // Sort scores in descending order
  9826. if (!candidates->sorted) {
  9827. auto comp = [](const llama_token_data & a, const llama_token_data & b) {
  9828. return a.logit > b.logit;
  9829. };
  9830. if (k <= 128) {
  9831. std::partial_sort(candidates->data, candidates->data + k, candidates->data + candidates->size, comp);
  9832. } else {
  9833. constexpr int nbuckets = 128;
  9834. constexpr float bucket_low = -10.0f;
  9835. constexpr float bucket_high = 10.0f;
  9836. constexpr float bucket_scale = nbuckets/(bucket_high - bucket_low);
  9837. constexpr float bucker_inter = -bucket_low * bucket_scale;
  9838. std::vector<int> bucket_idx(candidates->size);
  9839. std::vector<int> histo(nbuckets, 0);
  9840. for (int i = 0; i < (int)candidates->size; ++i) {
  9841. const float val = candidates->data[i].logit;
  9842. int ib = int(bucket_scale * val + bucker_inter); //nbuckets * (val - bucket_low) / (bucket_high - bucket_low);
  9843. ib = std::max(0, std::min(nbuckets-1, ib));
  9844. bucket_idx[i] = ib;
  9845. ++histo[ib];
  9846. }
  9847. int nhave = 0;
  9848. int ib = nbuckets - 1;
  9849. for ( ; ib >= 0; --ib) {
  9850. nhave += histo[ib];
  9851. if (nhave >= k) break;
  9852. }
  9853. std::vector<llama_token_data> tmp_tokens(nhave);
  9854. auto ptr = tmp_tokens.data();
  9855. std::vector<llama_token_data*> bucket_ptrs;
  9856. bucket_ptrs.reserve(nbuckets - ib);
  9857. for (int j = nbuckets - 1; j >= ib; --j) {
  9858. bucket_ptrs.push_back(ptr);
  9859. ptr += histo[j];
  9860. }
  9861. for (int i = 0; i < (int)candidates->size; ++i) {
  9862. int j = bucket_idx[i];
  9863. if (j >= ib) {
  9864. *bucket_ptrs[nbuckets-1-j]++ = candidates->data[i];
  9865. }
  9866. }
  9867. ptr = tmp_tokens.data();
  9868. int ndone = 0;
  9869. for (int j = nbuckets-1; j > ib; --j) {
  9870. std::sort(ptr, ptr + histo[j], comp);
  9871. ptr += histo[j];
  9872. ndone += histo[j];
  9873. }
  9874. std::partial_sort(ptr, ptr + k - ndone, ptr + histo[ib], comp);
  9875. std::memcpy(candidates->data, tmp_tokens.data(), k*sizeof(llama_token_data));
  9876. }
  9877. candidates->sorted = true;
  9878. }
  9879. candidates->size = k;
  9880. if (ctx) {
  9881. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9882. }
  9883. }
  9884. void llama_sample_top_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  9885. if (p >= 1.0f) {
  9886. return;
  9887. }
  9888. llama_sample_softmax(ctx, candidates);
  9889. const int64_t t_start_sample_us = ggml_time_us();
  9890. // Compute the cumulative probabilities
  9891. float cum_sum = 0.0f;
  9892. size_t last_idx = candidates->size;
  9893. for (size_t i = 0; i < candidates->size; ++i) {
  9894. cum_sum += candidates->data[i].p;
  9895. // Check if the running sum is at least p or if we have kept at least min_keep tokens
  9896. // we set the last index to i+1 to indicate that the current iterate should be included in the set
  9897. if (cum_sum >= p && i + 1 >= min_keep) {
  9898. last_idx = i + 1;
  9899. break;
  9900. }
  9901. }
  9902. // Resize the output vector to keep only the top-p tokens
  9903. candidates->size = last_idx;
  9904. if (ctx) {
  9905. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9906. }
  9907. }
  9908. void llama_sample_min_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  9909. if (p <= 0.0f || !candidates->size) {
  9910. return;
  9911. }
  9912. const int64_t t_start_sample_us = ggml_time_us();
  9913. bool min_p_applied = false;
  9914. // if the candidates aren't sorted, try the unsorted implementation first
  9915. if (!candidates->sorted) {
  9916. std::vector<llama_token_data> filtered_tokens;
  9917. float max_logit = -FLT_MAX;
  9918. for (size_t i = 0; i < candidates->size; ++i) {
  9919. max_logit = std::max(max_logit, candidates->data[i].logit);
  9920. }
  9921. const float min_logit = max_logit + logf(p); // min logit for p_i >= p * p_max
  9922. for (size_t i = 0; i < candidates->size; ++i) {
  9923. if (candidates->data[i].logit >= min_logit) {
  9924. filtered_tokens.push_back(candidates->data[i]);
  9925. }
  9926. }
  9927. // if we have enough values the operation was a success
  9928. if (filtered_tokens.size() >= min_keep) {
  9929. memcpy(candidates->data, filtered_tokens.data(), filtered_tokens.size()*sizeof(llama_token_data));
  9930. candidates->size = filtered_tokens.size();
  9931. min_p_applied = true;
  9932. }
  9933. }
  9934. // if the candidates are sorted or the unsorted implementation failed, use this implementation
  9935. if (!min_p_applied) {
  9936. // Sort the logits in descending order
  9937. if (!candidates->sorted) {
  9938. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  9939. return a.logit > b.logit;
  9940. });
  9941. candidates->sorted = true;
  9942. }
  9943. const float min_logit = candidates->data[0].logit + logf(p); // min logit for p_i >= p * p_max
  9944. size_t i = 1; // first token always matches
  9945. for (; i < candidates->size; ++i) {
  9946. if (candidates->data[i].logit < min_logit && i >= min_keep) {
  9947. break; // prob too small
  9948. }
  9949. }
  9950. // Resize the output vector to keep only the matching tokens
  9951. candidates->size = i;
  9952. }
  9953. if (ctx) {
  9954. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9955. }
  9956. }
  9957. void llama_sample_tail_free(struct llama_context * ctx, llama_token_data_array * candidates, float z, size_t min_keep) {
  9958. if (z >= 1.0f || candidates->size <= 2) {
  9959. return;
  9960. }
  9961. llama_sample_softmax(nullptr, candidates);
  9962. const int64_t t_start_sample_us = ggml_time_us();
  9963. // Compute the first and second derivatives
  9964. std::vector<float> first_derivatives(candidates->size - 1);
  9965. std::vector<float> second_derivatives(candidates->size - 2);
  9966. for (size_t i = 0; i < first_derivatives.size(); ++i) {
  9967. first_derivatives[i] = candidates->data[i].p - candidates->data[i + 1].p;
  9968. }
  9969. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  9970. second_derivatives[i] = first_derivatives[i] - first_derivatives[i + 1];
  9971. }
  9972. // Calculate absolute value of second derivatives
  9973. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  9974. second_derivatives[i] = std::abs(second_derivatives[i]);
  9975. }
  9976. // Normalize the second derivatives
  9977. {
  9978. const float second_derivatives_sum = std::accumulate(second_derivatives.begin(), second_derivatives.end(), 0.0f);
  9979. if (second_derivatives_sum > 1e-6f) {
  9980. for (float & value : second_derivatives) {
  9981. value /= second_derivatives_sum;
  9982. }
  9983. } else {
  9984. for (float & value : second_derivatives) {
  9985. value = 1.0f / second_derivatives.size();
  9986. }
  9987. }
  9988. }
  9989. float cum_sum = 0.0f;
  9990. size_t last_idx = candidates->size;
  9991. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  9992. cum_sum += second_derivatives[i];
  9993. // Check if the running sum is greater than z or if we have kept at least min_keep tokens
  9994. if (cum_sum > z && i >= min_keep) {
  9995. last_idx = i;
  9996. break;
  9997. }
  9998. }
  9999. // Resize the output vector to keep only the tokens above the tail location
  10000. candidates->size = last_idx;
  10001. if (ctx) {
  10002. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10003. }
  10004. }
  10005. void llama_sample_typical(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  10006. // Reference implementation:
  10007. // https://github.com/huggingface/transformers/compare/main...cimeister:typical-sampling:typical-pr
  10008. if (p >= 1.0f) {
  10009. return;
  10010. }
  10011. // Compute the softmax of logits and calculate entropy
  10012. llama_sample_softmax(nullptr, candidates);
  10013. const int64_t t_start_sample_us = ggml_time_us();
  10014. float entropy = 0.0f;
  10015. for (size_t i = 0; i < candidates->size; ++i) {
  10016. entropy += -candidates->data[i].p * logf(candidates->data[i].p);
  10017. }
  10018. // Compute the absolute difference between negative log probability and entropy for each candidate
  10019. std::vector<float> shifted_scores;
  10020. for (size_t i = 0; i < candidates->size; ++i) {
  10021. float shifted_score = fabsf(-logf(candidates->data[i].p) - entropy);
  10022. shifted_scores.push_back(shifted_score);
  10023. }
  10024. // Sort tokens based on the shifted_scores and their corresponding indices
  10025. std::vector<size_t> indices(candidates->size);
  10026. std::iota(indices.begin(), indices.end(), 0);
  10027. std::sort(indices.begin(), indices.end(), [&](size_t a, size_t b) {
  10028. return shifted_scores[a] < shifted_scores[b];
  10029. });
  10030. // Compute the cumulative probabilities
  10031. float cum_sum = 0.0f;
  10032. size_t last_idx = indices.size();
  10033. for (size_t i = 0; i < indices.size(); ++i) {
  10034. size_t idx = indices[i];
  10035. cum_sum += candidates->data[idx].p;
  10036. // Check if the running sum is greater than typical or if we have kept at least min_keep tokens
  10037. if (cum_sum > p && i >= min_keep - 1) {
  10038. last_idx = i + 1;
  10039. break;
  10040. }
  10041. }
  10042. // Resize the output vector to keep only the locally typical tokens
  10043. std::vector<llama_token_data> new_candidates;
  10044. for (size_t i = 0; i < last_idx; ++i) {
  10045. size_t idx = indices[i];
  10046. new_candidates.push_back(candidates->data[idx]);
  10047. }
  10048. // Replace the data in candidates with the new_candidates data
  10049. std::copy(new_candidates.begin(), new_candidates.end(), candidates->data);
  10050. candidates->size = new_candidates.size();
  10051. candidates->sorted = false;
  10052. if (ctx) {
  10053. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10054. }
  10055. }
  10056. void llama_sample_entropy(struct llama_context * ctx, llama_token_data_array * candidates_p, float min_temp, float max_temp, float exponent_val) {
  10057. const int64_t t_start_sample_us = ggml_time_us();
  10058. // no need to do anything if there is only one (or zero) candidates
  10059. if(candidates_p->size <= 1) {
  10060. return;
  10061. }
  10062. // Calculate maximum possible entropy
  10063. float max_entropy = -logf(1.0f / candidates_p->size);
  10064. llama_sample_softmax(nullptr, candidates_p);
  10065. // Calculate entropy of the softmax probabilities
  10066. float entropy = 0.0f;
  10067. for (size_t i = 0; i < candidates_p->size; ++i) {
  10068. float prob = candidates_p->data[i].p;
  10069. if (prob > 0.0f) { // Ensure no log(0)
  10070. entropy -= prob * logf(prob);
  10071. }
  10072. }
  10073. // Normalize the entropy (max_entropy cannot be 0 here because we checked candidates_p->size != 1 above)
  10074. float normalized_entropy = entropy / max_entropy;
  10075. // Map the normalized entropy to the desired temperature range using the power function
  10076. float dyn_temp = min_temp + (max_temp - min_temp) * powf(normalized_entropy, exponent_val);
  10077. #ifdef DEBUG
  10078. LLAMA_LOG_INFO("Your text maxtemp value is: %f\n", max_temp);
  10079. LLAMA_LOG_INFO("Entropy: %f\n", entropy);
  10080. LLAMA_LOG_INFO("Max Possible Entropy: %f\n", max_entropy);
  10081. LLAMA_LOG_INFO("Normalized Entropy: %f\n", normalized_entropy);
  10082. LLAMA_LOG_INFO("Exponent: %f\n", exponent_val);
  10083. LLAMA_LOG_INFO("Dynamic Temperature (dyn_temp): %f\n", dyn_temp);
  10084. #endif
  10085. // Apply the dynamically calculated temperature scaling
  10086. for (size_t i = 0; i < candidates_p->size; ++i) {
  10087. candidates_p->data[i].logit /= dyn_temp;
  10088. }
  10089. // Re-compute softmax probabilities after scaling logits with dynamic temperature
  10090. double max_l_double = candidates_p->data[0].logit;
  10091. double cum_sum_double = 0.0;
  10092. for (size_t i = 0; i < candidates_p->size; ++i) {
  10093. double p = exp(candidates_p->data[i].logit - max_l_double);
  10094. candidates_p->data[i].p = p; // Store the scaled probability
  10095. cum_sum_double += p;
  10096. }
  10097. for (size_t i = 0; i < candidates_p->size; ++i) {
  10098. candidates_p->data[i].p /= cum_sum_double; // Re-normalize the probabilities
  10099. }
  10100. #ifdef DEBUG
  10101. // Print the updated top 25 probabilities after temperature scaling
  10102. LLAMA_LOG_INFO("\nUpdated Top 25 Probabilities After Dynamic Temperature Scaling (in percentages):\n");
  10103. for (size_t i = 0; i < 25 && i < candidates_p->size; ++i) {
  10104. LLAMA_LOG_INFO("Token %zu: %f%%\n", i + 1, candidates_p->data[i].p * 100.0f);
  10105. }
  10106. #endif
  10107. if (ctx) {
  10108. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10109. }
  10110. }
  10111. void llama_sample_temp(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  10112. const int64_t t_start_sample_us = ggml_time_us();
  10113. for (size_t i = 0; i < candidates_p->size; ++i) {
  10114. candidates_p->data[i].logit /= temp;
  10115. }
  10116. if (ctx) {
  10117. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10118. }
  10119. }
  10120. void llama_sample_repetition_penalties(
  10121. struct llama_context * ctx,
  10122. llama_token_data_array * candidates,
  10123. const llama_token * last_tokens,
  10124. size_t penalty_last_n,
  10125. float penalty_repeat,
  10126. float penalty_freq,
  10127. float penalty_present) {
  10128. if (penalty_last_n == 0 || (penalty_repeat == 1.0f && penalty_freq == 0.0f && penalty_present == 0.0f)) {
  10129. return;
  10130. }
  10131. const int64_t t_start_sample_us = ggml_time_us();
  10132. // Create a frequency map to count occurrences of each token in last_tokens
  10133. std::unordered_map<llama_token, int> token_count;
  10134. for (size_t i = 0; i < penalty_last_n; ++i) {
  10135. token_count[last_tokens[i]]++;
  10136. }
  10137. // Apply frequency and presence penalties to the candidates
  10138. for (size_t i = 0; i < candidates->size; ++i) {
  10139. const auto token_iter = token_count.find(candidates->data[i].id);
  10140. if (token_iter == token_count.end()) {
  10141. continue;
  10142. }
  10143. const int count = token_iter->second;
  10144. // 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.
  10145. // This is common fix for this problem, which is to multiply by the penalty instead of dividing.
  10146. if (candidates->data[i].logit <= 0) {
  10147. candidates->data[i].logit *= penalty_repeat;
  10148. } else {
  10149. candidates->data[i].logit /= penalty_repeat;
  10150. }
  10151. candidates->data[i].logit -= float(count) * penalty_freq + float(count > 0) * penalty_present;
  10152. }
  10153. candidates->sorted = false;
  10154. if (ctx) {
  10155. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10156. }
  10157. }
  10158. void llama_sample_grammar(struct llama_context * ctx, llama_token_data_array * candidates, const struct llama_grammar * grammar) {
  10159. GGML_ASSERT(ctx);
  10160. const int64_t t_start_sample_us = ggml_time_us();
  10161. bool allow_eos = false;
  10162. for (const auto & stack : grammar->stacks) {
  10163. if (stack.empty()) {
  10164. allow_eos = true;
  10165. break;
  10166. }
  10167. }
  10168. const llama_token eos = llama_token_eos(&ctx->model);
  10169. std::vector<std::pair<std::vector<uint32_t>, llama_partial_utf8>> candidates_decoded;
  10170. candidates_decoded.reserve(candidates->size);
  10171. std::vector<llama_grammar_candidate> candidates_grammar;
  10172. candidates_grammar.reserve(candidates->size);
  10173. for (size_t i = 0; i < candidates->size; ++i) {
  10174. const llama_token id = candidates->data[i].id;
  10175. const std::string piece = llama_token_to_piece(ctx, id);
  10176. if (id == eos) {
  10177. if (!allow_eos) {
  10178. candidates->data[i].logit = -INFINITY;
  10179. }
  10180. } else if (piece.empty() || piece[0] == 0) {
  10181. candidates->data[i].logit = -INFINITY;
  10182. } else {
  10183. candidates_decoded.push_back(decode_utf8(piece, grammar->partial_utf8));
  10184. candidates_grammar.push_back({ i, candidates_decoded.back().first.data(), candidates_decoded.back().second });
  10185. }
  10186. }
  10187. const auto rejects = llama_grammar_reject_candidates(grammar->rules, grammar->stacks, candidates_grammar);
  10188. for (const auto & reject : rejects) {
  10189. candidates->data[reject.index].logit = -INFINITY;
  10190. }
  10191. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10192. }
  10193. static void llama_log_softmax(float * array, size_t size) {
  10194. float max_l = *std::max_element(array, array + size);
  10195. float sum = 0.f;
  10196. for (size_t i = 0; i < size; ++i) {
  10197. float p = expf(array[i] - max_l);
  10198. sum += p;
  10199. array[i] = p;
  10200. }
  10201. for (size_t i = 0; i < size; ++i) {
  10202. array[i] = logf(array[i] / sum);
  10203. }
  10204. }
  10205. void llama_sample_apply_guidance(
  10206. struct llama_context * ctx,
  10207. float * logits,
  10208. float * logits_guidance,
  10209. float scale) {
  10210. GGML_ASSERT(ctx);
  10211. const auto t_start_sample_us = ggml_time_us();
  10212. const auto n_vocab = llama_n_vocab(llama_get_model(ctx));
  10213. llama_log_softmax(logits, n_vocab);
  10214. llama_log_softmax(logits_guidance, n_vocab);
  10215. for (int i = 0; i < n_vocab; ++i) {
  10216. auto & l = logits[i];
  10217. const auto & g = logits_guidance[i];
  10218. l = scale * (l - g) + g;
  10219. }
  10220. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10221. }
  10222. llama_token llama_sample_token_mirostat(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, int32_t m, float * mu) {
  10223. GGML_ASSERT(ctx);
  10224. auto N = float(llama_n_vocab(llama_get_model(ctx)));
  10225. int64_t t_start_sample_us;
  10226. t_start_sample_us = ggml_time_us();
  10227. llama_sample_softmax(nullptr, candidates);
  10228. // Estimate s_hat using the most probable m tokens
  10229. float s_hat = 0.0;
  10230. float sum_ti_bi = 0.0;
  10231. float sum_ti_sq = 0.0;
  10232. for (size_t i = 0; i < size_t(m - 1) && i < candidates->size - 1; ++i) {
  10233. float t_i = logf(float(i + 2) / float(i + 1));
  10234. float b_i = logf(candidates->data[i].p / candidates->data[i + 1].p);
  10235. sum_ti_bi += t_i * b_i;
  10236. sum_ti_sq += t_i * t_i;
  10237. }
  10238. s_hat = sum_ti_bi / sum_ti_sq;
  10239. // Compute k from the estimated s_hat and target surprise value
  10240. float epsilon_hat = s_hat - 1;
  10241. float k = powf((epsilon_hat * powf(2, *mu)) / (1 - powf(N, -epsilon_hat)), 1 / s_hat);
  10242. // Sample the next word X using top-k sampling
  10243. llama_sample_top_k(nullptr, candidates, int(k), 1);
  10244. if (ctx) {
  10245. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10246. }
  10247. llama_token X = llama_sample_token(ctx, candidates);
  10248. t_start_sample_us = ggml_time_us();
  10249. // Compute error as the difference between observed surprise and target surprise value
  10250. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  10251. return candidate.id == X;
  10252. }));
  10253. float observed_surprise = -log2f(candidates->data[X_idx].p);
  10254. float e = observed_surprise - tau;
  10255. // Update mu using the learning rate and error
  10256. *mu = *mu - eta * e;
  10257. if (ctx) {
  10258. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10259. }
  10260. return X;
  10261. }
  10262. llama_token llama_sample_token_mirostat_v2(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, float * mu) {
  10263. int64_t t_start_sample_us;
  10264. t_start_sample_us = ggml_time_us();
  10265. llama_sample_softmax(ctx, candidates);
  10266. // Truncate the words with surprise values greater than mu
  10267. candidates->size = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  10268. return -log2f(candidate.p) > *mu;
  10269. }));
  10270. if (candidates->size == 0) {
  10271. candidates->size = 1;
  10272. }
  10273. if (ctx) {
  10274. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10275. }
  10276. // Normalize the probabilities of the remaining words
  10277. llama_sample_softmax(ctx, candidates);
  10278. // Sample the next word X from the remaining words
  10279. llama_token X = llama_sample_token(ctx, candidates);
  10280. t_start_sample_us = ggml_time_us();
  10281. // Compute error as the difference between observed surprise and target surprise value
  10282. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  10283. return candidate.id == X;
  10284. }));
  10285. float observed_surprise = -log2f(candidates->data[X_idx].p);
  10286. float e = observed_surprise - tau;
  10287. // Update mu using the learning rate and error
  10288. *mu = *mu - eta * e;
  10289. if (ctx) {
  10290. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10291. }
  10292. return X;
  10293. }
  10294. llama_token llama_sample_token_greedy(struct llama_context * ctx, llama_token_data_array * candidates) {
  10295. const int64_t t_start_sample_us = ggml_time_us();
  10296. // Find max element
  10297. auto * max_iter = std::max_element(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  10298. return a.logit < b.logit;
  10299. });
  10300. llama_token result = max_iter->id;
  10301. if (ctx) {
  10302. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10303. ctx->n_sample++;
  10304. }
  10305. return result;
  10306. }
  10307. llama_token llama_sample_token(struct llama_context * ctx, llama_token_data_array * candidates) {
  10308. GGML_ASSERT(ctx);
  10309. const int64_t t_start_sample_us = ggml_time_us();
  10310. llama_sample_softmax(nullptr, candidates);
  10311. std::vector<float> probs;
  10312. probs.reserve(candidates->size);
  10313. for (size_t i = 0; i < candidates->size; ++i) {
  10314. probs.push_back(candidates->data[i].p);
  10315. }
  10316. std::discrete_distribution<> dist(probs.begin(), probs.end());
  10317. auto & rng = ctx->rng;
  10318. int idx = dist(rng);
  10319. llama_token result = candidates->data[idx].id;
  10320. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10321. ctx->n_sample++;
  10322. return result;
  10323. }
  10324. void llama_grammar_accept_token(struct llama_context * ctx, struct llama_grammar * grammar, llama_token token) {
  10325. const int64_t t_start_sample_us = ggml_time_us();
  10326. if (token == llama_token_eos(&ctx->model)) {
  10327. for (const auto & stack : grammar->stacks) {
  10328. if (stack.empty()) {
  10329. return;
  10330. }
  10331. }
  10332. GGML_ASSERT(false);
  10333. }
  10334. const std::string piece = llama_token_to_piece(ctx, token);
  10335. // Note terminating 0 in decoded string
  10336. const auto decoded = decode_utf8(piece, grammar->partial_utf8);
  10337. const auto & code_points = decoded.first;
  10338. for (auto it = code_points.begin(), end = code_points.end() - 1; it != end; ++it) {
  10339. grammar->stacks = llama_grammar_accept(grammar->rules, grammar->stacks, *it);
  10340. }
  10341. grammar->partial_utf8 = decoded.second;
  10342. GGML_ASSERT(!grammar->stacks.empty());
  10343. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10344. }
  10345. //
  10346. // Beam search
  10347. //
  10348. struct llama_beam {
  10349. std::vector<llama_token> tokens;
  10350. float p; // Cumulative beam probability (renormalized relative to all beams)
  10351. bool eob; // Initialize end-of-beam to false. Callback sets this to true.
  10352. // Sort beams by probability. In case of ties, prefer beams at eob.
  10353. bool operator<(const llama_beam & rhs) const {
  10354. return std::make_pair(p, eob) < std::make_pair(rhs.p, rhs.eob);
  10355. }
  10356. // Shift off first n tokens and discard them.
  10357. void shift_tokens(const size_t n) {
  10358. if (n) {
  10359. std::copy(tokens.begin() + n, tokens.end(), tokens.begin());
  10360. tokens.resize(tokens.size() - n);
  10361. }
  10362. }
  10363. llama_beam_view view() const { return {tokens.data(), tokens.size(), p, eob}; }
  10364. };
  10365. // A struct for calculating logit-related info.
  10366. struct llama_logit_info {
  10367. const float * const logits;
  10368. const int n_vocab;
  10369. const float max_l;
  10370. const float normalizer;
  10371. struct sum_exp {
  10372. float max_l;
  10373. float operator()(float sum, float l) const { return sum + std::exp(l - max_l); }
  10374. };
  10375. llama_logit_info(llama_context * ctx)
  10376. : logits(llama_get_logits(ctx))
  10377. , n_vocab(llama_n_vocab(llama_get_model(ctx)))
  10378. , max_l(*std::max_element(logits, logits + n_vocab))
  10379. , normalizer(1.0f / std::accumulate(logits, logits + n_vocab, 0.0f, sum_exp{max_l}))
  10380. { }
  10381. llama_token_data get_token_data(const llama_token token_id) const {
  10382. constexpr auto p = std::numeric_limits<float>::quiet_NaN(); // never used
  10383. return {token_id, logits[token_id], p};
  10384. }
  10385. // Return top k token_data by logit.
  10386. std::vector<llama_token_data> top_k(size_t k) {
  10387. std::vector<llama_token_data> min_heap; // min-heap by logit
  10388. const llama_token k_min = std::min(static_cast<llama_token>(k), n_vocab);
  10389. min_heap.reserve(k_min);
  10390. for (llama_token token_id = 0 ; token_id < k_min ; ++token_id) {
  10391. min_heap.push_back(get_token_data(token_id));
  10392. }
  10393. auto comp = [](const llama_token_data & a, const llama_token_data & b) { return a.logit > b.logit; };
  10394. std::make_heap(min_heap.begin(), min_heap.end(), comp);
  10395. for (llama_token token_id = k_min ; token_id < n_vocab ; ++token_id) {
  10396. if (min_heap.front().logit < logits[token_id]) {
  10397. std::pop_heap(min_heap.begin(), min_heap.end(), comp);
  10398. min_heap.back().id = token_id;
  10399. min_heap.back().logit = logits[token_id];
  10400. std::push_heap(min_heap.begin(), min_heap.end(), comp);
  10401. }
  10402. }
  10403. return min_heap;
  10404. }
  10405. float probability_from_logit(float logit) const {
  10406. return normalizer * std::exp(logit - max_l);
  10407. }
  10408. };
  10409. struct llama_beam_search_data {
  10410. llama_context * ctx;
  10411. size_t n_beams;
  10412. int n_past;
  10413. int n_predict;
  10414. std::vector<llama_beam> beams;
  10415. std::vector<llama_beam> next_beams;
  10416. // Re-calculated on each loop iteration
  10417. size_t common_prefix_length;
  10418. // Used to communicate to/from callback on beams state.
  10419. std::vector<llama_beam_view> beam_views;
  10420. llama_beam_search_data(llama_context * ctx, size_t n_beams, int n_past, int n_predict)
  10421. : ctx(ctx)
  10422. , n_beams(n_beams)
  10423. , n_past(n_past)
  10424. , n_predict(n_predict)
  10425. , beam_views(n_beams) {
  10426. beams.reserve(n_beams);
  10427. next_beams.reserve(n_beams);
  10428. }
  10429. // Collapse beams to a single beam given by index.
  10430. void collapse_beams(const size_t beam_idx) {
  10431. if (0u < beam_idx) {
  10432. std::swap(beams[0], beams[beam_idx]);
  10433. }
  10434. beams.resize(1);
  10435. }
  10436. // Min-heaps are used to efficiently collect the top-k elements (k=n_beams).
  10437. // The repetitive patterns below reflect the 2 stages of heaps:
  10438. // * Gather elements until the vector is full, then call std::make_heap() on it.
  10439. // * If the heap is full and a new element is found that should be included, pop the
  10440. // least element to the back(), replace it with the new, then push it into the heap.
  10441. void fill_next_beams_by_top_probabilities(llama_beam & beam) {
  10442. // Min-heaps use a greater-than comparator.
  10443. const auto comp = [](const llama_beam & a, const llama_beam & b) { return a.p > b.p; };
  10444. if (beam.eob) {
  10445. // beam is at end-of-sentence, so just copy it to next_beams if its probability is high enough.
  10446. if (next_beams.size() < n_beams) {
  10447. next_beams.push_back(std::move(beam));
  10448. if (next_beams.size() == n_beams) {
  10449. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  10450. }
  10451. } else if (next_beams.front().p < beam.p) {
  10452. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  10453. next_beams.back() = std::move(beam);
  10454. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  10455. }
  10456. } else {
  10457. // beam is not at end-of-sentence, so branch with next top_k tokens.
  10458. if (!beam.tokens.empty()) {
  10459. llama_decode(ctx, llama_batch_get_one(beam.tokens.data(), beam.tokens.size(), n_past, 0));
  10460. }
  10461. llama_logit_info logit_info(ctx);
  10462. std::vector<llama_token_data> next_tokens = logit_info.top_k(n_beams);
  10463. size_t i=0;
  10464. if (next_beams.size() < n_beams) {
  10465. for (; next_beams.size() < n_beams ; ++i) {
  10466. llama_beam next_beam = beam;
  10467. next_beam.tokens.push_back(next_tokens[i].id);
  10468. next_beam.p *= logit_info.probability_from_logit(next_tokens[i].logit);
  10469. next_beams.push_back(std::move(next_beam));
  10470. }
  10471. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  10472. } else {
  10473. for (; next_beams.front().p == 0.0f ; ++i) {
  10474. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  10475. next_beams.back() = beam;
  10476. next_beams.back().tokens.push_back(next_tokens[i].id);
  10477. next_beams.back().p *= logit_info.probability_from_logit(next_tokens[i].logit);
  10478. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  10479. }
  10480. }
  10481. for (; i < n_beams ; ++i) {
  10482. const float next_p = beam.p * logit_info.probability_from_logit(next_tokens[i].logit);
  10483. if (next_beams.front().p < next_p) {
  10484. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  10485. next_beams.back() = beam;
  10486. next_beams.back().tokens.push_back(next_tokens[i].id);
  10487. next_beams.back().p = next_p;
  10488. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  10489. }
  10490. }
  10491. }
  10492. }
  10493. // Find common_prefix_length based on beams.
  10494. // Requires beams is not empty.
  10495. size_t find_common_prefix_length() {
  10496. size_t common_prefix_length = beams[0].tokens.size();
  10497. for (size_t i = 1 ; i < beams.size() ; ++i) {
  10498. common_prefix_length = std::min(common_prefix_length, beams[i].tokens.size());
  10499. for (size_t j = 0 ; j < common_prefix_length ; ++j) {
  10500. if (beams[0].tokens[j] != beams[i].tokens[j]) {
  10501. common_prefix_length = j;
  10502. break;
  10503. }
  10504. }
  10505. }
  10506. return common_prefix_length;
  10507. }
  10508. // Construct beams_state to send back to caller via the callback function.
  10509. // Side effect: set common_prefix_length = find_common_prefix_length();
  10510. llama_beams_state get_beams_state(const bool last_call) {
  10511. for (size_t i = 0 ; i < beams.size() ; ++i) {
  10512. beam_views[i] = beams[i].view();
  10513. }
  10514. common_prefix_length = find_common_prefix_length();
  10515. return {beam_views.data(), beams.size(), common_prefix_length, last_call};
  10516. }
  10517. // Loop:
  10518. // * while i < n_predict, AND
  10519. // * any of the beams have not yet reached end-of-beam (eob), AND
  10520. // * the highest probability beam(s) (plural in case of ties) are not at end-of-sentence
  10521. // (since all other beam probabilities can only decrease)
  10522. void loop(const llama_beam_search_callback_fn_t callback, void * const callback_data) {
  10523. beams.push_back({{}, 1.0f, false}); // Start with one empty beam w/ probability = 1.0 and !eob.
  10524. const auto not_eob = [](const llama_beam & beam) { return !beam.eob; };
  10525. for (int i = 0 ; i < n_predict && std::any_of(beams.begin(),beams.end(),not_eob) &&
  10526. !beams[top_beam_index()].eob ; ++i) {
  10527. callback(callback_data, get_beams_state(false)); // Sets common_prefix_length
  10528. update_beams_from_beam_views(); // Update values (p,eob) that callback may have changed.
  10529. if (common_prefix_length) {
  10530. llama_decode(ctx, llama_batch_get_one(beams[0].tokens.data(), common_prefix_length, n_past, 0));
  10531. n_past += common_prefix_length;
  10532. }
  10533. // Zero-out next_beam probabilities to place them last in following min-heap.
  10534. std::for_each(next_beams.begin(), next_beams.end(), [](llama_beam & beam) { beam.p = 0.0f; });
  10535. for (llama_beam & beam : beams) {
  10536. beam.shift_tokens(common_prefix_length);
  10537. fill_next_beams_by_top_probabilities(beam);
  10538. }
  10539. // next_beams become the beams of next/final iteration. Swap them to re-use memory.
  10540. beams.swap(next_beams);
  10541. renormalize_beam_probabilities(beams);
  10542. }
  10543. collapse_beams(top_beam_index());
  10544. callback(callback_data, get_beams_state(true));
  10545. }
  10546. // As beams grow, the cumulative probabilities decrease.
  10547. // Renormalize them to avoid floating point underflow.
  10548. static void renormalize_beam_probabilities(std::vector<llama_beam> & beams) {
  10549. const auto sum_p = [](float sum, llama_beam & beam) { return sum + beam.p; };
  10550. const float inv_sum = 1.0f / std::accumulate(beams.begin(), beams.end(), 0.0f, sum_p);
  10551. std::for_each(beams.begin(), beams.end(), [=](llama_beam & beam) { beam.p *= inv_sum; });
  10552. }
  10553. // Assumes beams is non-empty. Uses llama_beam::operator<() for ordering.
  10554. size_t top_beam_index() {
  10555. return std::max_element(beams.begin(), beams.end()) - beams.begin();
  10556. }
  10557. // Copy (p,eob) for each beam which may have been changed by the callback.
  10558. void update_beams_from_beam_views() {
  10559. for (size_t i = 0 ; i < beams.size() ; ++i) {
  10560. beams[i].p = beam_views[i].p;
  10561. beams[i].eob = beam_views[i].eob;
  10562. }
  10563. }
  10564. };
  10565. void llama_beam_search(llama_context * ctx,
  10566. llama_beam_search_callback_fn_t callback, void * callback_data,
  10567. size_t n_beams, int n_past, int n_predict) {
  10568. assert(ctx);
  10569. const int64_t t_start_sample_us = ggml_time_us();
  10570. llama_beam_search_data beam_search_data(ctx, n_beams, n_past, n_predict);
  10571. beam_search_data.loop(callback, callback_data);
  10572. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10573. ctx->n_sample++;
  10574. }
  10575. //
  10576. // quantization
  10577. //
  10578. struct quantize_state_internal {
  10579. const llama_model & model;
  10580. const llama_model_quantize_params * params;
  10581. int n_attention_wv = 0;
  10582. int n_ffn_down = 0;
  10583. int n_ffn_gate = 0;
  10584. int n_ffn_up = 0;
  10585. int i_attention_wv = 0;
  10586. int i_ffn_down = 0;
  10587. int i_ffn_gate = 0;
  10588. int i_ffn_up = 0;
  10589. int n_k_quantized = 0;
  10590. int n_fallback = 0;
  10591. bool has_imatrix = false;
  10592. // used to figure out if a model shares tok_embd with the output weight
  10593. bool has_output = false;
  10594. quantize_state_internal(const llama_model & model, const llama_model_quantize_params * params)
  10595. : model(model)
  10596. , params(params)
  10597. {}
  10598. };
  10599. static void llama_tensor_dequantize_internal(
  10600. struct ggml_tensor * tensor, std::vector<no_init<float>> & output, std::vector<std::thread> & workers,
  10601. const size_t nelements, const int nthread
  10602. ) {
  10603. if (output.size() < nelements) {
  10604. output.resize(nelements);
  10605. }
  10606. float * f32_output = (float *) output.data();
  10607. ggml_type_traits_t qtype;
  10608. if (ggml_is_quantized(tensor->type)) {
  10609. qtype = ggml_internal_get_type_traits(tensor->type);
  10610. if (qtype.to_float == NULL) {
  10611. throw std::runtime_error(format("type %s unsupported for integer quantization: no dequantization available", ggml_type_name(tensor->type)));
  10612. }
  10613. } else if (tensor->type != GGML_TYPE_F16) {
  10614. throw std::runtime_error(format("cannot dequantize/convert tensor type %s", ggml_type_name(tensor->type)));
  10615. }
  10616. if (nthread < 2) {
  10617. if (tensor->type == GGML_TYPE_F16) {
  10618. ggml_fp16_to_fp32_row((ggml_fp16_t *)tensor->data, f32_output, nelements);
  10619. } else if (ggml_is_quantized(tensor->type)) {
  10620. qtype.to_float(tensor->data, f32_output, nelements);
  10621. } else {
  10622. GGML_ASSERT(false); // unreachable
  10623. }
  10624. return;
  10625. }
  10626. size_t block_size = tensor->type == GGML_TYPE_F16 ? 1 : (size_t)ggml_blck_size(tensor->type);
  10627. size_t block_size_bytes = ggml_type_size(tensor->type);
  10628. GGML_ASSERT(nelements % block_size == 0);
  10629. size_t nblocks = nelements / block_size;
  10630. size_t blocks_per_thread = nblocks / nthread;
  10631. size_t spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count
  10632. size_t in_buff_offs = 0;
  10633. size_t out_buff_offs = 0;
  10634. for (int tnum = 0; tnum < nthread; tnum++) {
  10635. size_t thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread
  10636. size_t thr_elems = thr_blocks * block_size; // number of elements for this thread
  10637. size_t thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread
  10638. auto compute = [qtype] (ggml_type typ, uint8_t * inbuf, float * outbuf, int nels) {
  10639. if (typ == GGML_TYPE_F16) {
  10640. ggml_fp16_to_fp32_row((ggml_fp16_t *)inbuf, outbuf, nels);
  10641. } else {
  10642. qtype.to_float(inbuf, outbuf, nels);
  10643. }
  10644. };
  10645. workers.emplace_back(compute, tensor->type, (uint8_t *) tensor->data + in_buff_offs, f32_output + out_buff_offs, thr_elems);
  10646. in_buff_offs += thr_block_bytes;
  10647. out_buff_offs += thr_elems;
  10648. }
  10649. for (auto & w : workers) { w.join(); }
  10650. workers.clear();
  10651. }
  10652. static ggml_type llama_tensor_get_type(quantize_state_internal & qs, ggml_type new_type, const ggml_tensor * tensor, llama_ftype ftype) {
  10653. const std::string name = ggml_get_name(tensor);
  10654. // TODO: avoid hardcoded tensor names - use the TN_* constants
  10655. const llm_arch arch = qs.model.arch;
  10656. const auto tn = LLM_TN(arch);
  10657. auto use_more_bits = [](int i_layer, int num_layers) -> bool {
  10658. return i_layer < num_layers/8 || i_layer >= 7*num_layers/8 || (i_layer - num_layers/8)%3 == 2;
  10659. };
  10660. const int n_expert = std::max(1, (int)qs.model.hparams.n_expert);
  10661. auto layer_info = [n_expert] (int i_layer, int n_layer, const char * name) {
  10662. if (n_expert > 1) {
  10663. // Believe it or not, "experts" in the FFN of Mixtral-8x7B are not consecutive, but iccasionally randomly
  10664. // sprinkled in the model. Hence, simply dividing i_ffn_down by n_expert does not work
  10665. // for getting the current layer as I initially thought, and we need to resort to parsing the
  10666. // tensor name.
  10667. n_layer /= n_expert;
  10668. if (sscanf(name, "blk.%d.", &i_layer) != 1) {
  10669. throw std::runtime_error(format("Failed to determine layer for tensor %s", name));
  10670. }
  10671. if (i_layer < 0 || i_layer >= n_layer) {
  10672. throw std::runtime_error(format("Bad layer %d for tensor %s. Must be in [0, %d)", i_layer, name, n_layer));
  10673. }
  10674. }
  10675. return std::make_pair(i_layer, n_layer);
  10676. };
  10677. // for arches that share the same tensor between the token embeddings and the output, we quantize the token embeddings
  10678. // with the quantization of the output tensor
  10679. if (name == tn(LLM_TENSOR_OUTPUT, "weight") || (!qs.has_output && name == tn(LLM_TENSOR_TOKEN_EMBD, "weight"))) {
  10680. if (qs.params->output_tensor_type < GGML_TYPE_COUNT) {
  10681. new_type = qs.params->output_tensor_type;
  10682. } else {
  10683. int nx = tensor->ne[0];
  10684. if (arch == LLM_ARCH_FALCON || nx % QK_K != 0) {
  10685. new_type = GGML_TYPE_Q8_0;
  10686. }
  10687. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  10688. ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ||
  10689. ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  10690. new_type = GGML_TYPE_Q5_K;
  10691. }
  10692. else if (new_type != GGML_TYPE_Q8_0) {
  10693. new_type = GGML_TYPE_Q6_K;
  10694. }
  10695. }
  10696. } else if (name == "token_embd.weight") {
  10697. if (qs.params->token_embedding_type < GGML_TYPE_COUNT) {
  10698. new_type = qs.params->token_embedding_type;
  10699. } else {
  10700. if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS ||
  10701. ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  10702. new_type = GGML_TYPE_Q2_K;
  10703. }
  10704. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) {
  10705. new_type = GGML_TYPE_IQ3_S;
  10706. }
  10707. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  10708. new_type = GGML_TYPE_IQ3_S;
  10709. }
  10710. }
  10711. } else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S ||
  10712. ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  10713. if (name.find("attn_v.weight") != std::string::npos) {
  10714. if (qs.model.hparams.n_gqa() >= 4 || qs.model.hparams.n_expert >= 4) new_type = GGML_TYPE_Q4_K;
  10715. else new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  10716. ++qs.i_attention_wv;
  10717. }
  10718. else if (qs.model.hparams.n_expert == 8 && name.find("attn_k.weight") != std::string::npos) {
  10719. new_type = GGML_TYPE_Q4_K;
  10720. }
  10721. else if (name.find("ffn_down") != std::string::npos) {
  10722. if (qs.i_ffn_down < qs.n_ffn_down/8) {
  10723. new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  10724. }
  10725. ++qs.i_ffn_down;
  10726. }
  10727. else if (name.find("attn_output.weight") != std::string::npos) {
  10728. if (qs.model.hparams.n_expert == 8) {
  10729. new_type = GGML_TYPE_Q5_K;
  10730. } else {
  10731. if (ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) new_type = GGML_TYPE_IQ2_XXS;
  10732. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) new_type = GGML_TYPE_IQ3_S;
  10733. }
  10734. }
  10735. } else if (name.find("attn_v.weight") != std::string::npos) {
  10736. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) {
  10737. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  10738. }
  10739. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && qs.model.hparams.n_gqa() >= 4) {
  10740. new_type = GGML_TYPE_Q4_K;
  10741. }
  10742. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  10743. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : !qs.has_imatrix ? GGML_TYPE_IQ3_S : GGML_TYPE_IQ3_XXS;
  10744. }
  10745. else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S) && qs.model.hparams.n_gqa() >= 4) {
  10746. new_type = GGML_TYPE_Q4_K;
  10747. }
  10748. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  10749. new_type = GGML_TYPE_Q4_K;
  10750. }
  10751. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  10752. new_type = qs.i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  10753. }
  10754. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  10755. else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && qs.model.hparams.n_gqa() >= 4) {
  10756. new_type = GGML_TYPE_Q5_K;
  10757. }
  10758. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
  10759. use_more_bits(qs.i_attention_wv, qs.n_attention_wv)) new_type = GGML_TYPE_Q6_K;
  10760. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && qs.i_attention_wv < 4) new_type = GGML_TYPE_Q5_K;
  10761. else if (QK_K == 64 && (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S) &&
  10762. (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;
  10763. if (qs.model.type == MODEL_70B) {
  10764. // In the 70B model we have 8 heads sharing the same attn_v weights. As a result, the attn_v.weight tensor is
  10765. // 8x smaller compared to attn_q.weight. Hence, we can get a nice boost in quantization accuracy with
  10766. // nearly negligible increase in model size by quantizing this tensor with more bits:
  10767. if (new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K) new_type = GGML_TYPE_Q5_K;
  10768. }
  10769. if (qs.model.hparams.n_expert == 8) {
  10770. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  10771. // TODO: explore better strategies
  10772. new_type = GGML_TYPE_Q8_0;
  10773. }
  10774. ++qs.i_attention_wv;
  10775. } else if (name.find("attn_k.weight") != std::string::npos) {
  10776. if (qs.model.hparams.n_expert == 8) {
  10777. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  10778. // TODO: explore better strategies
  10779. new_type = GGML_TYPE_Q8_0;
  10780. }
  10781. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  10782. new_type = GGML_TYPE_IQ3_XXS;
  10783. }
  10784. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  10785. new_type = GGML_TYPE_IQ2_S;
  10786. }
  10787. } else if (name.find("attn_q.weight") != std::string::npos) {
  10788. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  10789. new_type = GGML_TYPE_IQ3_XXS;
  10790. }
  10791. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  10792. new_type = GGML_TYPE_IQ2_S;
  10793. }
  10794. } else if (name.find("ffn_down") != std::string::npos) {
  10795. auto info = layer_info(qs.i_ffn_down, qs.n_ffn_down, name.c_str());
  10796. int i_layer = info.first, n_layer = info.second;
  10797. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  10798. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S) {
  10799. if (i_layer < n_layer/8) new_type = GGML_TYPE_Q4_K;
  10800. }
  10801. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS && !qs.has_imatrix) {
  10802. new_type = i_layer < n_layer/8 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  10803. }
  10804. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  10805. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q5_K
  10806. : arch != LLM_ARCH_FALCON || use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q4_K
  10807. : GGML_TYPE_Q3_K;
  10808. }
  10809. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M && (i_layer < n_layer/8 ||
  10810. (qs.model.hparams.n_expert == 8 && use_more_bits(i_layer, n_layer)))) {
  10811. new_type = GGML_TYPE_Q4_K;
  10812. }
  10813. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) {
  10814. new_type = arch == LLM_ARCH_FALCON ? GGML_TYPE_Q4_K : GGML_TYPE_Q5_K;
  10815. }
  10816. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  10817. if (arch == LLM_ARCH_FALCON) {
  10818. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q6_K :
  10819. use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  10820. } else {
  10821. if (use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  10822. }
  10823. }
  10824. else if (i_layer < n_layer/8 && (ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && !qs.has_imatrix) {
  10825. new_type = GGML_TYPE_Q5_K;
  10826. }
  10827. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M && use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  10828. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && arch != LLM_ARCH_FALCON && i_layer < n_layer/8) {
  10829. new_type = GGML_TYPE_Q5_K;
  10830. }
  10831. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_0 || ftype == LLAMA_FTYPE_MOSTLY_Q5_0)
  10832. && qs.has_imatrix && i_layer < n_layer/8) {
  10833. // Guard against craziness in the first few ffn_down layers that can happen even with imatrix for Q4_0/Q5_0.
  10834. // We only do it when an imatrix is provided because a) we want to make sure that one can always get the
  10835. // same quantization as before imatrix stuff, and b) Q4_1/Q5_1 do go crazy on ffn_down without an imatrix.
  10836. new_type = ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ? GGML_TYPE_Q4_1 : GGML_TYPE_Q5_1;
  10837. }
  10838. ++qs.i_ffn_down;
  10839. } else if (name.find("attn_output.weight") != std::string::npos) {
  10840. if (arch != LLM_ARCH_FALCON) {
  10841. if (qs.model.hparams.n_expert == 8) {
  10842. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  10843. ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL ||
  10844. ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S ||
  10845. ftype == LLAMA_FTYPE_MOSTLY_IQ3_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) {
  10846. new_type = GGML_TYPE_Q5_K;
  10847. }
  10848. } else {
  10849. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K ) new_type = GGML_TYPE_Q3_K;
  10850. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) new_type = GGML_TYPE_IQ3_S;
  10851. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M ) new_type = GGML_TYPE_Q4_K;
  10852. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L ) new_type = GGML_TYPE_Q5_K;
  10853. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M ) new_type = GGML_TYPE_Q4_K;
  10854. }
  10855. } else {
  10856. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  10857. }
  10858. }
  10859. else if (name.find("attn_qkv.weight") != std::string::npos) {
  10860. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L || ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  10861. new_type = GGML_TYPE_Q4_K;
  10862. }
  10863. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) new_type = GGML_TYPE_Q5_K;
  10864. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) new_type = GGML_TYPE_Q6_K;
  10865. }
  10866. else if (name.find("ffn_gate") != std::string::npos) {
  10867. auto info = layer_info(qs.i_ffn_gate, qs.n_ffn_gate, name.c_str());
  10868. int i_layer = info.first, n_layer = info.second;
  10869. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  10870. new_type = GGML_TYPE_IQ3_XXS;
  10871. }
  10872. ++qs.i_ffn_gate;
  10873. }
  10874. else if (name.find("ffn_up") != std::string::npos) {
  10875. auto info = layer_info(qs.i_ffn_up, qs.n_ffn_up, name.c_str());
  10876. int i_layer = info.first, n_layer = info.second;
  10877. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  10878. new_type = GGML_TYPE_IQ3_XXS;
  10879. }
  10880. ++qs.i_ffn_up;
  10881. }
  10882. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  10883. //}
  10884. // IK: let's remove this, else Q2_K is almost the same as Q3_K_S
  10885. //else if (name.find("ffn_gate") != std::string::npos || name.find("ffn_up") != std::string::npos) {
  10886. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  10887. //}
  10888. // This can be used to reduce the size of the Q5_K_S model.
  10889. // The associated PPL increase is fully in line with the size reduction
  10890. //else {
  10891. // if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_S) new_type = GGML_TYPE_Q4_K;
  10892. //}
  10893. bool convert_incompatible_tensor = false;
  10894. if (new_type == GGML_TYPE_Q2_K || new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K ||
  10895. new_type == GGML_TYPE_Q5_K || new_type == GGML_TYPE_Q6_K || new_type == GGML_TYPE_IQ4_XS ||
  10896. new_type == GGML_TYPE_IQ2_XS || new_type == GGML_TYPE_IQ2_XXS || new_type == GGML_TYPE_IQ2_S ||
  10897. new_type == GGML_TYPE_IQ3_XXS || new_type == GGML_TYPE_IQ1_S || new_type == GGML_TYPE_IQ3_S ||
  10898. new_type == GGML_TYPE_IQ1_M) {
  10899. int nx = tensor->ne[0];
  10900. int ny = tensor->ne[1];
  10901. if (nx % QK_K != 0) {
  10902. 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));
  10903. convert_incompatible_tensor = true;
  10904. } else {
  10905. ++qs.n_k_quantized;
  10906. }
  10907. }
  10908. if (convert_incompatible_tensor) {
  10909. switch (new_type) {
  10910. case GGML_TYPE_IQ2_XXS:
  10911. case GGML_TYPE_IQ2_XS:
  10912. case GGML_TYPE_IQ2_S:
  10913. case GGML_TYPE_IQ3_XXS:
  10914. case GGML_TYPE_IQ3_S:
  10915. case GGML_TYPE_IQ1_S:
  10916. case GGML_TYPE_IQ1_M:
  10917. case GGML_TYPE_Q2_K:
  10918. case GGML_TYPE_Q3_K:
  10919. case GGML_TYPE_IQ4_XS: new_type = GGML_TYPE_IQ4_NL; break;
  10920. case GGML_TYPE_Q4_K: new_type = GGML_TYPE_Q5_0; break;
  10921. case GGML_TYPE_Q5_K: new_type = GGML_TYPE_Q5_1; break;
  10922. case GGML_TYPE_Q6_K: new_type = GGML_TYPE_Q8_0; break;
  10923. default: throw std::runtime_error("\nUnsupported tensor size encountered\n");
  10924. }
  10925. LLAMA_LOG_WARN(" - using fallback quantization %s\n", ggml_type_name(new_type));
  10926. ++qs.n_fallback;
  10927. }
  10928. return new_type;
  10929. }
  10930. 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) {
  10931. std::mutex mutex;
  10932. int counter = 0;
  10933. size_t new_size = 0;
  10934. if (nthread < 2) {
  10935. // single-thread
  10936. return ggml_quantize_chunk(new_type, f32_data, new_data, 0, nrows, n_per_row, imatrix);
  10937. }
  10938. auto compute = [&mutex, &counter, &new_size, new_type, f32_data, new_data, chunk_size,
  10939. nrows, n_per_row, imatrix]() {
  10940. const int nrows_per_chunk = chunk_size / n_per_row;
  10941. size_t local_size = 0;
  10942. while (true) {
  10943. std::unique_lock<std::mutex> lock(mutex);
  10944. int first_row = counter; counter += nrows_per_chunk;
  10945. if (first_row >= nrows) {
  10946. if (local_size > 0) {
  10947. new_size += local_size;
  10948. }
  10949. break;
  10950. }
  10951. lock.unlock();
  10952. const int this_nrow = std::min(nrows - first_row, nrows_per_chunk);
  10953. local_size += ggml_quantize_chunk(new_type, f32_data, new_data, first_row * n_per_row, this_nrow, n_per_row, imatrix);
  10954. }
  10955. };
  10956. for (int it = 0; it < nthread - 1; ++it) {
  10957. workers.emplace_back(compute);
  10958. }
  10959. compute();
  10960. for (auto & w : workers) { w.join(); }
  10961. workers.clear();
  10962. return new_size;
  10963. }
  10964. static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) {
  10965. ggml_type default_type;
  10966. llama_ftype ftype = params->ftype;
  10967. switch (params->ftype) {
  10968. case LLAMA_FTYPE_MOSTLY_Q4_0: default_type = GGML_TYPE_Q4_0; break;
  10969. case LLAMA_FTYPE_MOSTLY_Q4_1: default_type = GGML_TYPE_Q4_1; break;
  10970. case LLAMA_FTYPE_MOSTLY_Q5_0: default_type = GGML_TYPE_Q5_0; break;
  10971. case LLAMA_FTYPE_MOSTLY_Q5_1: default_type = GGML_TYPE_Q5_1; break;
  10972. case LLAMA_FTYPE_MOSTLY_Q8_0: default_type = GGML_TYPE_Q8_0; break;
  10973. case LLAMA_FTYPE_MOSTLY_F16: default_type = GGML_TYPE_F16; break;
  10974. case LLAMA_FTYPE_ALL_F32: default_type = GGML_TYPE_F32; break;
  10975. // K-quants
  10976. case LLAMA_FTYPE_MOSTLY_Q2_K_S:
  10977. case LLAMA_FTYPE_MOSTLY_Q2_K: default_type = GGML_TYPE_Q2_K; break;
  10978. case LLAMA_FTYPE_MOSTLY_IQ3_XS: default_type = GGML_TYPE_IQ3_S; break;
  10979. case LLAMA_FTYPE_MOSTLY_Q3_K_S:
  10980. case LLAMA_FTYPE_MOSTLY_Q3_K_M:
  10981. case LLAMA_FTYPE_MOSTLY_Q3_K_L: default_type = GGML_TYPE_Q3_K; break;
  10982. case LLAMA_FTYPE_MOSTLY_Q4_K_S:
  10983. case LLAMA_FTYPE_MOSTLY_Q4_K_M: default_type = GGML_TYPE_Q4_K; break;
  10984. case LLAMA_FTYPE_MOSTLY_Q5_K_S:
  10985. case LLAMA_FTYPE_MOSTLY_Q5_K_M: default_type = GGML_TYPE_Q5_K; break;
  10986. case LLAMA_FTYPE_MOSTLY_Q6_K: default_type = GGML_TYPE_Q6_K; break;
  10987. case LLAMA_FTYPE_MOSTLY_IQ2_XXS: default_type = GGML_TYPE_IQ2_XXS; break;
  10988. case LLAMA_FTYPE_MOSTLY_IQ2_XS: default_type = GGML_TYPE_IQ2_XS; break;
  10989. case LLAMA_FTYPE_MOSTLY_IQ2_S: default_type = GGML_TYPE_IQ2_XS; break;
  10990. case LLAMA_FTYPE_MOSTLY_IQ2_M: default_type = GGML_TYPE_IQ2_S; break;
  10991. case LLAMA_FTYPE_MOSTLY_IQ3_XXS: default_type = GGML_TYPE_IQ3_XXS; break;
  10992. case LLAMA_FTYPE_MOSTLY_IQ1_S: default_type = GGML_TYPE_IQ1_S; break;
  10993. case LLAMA_FTYPE_MOSTLY_IQ1_M: default_type = GGML_TYPE_IQ1_M; break;
  10994. case LLAMA_FTYPE_MOSTLY_IQ4_NL: default_type = GGML_TYPE_IQ4_NL; break;
  10995. case LLAMA_FTYPE_MOSTLY_IQ4_XS: default_type = GGML_TYPE_IQ4_XS; break;
  10996. case LLAMA_FTYPE_MOSTLY_IQ3_S: default_type = GGML_TYPE_IQ3_S; break;
  10997. case LLAMA_FTYPE_MOSTLY_IQ3_M: default_type = GGML_TYPE_IQ3_S; break;
  10998. default: throw std::runtime_error(format("invalid output file type %d\n", ftype));
  10999. }
  11000. int nthread = params->nthread;
  11001. if (nthread <= 0) {
  11002. nthread = std::thread::hardware_concurrency();
  11003. }
  11004. // mmap consistently increases speed Linux, and also increases speed on Windows with
  11005. // hot cache. It may cause a slowdown on macOS, possibly related to free memory.
  11006. #if defined(__linux__) || defined(_WIN32)
  11007. constexpr bool use_mmap = true;
  11008. #else
  11009. constexpr bool use_mmap = false;
  11010. #endif
  11011. llama_model_kv_override * kv_overrides = nullptr;
  11012. if (params->kv_overrides) {
  11013. auto v = (std::vector<llama_model_kv_override>*)params->kv_overrides;
  11014. kv_overrides = v->data();
  11015. }
  11016. llama_model_loader ml(fname_inp, use_mmap, kv_overrides);
  11017. ml.init_mappings(false); // no prefetching?
  11018. llama_model model;
  11019. llm_load_arch(ml, model);
  11020. llm_load_hparams(ml, model);
  11021. struct quantize_state_internal qs(model, params);
  11022. if (params->only_copy) {
  11023. ftype = model.ftype;
  11024. }
  11025. const std::unordered_map<std::string, std::vector<float>> * imatrix_data = nullptr;
  11026. if (params->imatrix) {
  11027. imatrix_data = static_cast<const std::unordered_map<std::string, std::vector<float>>*>(params->imatrix);
  11028. if (imatrix_data) {
  11029. LLAMA_LOG_INFO("================================ Have weights data with %d entries\n",int(imatrix_data->size()));
  11030. qs.has_imatrix = true;
  11031. }
  11032. }
  11033. const size_t align = GGUF_DEFAULT_ALIGNMENT;
  11034. struct gguf_context * ctx_out = gguf_init_empty();
  11035. // copy the KV pairs from the input file
  11036. gguf_set_kv (ctx_out, ml.meta);
  11037. gguf_set_val_u32(ctx_out, "general.quantization_version", GGML_QNT_VERSION);
  11038. gguf_set_val_u32(ctx_out, "general.file_type", ftype);
  11039. if (params->kv_overrides) {
  11040. const std::vector<llama_model_kv_override> & overrides = *(const std::vector<llama_model_kv_override> *)params->kv_overrides;
  11041. for (auto & o : overrides) {
  11042. if (o.key[0] == 0) break;
  11043. if (o.tag == LLAMA_KV_OVERRIDE_TYPE_FLOAT) {
  11044. gguf_set_val_f32(ctx_out, o.key, o.float_value);
  11045. } else if (o.tag == LLAMA_KV_OVERRIDE_TYPE_INT) {
  11046. gguf_set_val_i32(ctx_out, o.key, o.int_value);
  11047. } else if (o.tag == LLAMA_KV_OVERRIDE_TYPE_BOOL) {
  11048. gguf_set_val_bool(ctx_out, o.key, o.bool_value);
  11049. } else {
  11050. LLAMA_LOG_WARN("%s: unknown KV override type for key %s\n", __func__, o.key);
  11051. }
  11052. }
  11053. }
  11054. for (int i = 0; i < ml.n_tensors; ++i) {
  11055. const struct ggml_tensor * meta = ml.get_tensor_meta(i);
  11056. const std::string name = ggml_get_name(meta);
  11057. // TODO: avoid hardcoded tensor names - use the TN_* constants
  11058. if (name.find("attn_v.weight") != std::string::npos || name.find("attn_qkv.weight") != std::string::npos) {
  11059. ++qs.n_attention_wv;
  11060. } else if (name.find("ffn_down") != std::string::npos) {
  11061. ++qs.n_ffn_down;
  11062. } else if (name.find("ffn_gate") != std::string::npos) {
  11063. ++qs.n_ffn_gate;
  11064. } else if (name.find("ffn_up") != std::string::npos) {
  11065. ++qs.n_ffn_up;
  11066. } else if (name == LLM_TN(model.arch)(LLM_TENSOR_OUTPUT, "weight")) {
  11067. qs.has_output = true;
  11068. }
  11069. }
  11070. if (qs.n_attention_wv != qs.n_ffn_down || (uint32_t) qs.n_attention_wv != model.hparams.n_layer) {
  11071. LLAMA_LOG_WARN("%s ============ Strange model: n_attention_wv = %d, n_ffn_down = %d, hparams.n_layer = %d\n",
  11072. __func__, qs.n_attention_wv, qs.n_ffn_down, model.hparams.n_layer);
  11073. }
  11074. size_t total_size_org = 0;
  11075. size_t total_size_new = 0;
  11076. std::vector<std::thread> workers;
  11077. workers.reserve(nthread);
  11078. int idx = 0;
  11079. std::vector<no_init<uint8_t>> read_data;
  11080. std::vector<no_init<uint8_t>> work;
  11081. std::vector<no_init<float>> f32_conv_buf;
  11082. // populate the original tensors so we get an initial meta data
  11083. for (int i = 0; i < ml.n_tensors; ++i) {
  11084. const struct ggml_tensor * meta = ml.get_tensor_meta(i);
  11085. gguf_add_tensor(ctx_out, meta);
  11086. }
  11087. std::ofstream fout(fname_out, std::ios::binary);
  11088. fout.exceptions(std::ofstream::failbit); // fail fast on write errors
  11089. const size_t meta_size = gguf_get_meta_size(ctx_out);
  11090. LLAMA_LOG_INFO("%s: meta size = %zu bytes\n", __func__, meta_size);
  11091. // placeholder for the meta data
  11092. ::zeros(fout, meta_size);
  11093. for (int i = 0; i < ml.n_tensors; ++i) {
  11094. struct ggml_tensor * tensor = ml.get_tensor_meta(i);
  11095. const std::string name = ggml_get_name(tensor);
  11096. if (!ml.use_mmap) {
  11097. if (read_data.size() < ggml_nbytes(tensor)) {
  11098. read_data.resize(ggml_nbytes(tensor));
  11099. }
  11100. tensor->data = read_data.data();
  11101. }
  11102. ml.load_data_for(tensor);
  11103. LLAMA_LOG_INFO("[%4d/%4d] %36s - [%s], type = %6s, ",
  11104. ++idx, ml.n_tensors,
  11105. ggml_get_name(tensor),
  11106. llama_format_tensor_shape(tensor).c_str(),
  11107. ggml_type_name(tensor->type));
  11108. // This used to be a regex, but <regex> has an extreme cost to compile times.
  11109. bool quantize = name.rfind("weight") == name.size() - 6; // ends with 'weight'?
  11110. // quantize only 2D tensors
  11111. quantize &= (ggml_n_dims(tensor) == 2);
  11112. quantize &= params->quantize_output_tensor || name != "output.weight";
  11113. quantize &= !params->only_copy;
  11114. // do not quantize expert gating tensors
  11115. // NOTE: can't use LLM_TN here because the layer number is not known
  11116. quantize &= name.find("ffn_gate_inp.weight") == std::string::npos;
  11117. // do not quantize positional embeddings and token types (BERT)
  11118. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_POS_EMBD, "weight");
  11119. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_TOKEN_TYPES, "weight");
  11120. // do not quantize Mamba's small yet 2D weights
  11121. // NOTE: can't use LLM_TN here because the layer number is not known
  11122. quantize &= name.find("ssm_conv1d.weight") == std::string::npos;
  11123. quantize &= name.find("ssm_x.weight") == std::string::npos;
  11124. quantize &= name.find("ssm_dt.weight") == std::string::npos;
  11125. enum ggml_type new_type;
  11126. void * new_data;
  11127. size_t new_size;
  11128. if (quantize) {
  11129. new_type = default_type;
  11130. // get more optimal quantization type based on the tensor shape, layer, etc.
  11131. if (!params->pure && ggml_is_quantized(default_type)) {
  11132. new_type = llama_tensor_get_type(qs, new_type, tensor, ftype);
  11133. }
  11134. else if (params->token_embedding_type < GGML_TYPE_COUNT && strcmp(tensor->name, "token_embd.weight") == 0) {
  11135. new_type = params->token_embedding_type;
  11136. }
  11137. else if (params->output_tensor_type < GGML_TYPE_COUNT && strcmp(tensor->name, "output.weight") == 0) {
  11138. new_type = params->output_tensor_type;
  11139. }
  11140. // If we've decided to quantize to the same type the tensor is already
  11141. // in then there's nothing to do.
  11142. quantize = tensor->type != new_type;
  11143. }
  11144. if (!quantize) {
  11145. new_type = tensor->type;
  11146. new_data = tensor->data;
  11147. new_size = ggml_nbytes(tensor);
  11148. LLAMA_LOG_INFO("size = %8.3f MB\n", ggml_nbytes(tensor)/1024.0/1024.0);
  11149. } else {
  11150. const size_t nelements = ggml_nelements(tensor);
  11151. const float * imatrix = nullptr;
  11152. if (imatrix_data) {
  11153. auto it = imatrix_data->find(tensor->name);
  11154. if (it == imatrix_data->end()) {
  11155. LLAMA_LOG_INFO("\n====== %s: did not find weights for %s\n", __func__, tensor->name);
  11156. } else {
  11157. if (it->second.size() == (size_t)tensor->ne[0]) {
  11158. imatrix = it->second.data();
  11159. } else {
  11160. LLAMA_LOG_INFO("\n====== %s: imatrix size %d is different from tensor size %d for %s\n", __func__,
  11161. int(it->second.size()), int(tensor->ne[0]), tensor->name);
  11162. }
  11163. }
  11164. }
  11165. if ((new_type == GGML_TYPE_IQ2_XXS ||
  11166. new_type == GGML_TYPE_IQ2_XS ||
  11167. new_type == GGML_TYPE_IQ2_S ||
  11168. new_type == GGML_TYPE_IQ1_S ||
  11169. (new_type == GGML_TYPE_IQ1_M && strcmp(tensor->name, "token_embd.weight") && strcmp(tensor->name, "output.weight")) ||
  11170. (new_type == GGML_TYPE_Q2_K && params->ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && strcmp(tensor->name, "token_embd.weight") != 0)) && !imatrix) {
  11171. LLAMA_LOG_ERROR("\n\n============================================================\n");
  11172. LLAMA_LOG_ERROR("Missing importance matrix for tensor %s in a very low-bit quantization\n", tensor->name);
  11173. LLAMA_LOG_ERROR("The result will be garbage, so bailing out\n");
  11174. LLAMA_LOG_ERROR("============================================================\n\n");
  11175. throw std::runtime_error(format("Missing importance matrix for tensor %s in a very low-bit quantization", tensor->name));
  11176. }
  11177. float * f32_data;
  11178. if (tensor->type == GGML_TYPE_F32) {
  11179. f32_data = (float *) tensor->data;
  11180. } else if (ggml_is_quantized(tensor->type) && !params->allow_requantize) {
  11181. throw std::runtime_error(format("requantizing from type %s is disabled", ggml_type_name(tensor->type)));
  11182. } else {
  11183. llama_tensor_dequantize_internal(tensor, f32_conv_buf, workers, nelements, nthread);
  11184. f32_data = (float *) f32_conv_buf.data();
  11185. }
  11186. LLAMA_LOG_INFO("converting to %s .. ", ggml_type_name(new_type));
  11187. fflush(stdout);
  11188. if (work.size() < nelements * 4) {
  11189. work.resize(nelements * 4); // upper bound on size
  11190. }
  11191. new_data = work.data();
  11192. const int n_per_row = tensor->ne[0];
  11193. const int nrows = nelements / n_per_row;
  11194. static const int min_chunk_size = 32 * 512;
  11195. 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);
  11196. const int nchunk = (nelements + chunk_size - 1)/chunk_size;
  11197. const int nthread_use = nthread > 1 ? std::max(1, std::min(nthread, nchunk)) : 1;
  11198. new_size = llama_tensor_quantize_internal(new_type, f32_data, new_data, chunk_size, nrows, n_per_row, imatrix, workers, nthread_use);
  11199. LLAMA_LOG_INFO("size = %8.2f MiB -> %8.2f MiB\n", ggml_nbytes(tensor)/1024.0/1024.0, new_size/1024.0/1024.0);
  11200. }
  11201. total_size_org += ggml_nbytes(tensor);
  11202. total_size_new += new_size;
  11203. // update the gguf meta data as we go
  11204. gguf_set_tensor_type(ctx_out, name.c_str(), new_type);
  11205. gguf_set_tensor_data(ctx_out, name.c_str(), new_data, new_size);
  11206. // write tensor data + padding
  11207. fout.write((const char *) new_data, new_size);
  11208. zeros(fout, GGML_PAD(new_size, align) - new_size);
  11209. }
  11210. // go back to beginning of file and write the updated meta data
  11211. {
  11212. fout.seekp(0);
  11213. std::vector<uint8_t> data(gguf_get_meta_size(ctx_out));
  11214. gguf_get_meta_data(ctx_out, data.data());
  11215. fout.write((const char *) data.data(), data.size());
  11216. }
  11217. fout.close();
  11218. gguf_free(ctx_out);
  11219. LLAMA_LOG_INFO("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  11220. LLAMA_LOG_INFO("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  11221. if (qs.n_fallback > 0) {
  11222. LLAMA_LOG_WARN("%s: WARNING: %d of %d tensor(s) required fallback quantization\n",
  11223. __func__, qs.n_fallback, qs.n_k_quantized + qs.n_fallback);
  11224. }
  11225. }
  11226. static int llama_apply_lora_from_file_internal(
  11227. const struct llama_model & model, const char * path_lora, float scale, const char * path_base_model, int n_threads
  11228. ) {
  11229. LLAMA_LOG_INFO("%s: applying lora adapter from '%s' - please wait ...\n", __func__, path_lora);
  11230. const int64_t t_start_lora_us = ggml_time_us();
  11231. llama_file fin(path_lora, "rb");
  11232. // verify magic and version
  11233. {
  11234. uint32_t magic = fin.read_u32();
  11235. if (magic != LLAMA_FILE_MAGIC_GGLA) {
  11236. LLAMA_LOG_ERROR("%s: bad file magic\n", __func__);
  11237. return 1;
  11238. }
  11239. uint32_t format_version = fin.read_u32();
  11240. if (format_version != 1) {
  11241. LLAMA_LOG_ERROR("%s: unsupported file version\n", __func__ );
  11242. return 1;
  11243. }
  11244. }
  11245. int32_t lora_r = fin.read_u32();
  11246. int32_t lora_alpha = fin.read_u32();
  11247. float scaling = scale * (float)lora_alpha / (float)lora_r;
  11248. LLAMA_LOG_INFO("%s: r = %d, alpha = %d, scaling = %.2f\n", __func__, lora_r, lora_alpha, scaling);
  11249. // load base model
  11250. std::unique_ptr<llama_model_loader> ml;
  11251. if (path_base_model) {
  11252. LLAMA_LOG_INFO("%s: loading base model from '%s'\n", __func__, path_base_model);
  11253. ml.reset(new llama_model_loader(path_base_model, /*use_mmap*/ true, /*kv_overrides*/ nullptr));
  11254. ml->init_mappings(/*prefetch*/ false); // no prefetching
  11255. }
  11256. struct tensor_meta {
  11257. std::string name;
  11258. ggml_type type;
  11259. int32_t ne[2];
  11260. size_t offset;
  11261. };
  11262. std::map<std::string, tensor_meta> tensor_meta_map;
  11263. // load all tensor meta
  11264. while (true) {
  11265. if (fin.tell() == fin.size) {
  11266. // eof
  11267. break;
  11268. }
  11269. int32_t n_dims;
  11270. int32_t name_len;
  11271. int32_t ftype;
  11272. fin.read_raw(&n_dims, sizeof(n_dims));
  11273. fin.read_raw(&name_len, sizeof(name_len));
  11274. fin.read_raw(&ftype, sizeof(ftype));
  11275. if (n_dims != 1 && n_dims != 2) {
  11276. LLAMA_LOG_ERROR("%s: unsupported tensor dimension %d\n", __func__, n_dims);
  11277. return 1;
  11278. }
  11279. int32_t ne[2] = { 1, 1 };
  11280. for (int i = 0; i < n_dims; ++i) {
  11281. fin.read_raw(&ne[i], sizeof(ne[i]));
  11282. }
  11283. std::string name;
  11284. {
  11285. GGML_ASSERT(name_len < GGML_MAX_NAME);
  11286. char buf[GGML_MAX_NAME];
  11287. fin.read_raw(buf, name_len);
  11288. name = std::string(buf, name_len);
  11289. }
  11290. // check for lora suffix
  11291. std::string lora_suffix;
  11292. if (name.length() > 6) {
  11293. lora_suffix = name.substr(name.length() - 6);
  11294. }
  11295. if (lora_suffix != ".loraA" && lora_suffix != ".loraB") {
  11296. LLAMA_LOG_ERROR("%s: error: '%s' is not a lora tensor\n", __func__, name.c_str());
  11297. return 1;
  11298. }
  11299. // tensor type
  11300. ggml_type wtype;
  11301. switch (ftype) {
  11302. case 0: wtype = GGML_TYPE_F32; break;
  11303. case 1: wtype = GGML_TYPE_F16; break;
  11304. default:
  11305. {
  11306. LLAMA_LOG_ERROR("%s: invalid tensor data type '%d'\n",
  11307. __func__, ftype);
  11308. return 1;
  11309. }
  11310. }
  11311. // data offset
  11312. size_t offset = fin.tell();
  11313. offset = (offset + 31) & -32;
  11314. // skip tensor data
  11315. fin.seek(offset + ggml_row_size(wtype, ne[0]) * ne[1], SEEK_SET);
  11316. tensor_meta_map.emplace(name, tensor_meta{ name, wtype, { ne[0], ne[1] }, offset });
  11317. }
  11318. bool warned = false;
  11319. int n_tensors = 0;
  11320. // apply
  11321. ggml_backend_t backend_cpu = ggml_backend_cpu_init();
  11322. if (backend_cpu == nullptr) {
  11323. LLAMA_LOG_ERROR("%s: error: failed to initialize cpu backend\n", __func__);
  11324. return 1;
  11325. }
  11326. ggml_backend_cpu_set_n_threads(backend_cpu, n_threads);
  11327. std::vector<no_init<uint8_t>> read_buf;
  11328. for (const auto & it : model.tensors_by_name) {
  11329. const std::string & base_name = it.first;
  11330. ggml_tensor * model_t = it.second;
  11331. if (tensor_meta_map.find(base_name + ".loraA") == tensor_meta_map.end() ||
  11332. tensor_meta_map.find(base_name + ".loraB") == tensor_meta_map.end()) {
  11333. continue;
  11334. }
  11335. tensor_meta & metaA = tensor_meta_map.at(base_name + ".loraA");
  11336. tensor_meta & metaB = tensor_meta_map.at(base_name + ".loraB");
  11337. ggml_init_params lora_init_params = {
  11338. /* .mem_size */ ggml_tensor_overhead()*128 + ggml_graph_overhead(),
  11339. /* .mem_buffer */ nullptr,
  11340. /* .no_alloc */ true,
  11341. };
  11342. ggml_context * lora_ctx = ggml_init(lora_init_params);
  11343. if (lora_ctx == nullptr) {
  11344. LLAMA_LOG_ERROR("%s: error: failed to initialize lora context\n", __func__);
  11345. ggml_backend_free(backend_cpu);
  11346. return 1;
  11347. }
  11348. // create tensors
  11349. ggml_tensor * loraA = ggml_new_tensor_2d(lora_ctx, metaA.type, metaA.ne[0], metaA.ne[1]);
  11350. ggml_tensor * loraB = ggml_new_tensor_2d(lora_ctx, metaB.type, metaB.ne[0], metaB.ne[1]);
  11351. ggml_set_name(loraA, metaA.name.c_str());
  11352. ggml_set_name(loraB, metaB.name.c_str());
  11353. ggml_tensor * base_t;
  11354. if (ml) {
  11355. if (!ml->get_tensor_meta(base_name.c_str())) {
  11356. LLAMA_LOG_ERROR("%s: error: tensor '%s' not found in base model\n", __func__, base_name.c_str());
  11357. return 1;
  11358. }
  11359. base_t = ggml_dup_tensor(lora_ctx, ml->get_tensor_meta(base_name.c_str()));
  11360. } else {
  11361. base_t = ggml_dup_tensor(lora_ctx, model_t);
  11362. }
  11363. ggml_set_name(base_t, base_name.c_str());
  11364. // allocate in backend buffer
  11365. ggml_backend_buffer_t lora_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  11366. if (lora_buf == nullptr) {
  11367. LLAMA_LOG_ERROR("%s: error: failed to allocate lora tensors\n", __func__);
  11368. return 1;
  11369. }
  11370. // load tensor data
  11371. auto load_tensor = [&read_buf, &fin](const tensor_meta & tensor_meta, ggml_tensor * tensor) {
  11372. read_buf.resize(ggml_nbytes(tensor));
  11373. fin.seek(tensor_meta.offset, SEEK_SET);
  11374. fin.read_raw(read_buf.data(), ggml_nbytes(tensor));
  11375. ggml_backend_tensor_set(tensor, read_buf.data(), 0, read_buf.size());
  11376. };
  11377. load_tensor(metaA, loraA);
  11378. load_tensor(metaB, loraB);
  11379. // load base model tensor data
  11380. if (ml) {
  11381. ml->load_data_for(base_t);
  11382. } else {
  11383. ggml_backend_tensor_copy(model_t, base_t);
  11384. }
  11385. if (ggml_is_quantized(base_t->type) && !warned) {
  11386. LLAMA_LOG_WARN("%s: warning: using a lora adapter with a quantized model may result in poor quality, "
  11387. "use a f16 or f32 base model with --lora-base\n", __func__);
  11388. warned = true;
  11389. }
  11390. if (base_t->ne[0] != loraA->ne[1] || base_t->ne[1] != loraB->ne[1]) {
  11391. LLAMA_LOG_ERROR("%s: incompatible tensor dimensions (%" PRId64 " and %" PRId64 ");"
  11392. " are you sure that this adapter is for this model?\n", __func__, base_t->ne[0], loraA->ne[1]);
  11393. ggml_free(lora_ctx);
  11394. ggml_backend_buffer_free(lora_buf);
  11395. ggml_backend_free(backend_cpu);
  11396. return 1;
  11397. }
  11398. auto build_lora_graph = [&]() {
  11399. // w = w + BA*s
  11400. ggml_tensor * BA = ggml_mul_mat(lora_ctx, loraA, loraB);
  11401. ggml_set_name(BA, "BA");
  11402. if (scaling != 1.0f) {
  11403. BA = ggml_scale(lora_ctx, BA, scaling);
  11404. ggml_set_name(BA, "BA_scaled");
  11405. }
  11406. ggml_tensor * r;
  11407. r = ggml_add_inplace(lora_ctx, base_t, BA);
  11408. ggml_set_name(r, "r_add");
  11409. if (base_t->type != model_t->type) {
  11410. // convert the result to the model type
  11411. r = ggml_cast(lora_ctx, r, model_t->type);
  11412. ggml_set_name(r, "r_cast");
  11413. }
  11414. return r;
  11415. };
  11416. ggml_cgraph * gf = ggml_new_graph(lora_ctx);
  11417. ggml_tensor * r = build_lora_graph();
  11418. ggml_build_forward_expand(gf, r);
  11419. ggml_backend_buffer_t graph_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  11420. if (graph_buf == nullptr) {
  11421. LLAMA_LOG_ERROR("%s: error: failed to allocate graph tensors\n", __func__);
  11422. ggml_free(lora_ctx);
  11423. ggml_backend_buffer_free(lora_buf);
  11424. ggml_backend_free(backend_cpu);
  11425. return 1;
  11426. }
  11427. ggml_backend_graph_compute(backend_cpu, gf);
  11428. ggml_backend_tensor_set(model_t, r->data, 0, ggml_nbytes(r));
  11429. #if 0
  11430. // TODO: use scheduler with fallback to CPU for less copies between CPU and GPU
  11431. //ggml_backend_sched_t sched = ggml_backend_sched_new(backends.data(), backends.size(), GGML_DEFAULT_GRAPH_SIZE);
  11432. // sched compute
  11433. ggml_build_forward_expand(gf, build_graph());
  11434. ggml_backend_sched_init_measure(sched, gf);
  11435. // create the graph again, since the previous one was destroyed by the measure
  11436. ggml_graph_clear(gf);
  11437. ggml_build_forward_expand(gf, build_graph());
  11438. ggml_backend_sched_graph_compute(sched, gf);
  11439. ggml_backend_sched_free(sched);
  11440. #endif
  11441. ggml_backend_buffer_free(lora_buf);
  11442. ggml_backend_buffer_free(graph_buf);
  11443. ggml_free(lora_ctx);
  11444. n_tensors++;
  11445. if (n_tensors % 4 == 0) {
  11446. LLAMA_LOG_INFO(".");
  11447. }
  11448. }
  11449. ggml_backend_free(backend_cpu);
  11450. const int64_t t_lora_us = ggml_time_us() - t_start_lora_us;
  11451. LLAMA_LOG_INFO(" done (%.2f ms)\n", t_lora_us / 1000.0);
  11452. return 0;
  11453. }
  11454. //
  11455. // interface implementation
  11456. //
  11457. struct llama_model_params llama_model_default_params() {
  11458. struct llama_model_params result = {
  11459. /*.n_gpu_layers =*/ 0,
  11460. /*.split_mode =*/ LLAMA_SPLIT_MODE_LAYER,
  11461. /*.main_gpu =*/ 0,
  11462. /*.tensor_split =*/ nullptr,
  11463. /*.progress_callback =*/ nullptr,
  11464. /*.progress_callback_user_data =*/ nullptr,
  11465. /*.kv_overrides =*/ nullptr,
  11466. /*.vocab_only =*/ false,
  11467. /*.use_mmap =*/ true,
  11468. /*.use_mlock =*/ false,
  11469. };
  11470. #ifdef GGML_USE_METAL
  11471. // note: we usually have plenty of VRAM, so by default offload all layers to the GPU
  11472. result.n_gpu_layers = 999;
  11473. #endif
  11474. return result;
  11475. }
  11476. struct llama_context_params llama_context_default_params() {
  11477. struct llama_context_params result = {
  11478. /*.seed =*/ LLAMA_DEFAULT_SEED,
  11479. /*.n_ctx =*/ 512,
  11480. /*.n_batch =*/ 2048,
  11481. /*.n_ubatch =*/ 512,
  11482. /*.n_seq_max =*/ 1,
  11483. /*.n_threads =*/ GGML_DEFAULT_N_THREADS, // TODO: better default
  11484. /*.n_threads_batch =*/ GGML_DEFAULT_N_THREADS,
  11485. /*.rope_scaling_type =*/ LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED,
  11486. /*.pooling_type =*/ LLAMA_POOLING_TYPE_UNSPECIFIED,
  11487. /*.rope_freq_base =*/ 0.0f,
  11488. /*.rope_freq_scale =*/ 0.0f,
  11489. /*.yarn_ext_factor =*/ -1.0f,
  11490. /*.yarn_attn_factor =*/ 1.0f,
  11491. /*.yarn_beta_fast =*/ 32.0f,
  11492. /*.yarn_beta_slow =*/ 1.0f,
  11493. /*.yarn_orig_ctx =*/ 0,
  11494. /*.defrag_thold =*/ -1.0f,
  11495. /*.cb_eval =*/ nullptr,
  11496. /*.cb_eval_user_data =*/ nullptr,
  11497. /*.type_k =*/ GGML_TYPE_F16,
  11498. /*.type_v =*/ GGML_TYPE_F16,
  11499. /*.logits_all =*/ false,
  11500. /*.embeddings =*/ false,
  11501. /*.offload_kqv =*/ true,
  11502. /*.abort_callback =*/ nullptr,
  11503. /*.abort_callback_data =*/ nullptr,
  11504. };
  11505. return result;
  11506. }
  11507. struct llama_model_quantize_params llama_model_quantize_default_params() {
  11508. struct llama_model_quantize_params result = {
  11509. /*.nthread =*/ 0,
  11510. /*.ftype =*/ LLAMA_FTYPE_MOSTLY_Q5_1,
  11511. /*.output_tensor_type =*/ GGML_TYPE_COUNT,
  11512. /*.token_embedding_type =*/ GGML_TYPE_COUNT,
  11513. /*.allow_requantize =*/ false,
  11514. /*.quantize_output_tensor =*/ true,
  11515. /*.only_copy =*/ false,
  11516. /*.pure =*/ false,
  11517. /*.imatrix =*/ nullptr,
  11518. /*.kv_overrides =*/ nullptr,
  11519. };
  11520. return result;
  11521. }
  11522. size_t llama_max_devices(void) {
  11523. #if defined(GGML_USE_METAL)
  11524. return 1;
  11525. #elif defined(GGML_USE_CUDA)
  11526. return GGML_CUDA_MAX_DEVICES;
  11527. #elif defined(GGML_USE_SYCL)
  11528. return GGML_SYCL_MAX_DEVICES;
  11529. #elif defined(GGML_USE_VULKAN)
  11530. return GGML_VK_MAX_DEVICES;
  11531. #else
  11532. return 1;
  11533. #endif
  11534. }
  11535. bool llama_supports_mmap(void) {
  11536. return llama_mmap::SUPPORTED;
  11537. }
  11538. bool llama_supports_mlock(void) {
  11539. return llama_mlock::SUPPORTED;
  11540. }
  11541. bool llama_supports_gpu_offload(void) {
  11542. #if defined(GGML_USE_CUDA) || defined(GGML_USE_CLBLAST) || defined(GGML_USE_METAL) || defined(GGML_USE_VULKAN) || \
  11543. defined(GGML_USE_SYCL) || defined(GGML_USE_KOMPUTE)
  11544. // Defined when llama.cpp is compiled with support for offloading model layers to GPU.
  11545. return true;
  11546. #else
  11547. return false;
  11548. #endif
  11549. }
  11550. void llama_backend_init(void) {
  11551. ggml_time_init();
  11552. // needed to initialize f16 tables
  11553. {
  11554. struct ggml_init_params params = { 0, NULL, false };
  11555. struct ggml_context * ctx = ggml_init(params);
  11556. ggml_free(ctx);
  11557. }
  11558. #ifdef GGML_USE_MPI
  11559. ggml_mpi_backend_init();
  11560. #endif
  11561. }
  11562. void llama_numa_init(enum ggml_numa_strategy numa) {
  11563. if (numa != GGML_NUMA_STRATEGY_DISABLED) {
  11564. ggml_numa_init(numa);
  11565. }
  11566. }
  11567. void llama_backend_free(void) {
  11568. #ifdef GGML_USE_MPI
  11569. ggml_mpi_backend_free();
  11570. #endif
  11571. ggml_quantize_free();
  11572. }
  11573. int64_t llama_time_us(void) {
  11574. return ggml_time_us();
  11575. }
  11576. struct llama_model * llama_load_model_from_file(
  11577. const char * path_model,
  11578. struct llama_model_params params) {
  11579. ggml_time_init();
  11580. llama_model * model = new llama_model;
  11581. unsigned cur_percentage = 0;
  11582. if (params.progress_callback == NULL) {
  11583. params.progress_callback_user_data = &cur_percentage;
  11584. params.progress_callback = [](float progress, void * ctx) {
  11585. unsigned * cur_percentage_p = (unsigned *) ctx;
  11586. unsigned percentage = (unsigned) (100 * progress);
  11587. while (percentage > *cur_percentage_p) {
  11588. *cur_percentage_p = percentage;
  11589. LLAMA_LOG_INFO(".");
  11590. if (percentage >= 100) {
  11591. LLAMA_LOG_INFO("\n");
  11592. }
  11593. }
  11594. return true;
  11595. };
  11596. }
  11597. int status = llama_model_load(path_model, *model, params);
  11598. GGML_ASSERT(status <= 0);
  11599. if (status < 0) {
  11600. if (status == -1) {
  11601. LLAMA_LOG_ERROR("%s: failed to load model\n", __func__);
  11602. } else if (status == -2) {
  11603. LLAMA_LOG_INFO("%s: cancelled model load\n", __func__);
  11604. }
  11605. delete model;
  11606. return nullptr;
  11607. }
  11608. return model;
  11609. }
  11610. void llama_free_model(struct llama_model * model) {
  11611. delete model;
  11612. }
  11613. struct llama_context * llama_new_context_with_model(
  11614. struct llama_model * model,
  11615. struct llama_context_params params) {
  11616. if (!model) {
  11617. LLAMA_LOG_ERROR("%s: model cannot be NULL\n", __func__);
  11618. return nullptr;
  11619. }
  11620. if (params.n_batch == 0 && params.n_ubatch == 0) {
  11621. LLAMA_LOG_ERROR("%s: n_batch and n_ubatch cannot both be zero\n", __func__);
  11622. return nullptr;
  11623. }
  11624. if (params.n_ctx == 0 && model->hparams.n_ctx_train == 0) {
  11625. LLAMA_LOG_ERROR("%s: n_ctx and model->hparams.n_ctx_train cannot both be zero\n", __func__);
  11626. return nullptr;
  11627. }
  11628. llama_context * ctx = new llama_context(*model);
  11629. const auto & hparams = model->hparams;
  11630. auto & cparams = ctx->cparams;
  11631. cparams.n_seq_max = std::max(1u, params.n_seq_max);
  11632. cparams.n_threads = params.n_threads;
  11633. cparams.n_threads_batch = params.n_threads_batch;
  11634. cparams.yarn_ext_factor = params.yarn_ext_factor;
  11635. cparams.yarn_attn_factor = params.yarn_attn_factor;
  11636. cparams.yarn_beta_fast = params.yarn_beta_fast;
  11637. cparams.yarn_beta_slow = params.yarn_beta_slow;
  11638. cparams.defrag_thold = params.defrag_thold;
  11639. cparams.embeddings = params.embeddings;
  11640. cparams.offload_kqv = params.offload_kqv;
  11641. cparams.pooling_type = params.pooling_type;
  11642. cparams.n_ctx = params.n_ctx == 0 ? hparams.n_ctx_train : params.n_ctx;
  11643. cparams.rope_freq_base = params.rope_freq_base == 0.0f ? hparams.rope_freq_base_train : params.rope_freq_base;
  11644. cparams.rope_freq_scale = params.rope_freq_scale == 0.0f ? hparams.rope_freq_scale_train : params.rope_freq_scale;
  11645. // this is necessary due to kv_self.n being padded later during inference
  11646. cparams.n_ctx = GGML_PAD(cparams.n_ctx, 32);
  11647. // with causal attention, the batch size is limited by the context size
  11648. cparams.n_batch = hparams.causal_attn ? std::min(cparams.n_ctx, params.n_batch) : params.n_batch;
  11649. cparams.n_ubatch = std::min(cparams.n_batch, params.n_ubatch == 0 ? params.n_batch : params.n_ubatch);
  11650. cparams.n_yarn_orig_ctx = params.yarn_orig_ctx != 0 ? params.yarn_orig_ctx :
  11651. hparams.n_yarn_orig_ctx != 0 ? hparams.n_yarn_orig_ctx :
  11652. hparams.n_ctx_train;
  11653. cparams.cb_eval = params.cb_eval;
  11654. cparams.cb_eval_user_data = params.cb_eval_user_data;
  11655. auto rope_scaling_type = params.rope_scaling_type;
  11656. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED) {
  11657. rope_scaling_type = hparams.rope_scaling_type_train;
  11658. }
  11659. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_NONE) {
  11660. cparams.rope_freq_scale = 1.0f; // never scale if scaling type is none
  11661. }
  11662. if (cparams.yarn_ext_factor < 0.0f) { // negative indicates 'not set'
  11663. cparams.yarn_ext_factor = rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_YARN ? 1.0f : 0.0f;
  11664. }
  11665. cparams.causal_attn = hparams.causal_attn;
  11666. if (cparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  11667. if (hparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  11668. cparams.pooling_type = LLAMA_POOLING_TYPE_NONE;
  11669. } else {
  11670. cparams.pooling_type = hparams.pooling_type;
  11671. }
  11672. }
  11673. if (params.seed == LLAMA_DEFAULT_SEED) {
  11674. params.seed = time(NULL);
  11675. }
  11676. LLAMA_LOG_INFO("%s: n_ctx = %u\n", __func__, cparams.n_ctx);
  11677. LLAMA_LOG_INFO("%s: n_batch = %u\n", __func__, cparams.n_batch);
  11678. LLAMA_LOG_INFO("%s: n_ubatch = %u\n", __func__, cparams.n_ubatch);
  11679. LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, cparams.rope_freq_base);
  11680. LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, cparams.rope_freq_scale);
  11681. ctx->abort_callback = params.abort_callback;
  11682. ctx->abort_callback_data = params.abort_callback_data;
  11683. ctx->rng = std::mt19937(params.seed);
  11684. ctx->logits_all = params.logits_all;
  11685. uint32_t kv_size = cparams.n_ctx;
  11686. ggml_type type_k = params.type_k;
  11687. ggml_type type_v = params.type_v;
  11688. // Mamba only needs a constant number of KV cache cells per sequence
  11689. if (model->arch == LLM_ARCH_MAMBA) {
  11690. // Mamba needs at least as many KV cells as there are sequences kept at any time
  11691. kv_size = std::max((uint32_t) 1, params.n_seq_max);
  11692. // it's probably best to keep as much precision as possible for the states
  11693. type_k = GGML_TYPE_F32; // required by ggml_ssm_conv for Mamba's conv_states
  11694. type_v = GGML_TYPE_F32; // required by ggml_ssm_scan for Mamba's ssm_states
  11695. }
  11696. GGML_ASSERT(hparams.n_embd_head_k % ggml_blck_size(type_k) == 0);
  11697. GGML_ASSERT(hparams.n_embd_head_v % ggml_blck_size(type_v) == 0);
  11698. if (!hparams.vocab_only) {
  11699. // initialize backends
  11700. #ifdef GGML_USE_METAL
  11701. if (model->n_gpu_layers > 0) {
  11702. ctx->backend_metal = ggml_backend_metal_init();
  11703. if (ctx->backend_metal == nullptr) {
  11704. LLAMA_LOG_ERROR("%s: failed to initialize Metal backend\n", __func__);
  11705. llama_free(ctx);
  11706. return nullptr;
  11707. }
  11708. ctx->backends.push_back(ctx->backend_metal);
  11709. }
  11710. #elif defined(GGML_USE_CUDA)
  11711. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  11712. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  11713. ggml_backend_t backend = ggml_backend_cuda_init(model->main_gpu);
  11714. if (backend == nullptr) {
  11715. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, model->main_gpu);
  11716. llama_free(ctx);
  11717. return nullptr;
  11718. }
  11719. ctx->backends.push_back(backend);
  11720. } else {
  11721. // LLAMA_SPLIT_MODE_LAYER requires a backend for each GPU
  11722. for (int device = 0; device < ggml_backend_cuda_get_device_count(); ++device) {
  11723. ggml_backend_t backend = ggml_backend_cuda_init(device);
  11724. if (backend == nullptr) {
  11725. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, device);
  11726. llama_free(ctx);
  11727. return nullptr;
  11728. }
  11729. ctx->backends.push_back(backend);
  11730. }
  11731. }
  11732. #elif defined(GGML_USE_VULKAN)
  11733. if (model->n_gpu_layers > 0) {
  11734. for (int device = 0; device < ggml_backend_vk_get_device_count(); ++device) {
  11735. ggml_backend_t backend = ggml_backend_vk_init(device);
  11736. if (backend == nullptr) {
  11737. LLAMA_LOG_ERROR("%s: failed to initialize Vulkan%d backend\n", __func__, device);
  11738. llama_free(ctx);
  11739. return nullptr;
  11740. }
  11741. ctx->backends.push_back(backend);
  11742. }
  11743. }
  11744. #elif defined(GGML_USE_SYCL)
  11745. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  11746. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  11747. ggml_backend_t backend = ggml_backend_sycl_init(model->main_gpu);
  11748. if (backend == nullptr) {
  11749. int main_gpu_id = ggml_backend_sycl_get_device_id(model->main_gpu);
  11750. LLAMA_LOG_ERROR("%s: failed to initialize SYCL%d (index %d) backend\n", __func__, main_gpu_id, model->main_gpu);
  11751. llama_free(ctx);
  11752. return nullptr;
  11753. }
  11754. ctx->backends.push_back(backend);
  11755. } else {
  11756. // LLAMA_SPLIT_LAYER requires a backend for each GPU
  11757. for (int i = 0; i < ggml_backend_sycl_get_device_count(); ++i) {
  11758. ggml_backend_t backend = ggml_backend_sycl_init(i);
  11759. if (backend == nullptr) {
  11760. int id_list[GGML_SYCL_MAX_DEVICES];
  11761. ggml_sycl_get_gpu_list(id_list, GGML_SYCL_MAX_DEVICES);
  11762. LLAMA_LOG_ERROR("%s: failed to initialize SYCL%d (index %d) backend\n", __func__, id_list[i], i);
  11763. llama_free(ctx);
  11764. return nullptr;
  11765. }
  11766. ctx->backends.push_back(backend);
  11767. }
  11768. }
  11769. #elif defined(GGML_USE_KOMPUTE)
  11770. if (model->n_gpu_layers > 0) {
  11771. auto * backend = ggml_backend_kompute_init(model->main_gpu);
  11772. if (backend == nullptr) {
  11773. LLAMA_LOG_ERROR("%s: failed to initialize Kompute backend\n", __func__);
  11774. llama_free(ctx);
  11775. return nullptr;
  11776. }
  11777. ctx->backends.push_back(backend);
  11778. }
  11779. #endif
  11780. ctx->backend_cpu = ggml_backend_cpu_init();
  11781. if (ctx->backend_cpu == nullptr) {
  11782. LLAMA_LOG_ERROR("%s: failed to initialize CPU backend\n", __func__);
  11783. llama_free(ctx);
  11784. return nullptr;
  11785. }
  11786. ctx->backends.push_back(ctx->backend_cpu);
  11787. if (!llama_kv_cache_init(ctx->kv_self, ctx->model, type_k, type_v, kv_size, cparams.offload_kqv)) {
  11788. LLAMA_LOG_ERROR("%s: llama_kv_cache_init() failed for self-attention cache\n", __func__);
  11789. llama_free(ctx);
  11790. return nullptr;
  11791. }
  11792. {
  11793. size_t memory_size_k = 0;
  11794. size_t memory_size_v = 0;
  11795. for (auto & k : ctx->kv_self.k_l) {
  11796. memory_size_k += ggml_nbytes(k);
  11797. }
  11798. for (auto & v : ctx->kv_self.v_l) {
  11799. memory_size_v += ggml_nbytes(v);
  11800. }
  11801. LLAMA_LOG_INFO("%s: KV self size = %7.2f MiB, K (%s): %7.2f MiB, V (%s): %7.2f MiB\n", __func__,
  11802. (float)(memory_size_k + memory_size_v) / (1024.0f * 1024.0f),
  11803. ggml_type_name(type_k), (float)memory_size_k / (1024.0f * 1024.0f),
  11804. ggml_type_name(type_v), (float)memory_size_v / (1024.0f * 1024.0f));
  11805. }
  11806. // graph outputs buffer
  11807. {
  11808. // resized during inference when a batch uses more outputs
  11809. if (llama_output_reserve(*ctx, params.n_seq_max) < params.n_seq_max) {
  11810. LLAMA_LOG_ERROR("%s: failed to reserve initial output buffer\n", __func__);
  11811. llama_free(ctx);
  11812. return nullptr;
  11813. }
  11814. LLAMA_LOG_INFO("%s: %10s output buffer size = %8.2f MiB\n", __func__,
  11815. ggml_backend_buffer_name(ctx->buf_output),
  11816. ggml_backend_buffer_get_size(ctx->buf_output) / 1024.0 / 1024.0);
  11817. }
  11818. // scheduler and compute buffers
  11819. {
  11820. // buffer types used for the compute buffer of each backend
  11821. std::vector<ggml_backend_buffer_type_t> backend_buft;
  11822. for (auto * backend : ctx->backends) {
  11823. if (ggml_backend_is_cpu(backend)) {
  11824. // use host buffers for the CPU backend compute buffer
  11825. backend_buft.push_back(llama_default_buffer_type_cpu(true));
  11826. } else {
  11827. backend_buft.push_back(ggml_backend_get_default_buffer_type(backend));
  11828. }
  11829. }
  11830. // buffer used to store the computation graph and the tensor meta data
  11831. ctx->buf_compute_meta.resize(ggml_tensor_overhead()*LLAMA_MAX_NODES + ggml_graph_overhead_custom(LLAMA_MAX_NODES, false));
  11832. // enabling pipeline parallelism in the scheduler increases memory usage, so it is only done when necessary
  11833. bool pipeline_parallel = llama_get_device_count() > 1 && model->n_gpu_layers > (int)model->hparams.n_layer && model->split_mode == LLAMA_SPLIT_MODE_LAYER;
  11834. #ifndef GGML_USE_CUDA
  11835. // pipeline parallelism requires support for async compute and events
  11836. // currently this is only implemented in the CUDA backend
  11837. pipeline_parallel = false;
  11838. #endif
  11839. ctx->sched = ggml_backend_sched_new(ctx->backends.data(), backend_buft.data(), ctx->backends.size(), LLAMA_MAX_NODES, pipeline_parallel);
  11840. if (pipeline_parallel) {
  11841. LLAMA_LOG_INFO("%s: pipeline parallelism enabled (n_copies=%d)\n", __func__, ggml_backend_sched_get_n_copies(ctx->sched));
  11842. }
  11843. // build worst-case graph
  11844. int n_tokens = (int)std::min(cparams.n_ctx, cparams.n_ubatch);
  11845. int n_past = cparams.n_ctx - n_tokens;
  11846. 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
  11847. ggml_cgraph * gf = llama_build_graph(*ctx, llama_batch_get_one(&token, n_tokens, n_past, 0), true);
  11848. // initialize scheduler with the worst-case graph
  11849. if (!ggml_backend_sched_reserve(ctx->sched, gf)) {
  11850. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  11851. llama_free(ctx);
  11852. return nullptr;
  11853. }
  11854. for (size_t i = 0; i < ctx->backends.size(); i++) {
  11855. ggml_backend_t backend = ctx->backends[i];
  11856. ggml_backend_buffer_type_t buft = backend_buft[i];
  11857. size_t size = ggml_backend_sched_get_buffer_size(ctx->sched, backend);
  11858. if (size > 1) {
  11859. LLAMA_LOG_INFO("%s: %10s compute buffer size = %8.2f MiB\n", __func__,
  11860. ggml_backend_buft_name(buft),
  11861. size / 1024.0 / 1024.0);
  11862. }
  11863. }
  11864. // note: the number of splits during measure is higher than during inference due to the kv shift
  11865. int n_splits = ggml_backend_sched_get_n_splits(ctx->sched);
  11866. LLAMA_LOG_INFO("%s: graph nodes = %d\n", __func__, gf->n_nodes);
  11867. LLAMA_LOG_INFO("%s: graph splits = %d\n", __func__, n_splits);
  11868. }
  11869. }
  11870. #ifdef GGML_USE_MPI
  11871. ctx->ctx_mpi = ggml_mpi_init();
  11872. if (ggml_mpi_rank(ctx->ctx_mpi) > 0) {
  11873. // Enter a blocking eval loop with dummy input, letting rank=0 drive the process
  11874. // TODO: needs fix after #3228
  11875. GGML_ASSERT(false && "not implemented");
  11876. //const std::vector<llama_token> tmp(ctx->model.hparams.n_ctx, llama_token_bos(ctx));
  11877. //while (!llama_eval(ctx, tmp.data(), tmp.size(), 0, 0)) {};
  11878. llama_backend_free();
  11879. exit(1);
  11880. }
  11881. #endif
  11882. return ctx;
  11883. }
  11884. void llama_free(struct llama_context * ctx) {
  11885. delete ctx;
  11886. }
  11887. const llama_model * llama_get_model(const struct llama_context * ctx) {
  11888. return &ctx->model;
  11889. }
  11890. uint32_t llama_n_ctx(const struct llama_context * ctx) {
  11891. return ctx->cparams.n_ctx;
  11892. }
  11893. uint32_t llama_n_batch(const struct llama_context * ctx) {
  11894. return ctx->cparams.n_batch;
  11895. }
  11896. uint32_t llama_n_ubatch(const struct llama_context * ctx) {
  11897. return ctx->cparams.n_ubatch;
  11898. }
  11899. uint32_t llama_n_seq_max(const struct llama_context * ctx) {
  11900. return ctx->kv_self.size;
  11901. }
  11902. enum llama_vocab_type llama_vocab_type(const struct llama_model * model) {
  11903. return model->vocab.type;
  11904. }
  11905. enum llama_rope_type llama_rope_type(const struct llama_model * model) {
  11906. switch (model->arch) {
  11907. // these models do not use RoPE
  11908. case LLM_ARCH_GPT2:
  11909. case LLM_ARCH_GPTJ:
  11910. case LLM_ARCH_GPTNEOX:
  11911. case LLM_ARCH_MPT:
  11912. case LLM_ARCH_REFACT:
  11913. case LLM_ARCH_BLOOM:
  11914. case LLM_ARCH_MAMBA:
  11915. return LLAMA_ROPE_TYPE_NONE;
  11916. // use what we call a normal RoPE, operating on pairs of consecutive head values
  11917. case LLM_ARCH_LLAMA:
  11918. case LLM_ARCH_BAICHUAN:
  11919. case LLM_ARCH_STARCODER:
  11920. case LLM_ARCH_PLAMO:
  11921. case LLM_ARCH_CODESHELL:
  11922. case LLM_ARCH_ORION:
  11923. case LLM_ARCH_INTERNLM2:
  11924. case LLM_ARCH_MINICPM:
  11925. case LLM_ARCH_XVERSE:
  11926. case LLM_ARCH_COMMAND_R:
  11927. return LLAMA_ROPE_TYPE_NORM;
  11928. // the pairs of head values are offset by n_rot/2
  11929. case LLM_ARCH_FALCON:
  11930. case LLM_ARCH_GROK:
  11931. case LLM_ARCH_PERSIMMON:
  11932. case LLM_ARCH_BERT:
  11933. case LLM_ARCH_NOMIC_BERT:
  11934. case LLM_ARCH_STABLELM:
  11935. case LLM_ARCH_QWEN:
  11936. case LLM_ARCH_QWEN2:
  11937. case LLM_ARCH_PHI2:
  11938. case LLM_ARCH_GEMMA:
  11939. case LLM_ARCH_STARCODER2:
  11940. return LLAMA_ROPE_TYPE_NEOX;
  11941. // all model arches should be listed explicitly here
  11942. case LLM_ARCH_UNKNOWN:
  11943. GGML_ASSERT(false && "unknown architecture");
  11944. break;
  11945. }
  11946. return LLAMA_ROPE_TYPE_NONE;
  11947. }
  11948. int32_t llama_n_vocab(const struct llama_model * model) {
  11949. return model->hparams.n_vocab;
  11950. }
  11951. int32_t llama_n_ctx_train(const struct llama_model * model) {
  11952. return model->hparams.n_ctx_train;
  11953. }
  11954. int32_t llama_n_embd(const struct llama_model * model) {
  11955. return model->hparams.n_embd;
  11956. }
  11957. int32_t llama_n_layer(const struct llama_model * model) {
  11958. return model->hparams.n_layer;
  11959. }
  11960. float llama_rope_freq_scale_train(const struct llama_model * model) {
  11961. return model->hparams.rope_freq_scale_train;
  11962. }
  11963. int32_t llama_model_meta_val_str(const struct llama_model * model, const char * key, char * buf, size_t buf_size) {
  11964. const auto & it = model->gguf_kv.find(key);
  11965. if (it == model->gguf_kv.end()) {
  11966. if (buf_size > 0) {
  11967. buf[0] = '\0';
  11968. }
  11969. return -1;
  11970. }
  11971. return snprintf(buf, buf_size, "%s", it->second.c_str());
  11972. }
  11973. int32_t llama_model_meta_count(const struct llama_model * model) {
  11974. return (int)model->gguf_kv.size();
  11975. }
  11976. int32_t llama_model_meta_key_by_index(const struct llama_model * model, int i, char * buf, size_t buf_size) {
  11977. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  11978. if (buf_size > 0) {
  11979. buf[0] = '\0';
  11980. }
  11981. return -1;
  11982. }
  11983. auto it = model->gguf_kv.begin();
  11984. std::advance(it, i);
  11985. return snprintf(buf, buf_size, "%s", it->first.c_str());
  11986. }
  11987. int32_t llama_model_meta_val_str_by_index(const struct llama_model * model, int32_t i, char * buf, size_t buf_size) {
  11988. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  11989. if (buf_size > 0) {
  11990. buf[0] = '\0';
  11991. }
  11992. return -1;
  11993. }
  11994. auto it = model->gguf_kv.begin();
  11995. std::advance(it, i);
  11996. return snprintf(buf, buf_size, "%s", it->second.c_str());
  11997. }
  11998. int32_t llama_model_desc(const struct llama_model * model, char * buf, size_t buf_size) {
  11999. return snprintf(buf, buf_size, "%s %s %s",
  12000. llama_model_arch_name(model->arch),
  12001. llama_model_type_name(model->type),
  12002. llama_model_ftype_name(model->ftype).c_str());
  12003. }
  12004. uint64_t llama_model_size(const struct llama_model * model) {
  12005. uint64_t size = 0;
  12006. for (const auto & it : model->tensors_by_name) {
  12007. size += ggml_nbytes(it.second);
  12008. }
  12009. return size;
  12010. }
  12011. uint64_t llama_model_n_params(const struct llama_model * model) {
  12012. uint64_t nparams = 0;
  12013. for (const auto & it : model->tensors_by_name) {
  12014. nparams += ggml_nelements(it.second);
  12015. }
  12016. return nparams;
  12017. }
  12018. struct ggml_tensor * llama_get_model_tensor(struct llama_model * model, const char * name) {
  12019. auto it = std::find_if(model->tensors_by_name.begin(), model->tensors_by_name.end(),
  12020. [name](const std::pair<std::string, struct ggml_tensor *> & it) {
  12021. return it.first == name;
  12022. });
  12023. if (it == model->tensors_by_name.end()) {
  12024. return nullptr;
  12025. }
  12026. return it->second;
  12027. }
  12028. uint32_t llama_model_quantize(
  12029. const char * fname_inp,
  12030. const char * fname_out,
  12031. const llama_model_quantize_params * params) {
  12032. try {
  12033. llama_model_quantize_internal(fname_inp, fname_out, params);
  12034. return 0;
  12035. } catch (const std::exception & err) {
  12036. LLAMA_LOG_ERROR("%s: failed to quantize: %s\n", __func__, err.what());
  12037. return 1;
  12038. }
  12039. }
  12040. 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) {
  12041. try {
  12042. return llama_apply_lora_from_file_internal(*model, path_lora, scale, path_base_model, n_threads);
  12043. } catch (const std::exception & err) {
  12044. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  12045. return 1;
  12046. }
  12047. }
  12048. static bool llama_control_vector_init(struct llama_control_vector & cvec, const llama_model & model) {
  12049. GGML_ASSERT(cvec.tensors.empty());
  12050. GGML_ASSERT(cvec.ctxs.empty());
  12051. GGML_ASSERT(cvec.bufs.empty());
  12052. // count layer buffer types
  12053. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  12054. for (int64_t i = 0; i < model.hparams.n_layer; i++) {
  12055. buft_layer_count[model.buft_layer[i].buft]++;
  12056. }
  12057. // allocate contexts
  12058. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  12059. for (auto & it : buft_layer_count) {
  12060. int n_layers = it.second;
  12061. struct ggml_init_params params = {
  12062. /*.mem_size =*/ n_layers * ggml_tensor_overhead(),
  12063. /*.mem_buffer =*/ NULL,
  12064. /*.no_alloc =*/ true,
  12065. };
  12066. ggml_context * ctx = ggml_init(params);
  12067. if (!ctx) {
  12068. LLAMA_LOG_ERROR("%s: failed to allocate context for control vector\n", __func__);
  12069. return 1;
  12070. }
  12071. ctx_map[it.first] = ctx;
  12072. }
  12073. // make tensors
  12074. cvec.tensors.push_back(nullptr); // there's never a tensor for layer 0
  12075. for (size_t il = 1; il < model.hparams.n_layer; il++) {
  12076. struct ggml_context * ctx = ctx_map.at(model.buft_layer[il].buft);
  12077. ggml_tensor * tensor = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, model.hparams.n_embd);
  12078. cvec.tensors.push_back(tensor);
  12079. }
  12080. // allocate tensors / buffers and zero
  12081. for (auto it : ctx_map) {
  12082. ggml_backend_buffer_type_t buft = it.first;
  12083. ggml_context * ctx = it.second;
  12084. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  12085. if (!buf) {
  12086. LLAMA_LOG_ERROR("%s: failed to allocate buffer for control vector\n", __func__);
  12087. return false;
  12088. }
  12089. ggml_backend_buffer_clear(buf, 0);
  12090. cvec.ctxs.push_back(ctx);
  12091. cvec.bufs.push_back(buf);
  12092. }
  12093. return true;
  12094. }
  12095. 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) {
  12096. const llama_model & model = lctx->model;
  12097. llama_control_vector & cvec = lctx->cvec;
  12098. if (data == nullptr) {
  12099. // disable the current control vector (but leave allocated for later)
  12100. cvec.layer_start = -1;
  12101. cvec.layer_end = -1;
  12102. return 0;
  12103. }
  12104. if (n_embd != (int) model.hparams.n_embd) {
  12105. LLAMA_LOG_ERROR("%s: control vector n_embd does not match model\n", __func__);
  12106. return 1;
  12107. }
  12108. if (cvec.tensors.empty()) {
  12109. if (!llama_control_vector_init(cvec, model)) {
  12110. return 1;
  12111. }
  12112. }
  12113. cvec.layer_start = il_start;
  12114. cvec.layer_end = il_end;
  12115. for (size_t il = 1; il < model.hparams.n_layer; il++) {
  12116. assert(cvec.tensors[il] != nullptr);
  12117. const size_t off = n_embd * (il - 1); // buffer doesn't have data for layer 0, since it's never present
  12118. if (off + n_embd <= len) {
  12119. ggml_backend_tensor_set(cvec.tensors[il], data + off, 0, n_embd * ggml_element_size(cvec.tensors[il]));
  12120. }
  12121. }
  12122. return 0;
  12123. }
  12124. struct llama_kv_cache_view llama_kv_cache_view_init(const struct llama_context * ctx, int32_t n_seq_max) {
  12125. struct llama_kv_cache_view result = {
  12126. /*.n_cells = */ 0,
  12127. /*.n_seq_max = */ n_seq_max,
  12128. /*.token_count = */ 0,
  12129. /*.used_cells = */ llama_get_kv_cache_used_cells(ctx),
  12130. /*.max_contiguous = */ 0,
  12131. /*.max_contiguous_idx = */ -1,
  12132. /*.cells = */ nullptr,
  12133. /*.cells_sequences = */ nullptr,
  12134. };
  12135. return result;
  12136. }
  12137. void llama_kv_cache_view_free(struct llama_kv_cache_view * view) {
  12138. if (view->cells != nullptr) {
  12139. free(view->cells);
  12140. view->cells = nullptr;
  12141. }
  12142. if (view->cells_sequences != nullptr) {
  12143. free(view->cells_sequences);
  12144. view->cells_sequences = nullptr;
  12145. }
  12146. }
  12147. void llama_kv_cache_view_update(const struct llama_context * ctx, struct llama_kv_cache_view * view) {
  12148. if (uint32_t(view->n_cells) < ctx->kv_self.size || view->cells == nullptr) {
  12149. view->n_cells = int32_t(ctx->kv_self.size);
  12150. void * p = realloc(view->cells, sizeof(struct llama_kv_cache_view_cell) * view->n_cells);
  12151. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells");
  12152. view->cells = (struct llama_kv_cache_view_cell *)p;
  12153. p = realloc(view->cells_sequences, sizeof(llama_seq_id) * view->n_seq_max * view->n_cells);
  12154. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells sequences");
  12155. view->cells_sequences = (llama_seq_id *)p;
  12156. }
  12157. const std::vector<llama_kv_cell> & kv_cells = ctx->kv_self.cells;
  12158. llama_kv_cache_view_cell * c_curr = view->cells;
  12159. llama_seq_id * cs_curr = view->cells_sequences;
  12160. int32_t used_cells = 0;
  12161. int32_t token_count = 0;
  12162. int32_t curr_contig_idx = -1;
  12163. uint32_t max_contig = 0;
  12164. int32_t max_contig_idx = -1;
  12165. for (int32_t i = 0; i < int32_t(ctx->kv_self.size); i++, c_curr++, cs_curr += view->n_seq_max) {
  12166. const size_t curr_size = kv_cells[i].seq_id.size();
  12167. token_count += curr_size;
  12168. c_curr->pos = kv_cells[i].pos + kv_cells[i].delta;
  12169. if (curr_size > 0) {
  12170. if (curr_contig_idx >= 0 && uint32_t(i - curr_contig_idx) > max_contig) {
  12171. max_contig = i - curr_contig_idx;
  12172. max_contig_idx = curr_contig_idx;
  12173. }
  12174. curr_contig_idx = -1;
  12175. } else if (curr_contig_idx < 0) {
  12176. curr_contig_idx = i;
  12177. }
  12178. int seq_idx = 0;
  12179. for (const llama_seq_id it : kv_cells[i].seq_id) {
  12180. if (seq_idx >= view->n_seq_max) {
  12181. break;
  12182. }
  12183. cs_curr[seq_idx] = it;
  12184. seq_idx++;
  12185. }
  12186. if (seq_idx != 0) {
  12187. used_cells++;
  12188. }
  12189. for (; seq_idx < view->n_seq_max; seq_idx++) {
  12190. cs_curr[seq_idx] = -1;
  12191. }
  12192. }
  12193. if (curr_contig_idx >= 0 && kv_cells.size() - curr_contig_idx > max_contig) {
  12194. max_contig_idx = curr_contig_idx;
  12195. max_contig = kv_cells.size() - curr_contig_idx;
  12196. }
  12197. view->max_contiguous = max_contig;
  12198. view->max_contiguous_idx = max_contig_idx;
  12199. view->token_count = token_count;
  12200. view->used_cells = used_cells;
  12201. if (uint32_t(used_cells) != ctx->kv_self.used) {
  12202. LLAMA_LOG_ERROR("%s: used cells mismatch. kv_cache says %d but we calculated %d\n",
  12203. __func__, ctx->kv_self.used, used_cells);
  12204. }
  12205. }
  12206. int32_t llama_get_kv_cache_token_count(const struct llama_context * ctx) {
  12207. int result = 0;
  12208. for (uint32_t i = 0; i < ctx->kv_self.size; i++) {
  12209. result += ctx->kv_self.cells[i].seq_id.size();
  12210. }
  12211. return result;
  12212. }
  12213. int32_t llama_get_kv_cache_used_cells(const struct llama_context * ctx) {
  12214. return ctx->kv_self.used;
  12215. }
  12216. void llama_kv_cache_clear(struct llama_context * ctx) {
  12217. llama_kv_cache_clear(ctx->kv_self);
  12218. }
  12219. bool llama_kv_cache_seq_rm(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
  12220. return llama_kv_cache_seq_rm(ctx->kv_self, seq_id, p0, p1);
  12221. }
  12222. 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) {
  12223. if (seq_id_src == seq_id_dst) {
  12224. return;
  12225. }
  12226. llama_kv_cache_seq_cp(ctx->kv_self, seq_id_src, seq_id_dst, p0, p1);
  12227. }
  12228. void llama_kv_cache_seq_keep(struct llama_context * ctx, llama_seq_id seq_id) {
  12229. llama_kv_cache_seq_keep(ctx->kv_self, seq_id);
  12230. }
  12231. void llama_kv_cache_seq_add(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos delta) {
  12232. if (delta == 0) {
  12233. return;
  12234. }
  12235. llama_kv_cache_seq_add(ctx->kv_self, seq_id, p0, p1, delta);
  12236. }
  12237. void llama_kv_cache_seq_div(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) {
  12238. if (d == 1) {
  12239. return;
  12240. }
  12241. llama_kv_cache_seq_div(ctx->kv_self, seq_id, p0, p1, d);
  12242. }
  12243. llama_pos llama_kv_cache_seq_pos_max(struct llama_context * ctx, llama_seq_id seq_id) {
  12244. return llama_kv_cache_seq_pos_max(ctx->kv_self, seq_id);
  12245. }
  12246. void llama_kv_cache_defrag(struct llama_context * ctx) {
  12247. llama_kv_cache_defrag(ctx->kv_self);
  12248. }
  12249. void llama_kv_cache_update(struct llama_context * ctx) {
  12250. llama_kv_cache_update_internal(*ctx);
  12251. }
  12252. // Returns the *maximum* size of the state
  12253. size_t llama_get_state_size(const struct llama_context * ctx) {
  12254. const auto & cparams = ctx->cparams;
  12255. const auto & hparams = ctx->model.hparams;
  12256. // we don't know size of rng until we actually serialize it. so reserve more than enough memory for its serialized state.
  12257. // for reference, std::mt19937(1337) serializes to 6701 bytes.
  12258. const size_t s_rng_size = sizeof(size_t);
  12259. const size_t s_rng = LLAMA_MAX_RNG_STATE;
  12260. const size_t s_n_outputs = sizeof(size_t);
  12261. // assume worst case for outputs although only currently set ones are serialized
  12262. const size_t s_output_pos = ctx->cparams.n_batch * sizeof(int32_t);
  12263. const size_t s_logits_size = sizeof(size_t);
  12264. const size_t s_logits = ctx->logits_size ? cparams.n_batch * hparams.n_vocab * sizeof(float) : 0;
  12265. const size_t s_embedding_size = sizeof(size_t);
  12266. const size_t s_embedding = ctx->embd_size ? cparams.n_batch * hparams.n_embd * sizeof(float) : 0;
  12267. const size_t s_kv_buf_size = sizeof(size_t);
  12268. const size_t s_kv_head = sizeof(uint32_t);
  12269. const size_t s_kv_size = sizeof(uint32_t);
  12270. const size_t s_kv_used = sizeof(uint32_t);
  12271. const size_t s_kv = ctx->kv_self.total_size();
  12272. const size_t s_kv_cell = sizeof(llama_pos) + sizeof(size_t) + cparams.n_seq_max*sizeof(llama_seq_id);
  12273. const size_t s_kv_cells = ctx->kv_self.size * s_kv_cell;
  12274. const size_t s_total = (
  12275. + s_rng_size
  12276. + s_rng
  12277. + s_n_outputs
  12278. + s_output_pos
  12279. + s_logits_size
  12280. + s_logits
  12281. + s_embedding_size
  12282. + s_embedding
  12283. + s_kv_buf_size
  12284. + s_kv_head
  12285. + s_kv_size
  12286. + s_kv_used
  12287. + s_kv
  12288. + s_kv_cells
  12289. );
  12290. return s_total;
  12291. }
  12292. // llama_context_data
  12293. struct llama_data_context {
  12294. virtual void write(const void * src, size_t size) = 0;
  12295. virtual size_t get_size_written() = 0;
  12296. virtual ~llama_data_context() = default;
  12297. };
  12298. struct llama_data_buffer_context : llama_data_context {
  12299. uint8_t * ptr;
  12300. size_t size_written = 0;
  12301. llama_data_buffer_context(uint8_t * p) : ptr(p) {}
  12302. void write(const void * src, size_t size) override {
  12303. memcpy(ptr, src, size);
  12304. ptr += size;
  12305. size_written += size;
  12306. }
  12307. size_t get_size_written() override {
  12308. return size_written;
  12309. }
  12310. };
  12311. struct llama_data_file_context : llama_data_context {
  12312. llama_file * file;
  12313. size_t size_written = 0;
  12314. llama_data_file_context(llama_file * f) : file(f) {}
  12315. void write(const void * src, size_t size) override {
  12316. file->write_raw(src, size);
  12317. size_written += size;
  12318. }
  12319. size_t get_size_written() override {
  12320. return size_written;
  12321. }
  12322. };
  12323. /** copy state data into either a buffer or file depending on the passed in context
  12324. *
  12325. * file context:
  12326. * llama_file file("/path", "wb");
  12327. * llama_data_file_context data_ctx(&file);
  12328. * llama_copy_state_data(ctx, &data_ctx);
  12329. *
  12330. * buffer context:
  12331. * std::vector<uint8_t> buf(max_size, 0);
  12332. * llama_data_buffer_context data_ctx(&buf.data());
  12333. * llama_copy_state_data(ctx, &data_ctx);
  12334. *
  12335. */
  12336. static void llama_copy_state_data_internal(struct llama_context * ctx, llama_data_context * data_ctx) {
  12337. // copy rng
  12338. {
  12339. std::ostringstream rng_ss;
  12340. rng_ss << ctx->rng;
  12341. const std::string & rng_str = rng_ss.str();
  12342. const size_t rng_size = rng_str.size();
  12343. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  12344. data_ctx->write(&rng_size, sizeof(rng_size));
  12345. data_ctx->write(rng_str.data(), rng_size);
  12346. }
  12347. // copy outputs
  12348. {
  12349. // Can't use ctx->n_outputs because it's not for the
  12350. // entire last batch when n_ubatch is smaller than n_batch
  12351. size_t n_outputs = 0;
  12352. // copy output ids
  12353. {
  12354. std::vector<int32_t> output_pos;
  12355. const size_t n_batch = ctx->cparams.n_batch;
  12356. const auto & output_ids = ctx->output_ids;
  12357. output_pos.resize(ctx->output_size);
  12358. // build a more compact representation of the output ids
  12359. for (size_t i = 0; i < n_batch; ++i) {
  12360. // map an output id to a position in the batch
  12361. int32_t pos = output_ids[i];
  12362. if (pos >= 0) {
  12363. if ((size_t) pos >= n_outputs) {
  12364. n_outputs = pos + 1;
  12365. }
  12366. GGML_ASSERT((size_t) pos < ctx->output_size);
  12367. output_pos[pos] = i;
  12368. }
  12369. }
  12370. data_ctx->write(&n_outputs, sizeof(n_outputs));
  12371. if (n_outputs) {
  12372. data_ctx->write(output_pos.data(), n_outputs * sizeof(int32_t));
  12373. }
  12374. }
  12375. // copy logits
  12376. {
  12377. const size_t logits_size = std::min(ctx->logits_size, n_outputs * ctx->model.hparams.n_vocab);
  12378. data_ctx->write(&logits_size, sizeof(logits_size));
  12379. if (logits_size) {
  12380. data_ctx->write(ctx->logits, logits_size * sizeof(float));
  12381. }
  12382. }
  12383. // copy embeddings
  12384. {
  12385. const size_t embeddings_size = std::min(ctx->embd_size, n_outputs * ctx->model.hparams.n_embd);
  12386. data_ctx->write(&embeddings_size, sizeof(embeddings_size));
  12387. if (embeddings_size) {
  12388. data_ctx->write(ctx->embd, embeddings_size * sizeof(float));
  12389. }
  12390. }
  12391. }
  12392. // copy kv cache
  12393. {
  12394. const auto & kv_self = ctx->kv_self;
  12395. const auto & hparams = ctx->model.hparams;
  12396. const uint32_t n_layer = hparams.n_layer;
  12397. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  12398. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  12399. // NOTE: kv_size and kv_buf_size are mostly used for sanity checks
  12400. const uint32_t kv_head = llama_kv_cache_cell_max(kv_self);
  12401. const uint32_t kv_size = kv_self.size;
  12402. const size_t kv_buf_size = kv_self.total_size() / (kv_size ? kv_size : 1) * kv_head;
  12403. const uint32_t kv_used = kv_self.used;
  12404. data_ctx->write(&kv_buf_size, sizeof(kv_buf_size));
  12405. data_ctx->write(&kv_head, sizeof(kv_head));
  12406. data_ctx->write(&kv_size, sizeof(kv_size));
  12407. data_ctx->write(&kv_used, sizeof(kv_used));
  12408. if (kv_buf_size) {
  12409. const size_t pre_kv_buf_size = data_ctx->get_size_written();
  12410. std::vector<uint8_t> tmp_buf;
  12411. for (int il = 0; il < (int) n_layer; ++il) {
  12412. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_head);
  12413. tmp_buf.resize(k_size);
  12414. ggml_backend_tensor_get(kv_self.k_l[il], tmp_buf.data(), 0, tmp_buf.size());
  12415. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  12416. if (kv_self.recurrent) {
  12417. // v is contiguous for recurrent models
  12418. // TODO: use other tensors for state models than k and v
  12419. const size_t v_size = ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa*kv_head);
  12420. tmp_buf.resize(v_size);
  12421. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), 0, tmp_buf.size());
  12422. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  12423. continue;
  12424. }
  12425. // v is not contiguous, copy row by row
  12426. const size_t v_row_size = ggml_row_size(kv_self.v_l[il]->type, kv_head);
  12427. const size_t v_row_stride = ggml_row_size(kv_self.v_l[il]->type, kv_size);
  12428. tmp_buf.resize(v_row_size);
  12429. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  12430. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), ir*v_row_stride, tmp_buf.size());
  12431. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  12432. }
  12433. }
  12434. GGML_ASSERT(kv_buf_size == data_ctx->get_size_written() - pre_kv_buf_size);
  12435. }
  12436. for (uint32_t i = 0; i < kv_head; ++i) {
  12437. const auto & cell = kv_self.cells[i];
  12438. const llama_pos pos = cell.pos;
  12439. const size_t seq_id_size = cell.seq_id.size();
  12440. data_ctx->write(&pos, sizeof(pos));
  12441. data_ctx->write(&seq_id_size, sizeof(seq_id_size));
  12442. for (auto seq_id : cell.seq_id) {
  12443. data_ctx->write(&seq_id, sizeof(seq_id));
  12444. }
  12445. }
  12446. }
  12447. }
  12448. size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dst) {
  12449. llama_data_buffer_context data_ctx(dst);
  12450. llama_copy_state_data_internal(ctx, &data_ctx);
  12451. return data_ctx.get_size_written();
  12452. }
  12453. // Sets the state reading from the specified source address
  12454. size_t llama_set_state_data(struct llama_context * ctx, const uint8_t * src) {
  12455. const uint8_t * inp = src;
  12456. // set rng
  12457. {
  12458. size_t rng_size;
  12459. memcpy(&rng_size, inp, sizeof(rng_size)); inp += sizeof(rng_size);
  12460. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  12461. std::string rng_str((const char *)inp, rng_size); inp += rng_size;
  12462. std::istringstream rng_ss(rng_str);
  12463. rng_ss >> ctx->rng;
  12464. GGML_ASSERT(!rng_ss.fail());
  12465. }
  12466. // set output ids
  12467. {
  12468. size_t n_outputs;
  12469. std::vector<int32_t> output_pos;
  12470. memcpy(&n_outputs, inp, sizeof(n_outputs)); inp += sizeof(n_outputs);
  12471. GGML_ASSERT(n_outputs <= llama_output_reserve(*ctx, n_outputs));
  12472. if (n_outputs) {
  12473. output_pos.resize(n_outputs);
  12474. memcpy(output_pos.data(), inp, n_outputs * sizeof(int32_t));
  12475. inp += n_outputs * sizeof(int32_t);
  12476. for (int32_t i = 0; i < (int32_t) output_pos.size(); ++i) {
  12477. int32_t id = output_pos[i];
  12478. GGML_ASSERT((uint32_t) id < ctx->cparams.n_batch);
  12479. ctx->output_ids[id] = i;
  12480. }
  12481. }
  12482. }
  12483. // set logits
  12484. {
  12485. size_t logits_size;
  12486. memcpy(&logits_size, inp, sizeof(logits_size)); inp += sizeof(logits_size);
  12487. GGML_ASSERT(ctx->logits_size >= logits_size);
  12488. if (logits_size) {
  12489. memcpy(ctx->logits, inp, logits_size * sizeof(float));
  12490. inp += logits_size * sizeof(float);
  12491. }
  12492. }
  12493. // set embeddings
  12494. {
  12495. size_t embeddings_size;
  12496. memcpy(&embeddings_size, inp, sizeof(embeddings_size)); inp += sizeof(embeddings_size);
  12497. GGML_ASSERT(ctx->embd_size >= embeddings_size);
  12498. if (embeddings_size) {
  12499. memcpy(ctx->embd, inp, embeddings_size * sizeof(float));
  12500. inp += embeddings_size * sizeof(float);
  12501. }
  12502. }
  12503. // set kv cache
  12504. {
  12505. const auto & kv_self = ctx->kv_self;
  12506. const auto & hparams = ctx->model.hparams;
  12507. const uint32_t n_layer = hparams.n_layer;
  12508. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  12509. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  12510. size_t kv_buf_size;
  12511. uint32_t kv_head;
  12512. uint32_t kv_size;
  12513. uint32_t kv_used;
  12514. memcpy(&kv_buf_size, inp, sizeof(kv_buf_size)); inp += sizeof(kv_buf_size);
  12515. memcpy(&kv_head, inp, sizeof(kv_head)); inp += sizeof(kv_head);
  12516. memcpy(&kv_size, inp, sizeof(kv_size)); inp += sizeof(kv_size);
  12517. memcpy(&kv_used, inp, sizeof(kv_used)); inp += sizeof(kv_used);
  12518. if (kv_self.size != kv_size) {
  12519. // the KV cache needs to be big enough to load all the KV cells from the saved state
  12520. GGML_ASSERT(kv_self.size >= kv_head);
  12521. 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",
  12522. __func__, kv_head, kv_size, kv_self.size);
  12523. }
  12524. if (kv_buf_size) {
  12525. const size_t pre_kv_buf_size = inp - src;
  12526. GGML_ASSERT(kv_self.total_size() >= kv_buf_size);
  12527. for (int il = 0; il < (int) n_layer; ++il) {
  12528. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_head);
  12529. ggml_backend_tensor_set(kv_self.k_l[il], inp, 0, k_size);
  12530. inp += k_size;
  12531. if (kv_self.recurrent) {
  12532. // v is contiguous for recurrent models
  12533. // TODO: use other tensors for state models than k and v
  12534. const size_t v_size = ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa*kv_head);
  12535. ggml_backend_tensor_set(kv_self.v_l[il], inp, 0, v_size);
  12536. inp += v_size;
  12537. continue;
  12538. }
  12539. // v is not contiguous, copy row by row
  12540. const size_t v_row_size = ggml_row_size(kv_self.v_l[il]->type, kv_head);
  12541. const size_t v_row_stride = ggml_row_size(kv_self.v_l[il]->type, kv_self.size);
  12542. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  12543. ggml_backend_tensor_set(kv_self.v_l[il], inp, ir*v_row_stride, v_row_size);
  12544. inp += v_row_size;
  12545. }
  12546. }
  12547. GGML_ASSERT(kv_buf_size == inp - src - pre_kv_buf_size);
  12548. }
  12549. llama_kv_cache_clear(ctx);
  12550. ctx->kv_self.head = kv_head;
  12551. ctx->kv_self.used = kv_used;
  12552. for (uint32_t i = 0; i < kv_head; ++i) {
  12553. llama_pos pos;
  12554. size_t seq_id_size;
  12555. memcpy(&pos, inp, sizeof(pos)); inp += sizeof(pos);
  12556. memcpy(&seq_id_size, inp, sizeof(seq_id_size)); inp += sizeof(seq_id_size);
  12557. ctx->kv_self.cells[i].pos = pos;
  12558. llama_seq_id seq_id;
  12559. for (size_t j = 0; j < seq_id_size; ++j) {
  12560. memcpy(&seq_id, inp, sizeof(seq_id)); inp += sizeof(seq_id);
  12561. ctx->kv_self.cells[i].seq_id.insert(seq_id);
  12562. }
  12563. }
  12564. }
  12565. const size_t nread = inp - src;
  12566. const size_t max_size = llama_get_state_size(ctx);
  12567. GGML_ASSERT(nread <= max_size);
  12568. return nread;
  12569. }
  12570. 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) {
  12571. llama_file file(path_session, "rb");
  12572. // sanity checks
  12573. {
  12574. const uint32_t magic = file.read_u32();
  12575. const uint32_t version = file.read_u32();
  12576. if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
  12577. LLAMA_LOG_ERROR("%s : unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
  12578. return false;
  12579. }
  12580. llama_hparams session_hparams;
  12581. file.read_raw(&session_hparams, sizeof(llama_hparams));
  12582. if (session_hparams != ctx->model.hparams) {
  12583. LLAMA_LOG_INFO("%s : model hparams didn't match from session file!\n", __func__);
  12584. return false;
  12585. }
  12586. }
  12587. // load the prompt
  12588. {
  12589. const uint32_t n_token_count = file.read_u32();
  12590. if (n_token_count > n_token_capacity) {
  12591. LLAMA_LOG_ERROR("%s : token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  12592. return false;
  12593. }
  12594. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  12595. *n_token_count_out = n_token_count;
  12596. }
  12597. // restore the context state
  12598. {
  12599. const size_t n_state_size_cur = file.size - file.tell();
  12600. const size_t n_state_size_max = llama_get_state_size(ctx);
  12601. if (n_state_size_cur > n_state_size_max) {
  12602. 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);
  12603. return false;
  12604. }
  12605. std::vector<uint8_t> state_data(n_state_size_max);
  12606. file.read_raw(state_data.data(), n_state_size_cur);
  12607. llama_set_state_data(ctx, state_data.data());
  12608. }
  12609. return true;
  12610. }
  12611. 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) {
  12612. try {
  12613. return llama_load_session_file_internal(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  12614. } catch (const std::exception & err) {
  12615. LLAMA_LOG_ERROR("error loading session file: %s\n", err.what());
  12616. return false;
  12617. }
  12618. }
  12619. bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  12620. llama_file file(path_session, "wb");
  12621. file.write_u32(LLAMA_SESSION_MAGIC);
  12622. file.write_u32(LLAMA_SESSION_VERSION);
  12623. file.write_raw(&ctx->model.hparams, sizeof(llama_hparams));
  12624. // save the prompt
  12625. file.write_u32((uint32_t) n_token_count);
  12626. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  12627. // save the context state using stream saving
  12628. llama_data_file_context data_ctx(&file);
  12629. llama_copy_state_data_internal(ctx, &data_ctx);
  12630. return true;
  12631. }
  12632. void llama_set_n_threads(struct llama_context * ctx, uint32_t n_threads, uint32_t n_threads_batch) {
  12633. ctx->cparams.n_threads = n_threads;
  12634. ctx->cparams.n_threads_batch = n_threads_batch;
  12635. }
  12636. void llama_set_abort_callback(struct llama_context * ctx, bool (*abort_callback)(void * data), void * abort_callback_data) {
  12637. ctx->abort_callback = abort_callback;
  12638. ctx->abort_callback_data = abort_callback_data;
  12639. }
  12640. void llama_set_causal_attn(struct llama_context * ctx, bool causal_attn) {
  12641. ctx->cparams.causal_attn = causal_attn;
  12642. }
  12643. struct llama_batch llama_batch_get_one(
  12644. llama_token * tokens,
  12645. int32_t n_tokens,
  12646. llama_pos pos_0,
  12647. llama_seq_id seq_id) {
  12648. return {
  12649. /*n_tokens =*/ n_tokens,
  12650. /*tokens =*/ tokens,
  12651. /*embd =*/ nullptr,
  12652. /*pos =*/ nullptr,
  12653. /*n_seq_id =*/ nullptr,
  12654. /*seq_id =*/ nullptr,
  12655. /*logits =*/ nullptr,
  12656. /*all_pos_0 =*/ pos_0,
  12657. /*all_pos_1 =*/ 1,
  12658. /*all_seq_id =*/ seq_id,
  12659. };
  12660. }
  12661. struct llama_batch llama_batch_init(int32_t n_tokens_alloc, int32_t embd, int32_t n_seq_max) {
  12662. llama_batch batch = { 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, 0, 0, 0, };
  12663. if (embd) {
  12664. batch.embd = (float *) malloc(sizeof(float) * n_tokens_alloc * embd);
  12665. } else {
  12666. batch.token = (llama_token *) malloc(sizeof(llama_token) * n_tokens_alloc);
  12667. }
  12668. batch.pos = (llama_pos *) malloc(sizeof(llama_pos) * n_tokens_alloc);
  12669. batch.n_seq_id = (int32_t *) malloc(sizeof(int32_t) * n_tokens_alloc);
  12670. batch.seq_id = (llama_seq_id **) malloc(sizeof(llama_seq_id *) * (n_tokens_alloc + 1));
  12671. for (int i = 0; i < n_tokens_alloc; ++i) {
  12672. batch.seq_id[i] = (llama_seq_id *) malloc(sizeof(llama_seq_id) * n_seq_max);
  12673. }
  12674. batch.seq_id[n_tokens_alloc] = nullptr;
  12675. batch.logits = (int8_t *) malloc(sizeof(int8_t) * n_tokens_alloc);
  12676. return batch;
  12677. }
  12678. void llama_batch_free(struct llama_batch batch) {
  12679. if (batch.token) free(batch.token);
  12680. if (batch.embd) free(batch.embd);
  12681. if (batch.pos) free(batch.pos);
  12682. if (batch.n_seq_id) free(batch.n_seq_id);
  12683. if (batch.seq_id) {
  12684. for (int i = 0; batch.seq_id[i] != nullptr; ++i) {
  12685. free(batch.seq_id[i]);
  12686. }
  12687. free(batch.seq_id);
  12688. }
  12689. if (batch.logits) free(batch.logits);
  12690. }
  12691. int32_t llama_decode(
  12692. struct llama_context * ctx,
  12693. struct llama_batch batch) {
  12694. const int ret = llama_decode_internal(*ctx, batch);
  12695. if (ret < 0) {
  12696. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  12697. }
  12698. return ret;
  12699. }
  12700. void llama_synchronize(struct llama_context * ctx) {
  12701. ggml_backend_sched_synchronize(ctx->sched);
  12702. // FIXME: if multiple single tokens are evaluated without a synchronization,
  12703. // the stats will be added to the prompt evaluation stats
  12704. // this should only happen when using batch size 1 to evaluate a batch
  12705. // add the evaluation to the stats
  12706. if (ctx->n_queued_tokens == 1) {
  12707. ctx->t_eval_us += ggml_time_us() - ctx->t_compute_start_us;
  12708. ctx->n_eval++;
  12709. } else if (ctx->n_queued_tokens > 1) {
  12710. ctx->t_p_eval_us += ggml_time_us() - ctx->t_compute_start_us;
  12711. ctx->n_p_eval += ctx->n_queued_tokens;
  12712. }
  12713. // get a more accurate load time, upon first eval
  12714. if (ctx->n_queued_tokens > 0 && !ctx->has_evaluated_once) {
  12715. ctx->t_load_us = ggml_time_us() - ctx->t_start_us;
  12716. ctx->has_evaluated_once = true;
  12717. }
  12718. ctx->n_queued_tokens = 0;
  12719. ctx->t_compute_start_us = 0;
  12720. }
  12721. float * llama_get_logits(struct llama_context * ctx) {
  12722. llama_synchronize(ctx);
  12723. return ctx->logits;
  12724. }
  12725. float * llama_get_logits_ith(struct llama_context * ctx, int32_t i) {
  12726. llama_synchronize(ctx);
  12727. try {
  12728. if (ctx->logits == nullptr) {
  12729. throw std::runtime_error("no logits");
  12730. }
  12731. if ((size_t) i >= ctx->output_ids.size()) {
  12732. throw std::runtime_error(format("out of range [0, %lu)", ctx->output_ids.size()));
  12733. }
  12734. const int32_t j = ctx->output_ids[i];
  12735. if (j < 0) {
  12736. throw std::runtime_error(format("batch.logits[%d] != true", i));
  12737. }
  12738. if ((size_t) j >= ctx->output_size) {
  12739. // This should not happen
  12740. throw std::runtime_error(format("corrupt output buffer (j=%d, output_size=%lu)", j, ctx->output_size));
  12741. }
  12742. return ctx->logits + j*ctx->model.hparams.n_vocab;
  12743. } catch (const std::exception & err) {
  12744. LLAMA_LOG_ERROR("%s: invalid logits id %d, reason: %s\n", __func__, i, err.what());
  12745. #ifndef NDEBUG
  12746. GGML_ASSERT(false);
  12747. #endif
  12748. return nullptr;
  12749. }
  12750. }
  12751. float * llama_get_embeddings(struct llama_context * ctx) {
  12752. llama_synchronize(ctx);
  12753. return ctx->embd;
  12754. }
  12755. float * llama_get_embeddings_ith(struct llama_context * ctx, int32_t i) {
  12756. llama_synchronize(ctx);
  12757. try {
  12758. if (ctx->embd == nullptr) {
  12759. throw std::runtime_error("no embeddings");
  12760. }
  12761. if ((size_t) i >= ctx->output_ids.size()) {
  12762. throw std::runtime_error(format("out of range [0, %lu)", ctx->output_ids.size()));
  12763. }
  12764. const int32_t j = ctx->output_ids[i];
  12765. if (j < 0) {
  12766. throw std::runtime_error(format("batch.logits[%d] != true", i));
  12767. }
  12768. if ((size_t) j >= ctx->output_size) {
  12769. // This should not happen
  12770. throw std::runtime_error(format("corrupt output buffer (j=%d, output_size=%lu)", j, ctx->output_size));
  12771. }
  12772. return ctx->embd + j*ctx->model.hparams.n_embd;
  12773. } catch (const std::exception & err) {
  12774. LLAMA_LOG_ERROR("%s: invalid embeddings id %d, reason: %s\n", __func__, i, err.what());
  12775. #ifndef NDEBUG
  12776. GGML_ASSERT(false);
  12777. #endif
  12778. return nullptr;
  12779. }
  12780. }
  12781. float * llama_get_embeddings_seq(struct llama_context * ctx, llama_seq_id seq_id) {
  12782. llama_synchronize(ctx);
  12783. auto it = ctx->embd_seq.find(seq_id);
  12784. if (it == ctx->embd_seq.end()) {
  12785. return nullptr;
  12786. }
  12787. return it->second.data();
  12788. }
  12789. const char * llama_token_get_text(const struct llama_model * model, llama_token token) {
  12790. GGML_ASSERT(model->vocab.type != LLAMA_VOCAB_TYPE_NONE);
  12791. return model->vocab.id_to_token[token].text.c_str();
  12792. }
  12793. float llama_token_get_score(const struct llama_model * model, llama_token token) {
  12794. GGML_ASSERT(model->vocab.type != LLAMA_VOCAB_TYPE_NONE);
  12795. return model->vocab.id_to_token[token].score;
  12796. }
  12797. llama_token_type llama_token_get_type(const struct llama_model * model, llama_token token) {
  12798. GGML_ASSERT(model->vocab.type != LLAMA_VOCAB_TYPE_NONE);
  12799. return model->vocab.id_to_token[token].type;
  12800. }
  12801. llama_token llama_token_bos(const struct llama_model * model) {
  12802. return model->vocab.special_bos_id;
  12803. }
  12804. llama_token llama_token_eos(const struct llama_model * model) {
  12805. return model->vocab.special_eos_id;
  12806. }
  12807. llama_token llama_token_nl(const struct llama_model * model) {
  12808. return model->vocab.linefeed_id;
  12809. }
  12810. int32_t llama_add_bos_token(const struct llama_model * model) {
  12811. return model->vocab.special_add_bos;
  12812. }
  12813. int32_t llama_add_eos_token(const struct llama_model * model) {
  12814. return model->vocab.special_add_eos;
  12815. }
  12816. llama_token llama_token_prefix(const struct llama_model * model) {
  12817. return model->vocab.special_prefix_id;
  12818. }
  12819. llama_token llama_token_middle(const struct llama_model * model) {
  12820. return model->vocab.special_middle_id;
  12821. }
  12822. llama_token llama_token_suffix(const struct llama_model * model) {
  12823. return model->vocab.special_suffix_id;
  12824. }
  12825. llama_token llama_token_eot(const struct llama_model * model) {
  12826. return model->vocab.special_eot_id;
  12827. }
  12828. int32_t llama_tokenize(
  12829. const struct llama_model * model,
  12830. const char * text,
  12831. int32_t text_len,
  12832. llama_token * tokens,
  12833. int32_t n_tokens_max,
  12834. bool add_bos,
  12835. bool special) {
  12836. auto res = llama_tokenize_internal(model->vocab, std::string(text, text_len), add_bos, special);
  12837. if (n_tokens_max < (int) res.size()) {
  12838. // LLAMA_LOG_ERROR("%s: too many tokens\n", __func__);
  12839. return -((int) res.size());
  12840. }
  12841. for (size_t i = 0; i < res.size(); i++) {
  12842. tokens[i] = res[i];
  12843. }
  12844. return res.size();
  12845. }
  12846. static std::string llama_decode_text(const std::string & text) {
  12847. std::string decoded_text;
  12848. auto unicode_sequences = unicode_cpts_from_utf8(text);
  12849. for (auto & unicode_sequence : unicode_sequences) {
  12850. decoded_text += unicode_utf8_to_byte(unicode_cpt_to_utf8(unicode_sequence));
  12851. }
  12852. return decoded_text;
  12853. }
  12854. // does not write null-terminator to buf
  12855. int32_t llama_token_to_piece(const struct llama_model * model, llama_token token, char * buf, int32_t length) {
  12856. if (0 <= token && token < llama_n_vocab(model)) {
  12857. switch (llama_vocab_get_type(model->vocab)) {
  12858. case LLAMA_VOCAB_TYPE_WPM:
  12859. case LLAMA_VOCAB_TYPE_SPM: {
  12860. // NOTE: we accept all unsupported token types,
  12861. // suppressing them like CONTROL tokens.
  12862. if (llama_is_normal_token(model->vocab, token)) {
  12863. std::string result = model->vocab.id_to_token[token].text;
  12864. llama_unescape_whitespace(result);
  12865. if (length < (int) result.length()) {
  12866. return -(int) result.length();
  12867. }
  12868. memcpy(buf, result.c_str(), result.length());
  12869. return result.length();
  12870. } else if (llama_is_user_defined_token(model->vocab, token)) {
  12871. std::string result = model->vocab.id_to_token[token].text;
  12872. if (length < (int) result.length()) {
  12873. return -(int) result.length();
  12874. }
  12875. memcpy(buf, result.c_str(), result.length());
  12876. return result.length();
  12877. } else if (llama_is_unknown_token(model->vocab, token)) { // NOLINT
  12878. if (length < 3) {
  12879. return -3;
  12880. }
  12881. memcpy(buf, "\xe2\x96\x85", 3);
  12882. return 3;
  12883. } else if (llama_is_control_token(model->vocab, token)) {
  12884. ;
  12885. } else if (llama_is_byte_token(model->vocab, token)) {
  12886. if (length < 1) {
  12887. return -1;
  12888. }
  12889. buf[0] = llama_token_to_byte(model->vocab, token);
  12890. return 1;
  12891. }
  12892. break;
  12893. }
  12894. case LLAMA_VOCAB_TYPE_BPE: {
  12895. // NOTE: we accept all unsupported token types,
  12896. // suppressing them like CONTROL tokens.
  12897. if (llama_is_normal_token(model->vocab, token)) {
  12898. std::string result = model->vocab.id_to_token[token].text;
  12899. result = llama_decode_text(result);
  12900. if (length < (int) result.length()) {
  12901. return -(int) result.length();
  12902. }
  12903. memcpy(buf, result.c_str(), result.length());
  12904. return result.length();
  12905. } else if (llama_is_user_defined_token(model->vocab, token)) {
  12906. std::string result = model->vocab.id_to_token[token].text;
  12907. if (length < (int) result.length()) {
  12908. return -(int) result.length();
  12909. }
  12910. memcpy(buf, result.c_str(), result.length());
  12911. return result.length();
  12912. } else if (llama_is_control_token(model->vocab, token)) {
  12913. ;
  12914. }
  12915. break;
  12916. }
  12917. default:
  12918. GGML_ASSERT(false);
  12919. }
  12920. }
  12921. return 0;
  12922. }
  12923. // trim whitespace from the beginning and end of a string
  12924. static std::string trim(const std::string & str) {
  12925. size_t start = 0;
  12926. size_t end = str.size();
  12927. while (start < end && isspace(str[start])) {
  12928. start += 1;
  12929. }
  12930. while (end > start && isspace(str[end - 1])) {
  12931. end -= 1;
  12932. }
  12933. return str.substr(start, end - start);
  12934. }
  12935. // Simple version of "llama_apply_chat_template" that only works with strings
  12936. // This function uses heuristic checks to determine commonly used template. It is not a jinja parser.
  12937. static int32_t llama_chat_apply_template_internal(
  12938. const std::string & tmpl,
  12939. const std::vector<const llama_chat_message *> & chat,
  12940. std::string & dest, bool add_ass) {
  12941. // Taken from the research: https://github.com/ggerganov/llama.cpp/issues/5527
  12942. std::stringstream ss;
  12943. if (tmpl == "chatml" || tmpl.find("<|im_start|>") != std::string::npos) {
  12944. // chatml template
  12945. for (auto message : chat) {
  12946. ss << "<|im_start|>" << message->role << "\n" << message->content << "<|im_end|>\n";
  12947. }
  12948. if (add_ass) {
  12949. ss << "<|im_start|>assistant\n";
  12950. }
  12951. } else if (tmpl == "llama2" || tmpl.find("[INST]") != std::string::npos) {
  12952. // llama2 template and its variants
  12953. // [variant] support system message
  12954. bool support_system_message = tmpl.find("<<SYS>>") != std::string::npos;
  12955. // [variant] space before + after response
  12956. bool space_around_response = tmpl.find("' ' + eos_token") != std::string::npos;
  12957. // [variant] add BOS inside history
  12958. bool add_bos_inside_history = tmpl.find("bos_token + '[INST]") != std::string::npos;
  12959. // [variant] trim spaces from the input message
  12960. bool strip_message = tmpl.find("content.strip()") != std::string::npos;
  12961. // construct the prompt
  12962. bool is_inside_turn = true; // skip BOS at the beginning
  12963. ss << "[INST] ";
  12964. for (auto message : chat) {
  12965. std::string content = strip_message ? trim(message->content) : message->content;
  12966. std::string role(message->role);
  12967. if (!is_inside_turn) {
  12968. is_inside_turn = true;
  12969. ss << (add_bos_inside_history ? "<s>[INST] " : "[INST] ");
  12970. }
  12971. if (role == "system") {
  12972. if (support_system_message) {
  12973. ss << "<<SYS>>\n" << content << "\n<</SYS>>\n\n";
  12974. } else {
  12975. // if the model does not support system message, we still include it in the first message, but without <<SYS>>
  12976. ss << content << "\n";
  12977. }
  12978. } else if (role == "user") {
  12979. ss << content << " [/INST]";
  12980. } else {
  12981. ss << (space_around_response ? " " : "") << content << (space_around_response ? " " : "") << "</s>";
  12982. is_inside_turn = false;
  12983. }
  12984. }
  12985. // llama2 templates seem to not care about "add_generation_prompt"
  12986. } else if (tmpl == "zephyr" || tmpl.find("<|user|>") != std::string::npos) {
  12987. // zephyr template
  12988. for (auto message : chat) {
  12989. ss << "<|" << message->role << "|>" << "\n" << message->content << "<|endoftext|>\n";
  12990. }
  12991. if (add_ass) {
  12992. ss << "<|assistant|>\n";
  12993. }
  12994. } else if (tmpl == "monarch" || tmpl.find("bos_token + message['role']") != std::string::npos) {
  12995. // mlabonne/AlphaMonarch-7B template (the <s> is included inside history)
  12996. for (auto message : chat) {
  12997. std::string bos = (message == chat.front()) ? "" : "<s>"; // skip BOS for first message
  12998. ss << bos << message->role << "\n" << message->content << "</s>\n";
  12999. }
  13000. if (add_ass) {
  13001. ss << "<s>assistant\n";
  13002. }
  13003. } else if (tmpl == "gemma" || tmpl.find("<start_of_turn>") != std::string::npos) {
  13004. // google/gemma-7b-it
  13005. std::string system_prompt = "";
  13006. for (auto message : chat) {
  13007. std::string role(message->role);
  13008. if (role == "system") {
  13009. // there is no system message for gemma, but we will merge it with user prompt, so nothing is broken
  13010. system_prompt = trim(message->content);
  13011. continue;
  13012. }
  13013. // in gemma, "assistant" is "model"
  13014. role = role == "assistant" ? "model" : message->role;
  13015. ss << "<start_of_turn>" << role << "\n";
  13016. if (!system_prompt.empty() && role != "model") {
  13017. ss << system_prompt << "\n\n";
  13018. system_prompt = "";
  13019. }
  13020. ss << trim(message->content) << "<end_of_turn>\n";
  13021. }
  13022. if (add_ass) {
  13023. ss << "<start_of_turn>model\n";
  13024. }
  13025. } else if (tmpl == "orion" || tmpl.find("'\\n\\nAssistant: ' + eos_token") != std::string::npos) {
  13026. // OrionStarAI/Orion-14B-Chat
  13027. std::string system_prompt = "";
  13028. for (auto message : chat) {
  13029. std::string role(message->role);
  13030. if (role == "system") {
  13031. // there is no system message support, we will merge it with user prompt
  13032. system_prompt = message->content;
  13033. continue;
  13034. } else if (role == "user") {
  13035. ss << "Human: ";
  13036. if (!system_prompt.empty()) {
  13037. ss << system_prompt << "\n\n";
  13038. system_prompt = "";
  13039. }
  13040. ss << message->content << "\n\nAssistant: </s>";
  13041. } else {
  13042. ss << message->content << "</s>";
  13043. }
  13044. }
  13045. } else {
  13046. // template not supported
  13047. return -1;
  13048. }
  13049. dest = ss.str();
  13050. return dest.size();
  13051. }
  13052. LLAMA_API int32_t llama_chat_apply_template(
  13053. const struct llama_model * model,
  13054. const char * tmpl,
  13055. const struct llama_chat_message * chat,
  13056. size_t n_msg,
  13057. bool add_ass,
  13058. char * buf,
  13059. int32_t length) {
  13060. std::string curr_tmpl(tmpl == nullptr ? "" : tmpl);
  13061. if (tmpl == nullptr) {
  13062. GGML_ASSERT(model != nullptr);
  13063. // load template from model
  13064. std::vector<char> model_template(2048, 0); // longest known template is about 1200 bytes
  13065. std::string template_key = "tokenizer.chat_template";
  13066. int32_t res = llama_model_meta_val_str(model, template_key.c_str(), model_template.data(), model_template.size());
  13067. if (res < 0) {
  13068. // worst case: there is no information about template, we will use chatml by default
  13069. curr_tmpl = "chatml"; // see llama_chat_apply_template_internal
  13070. } else {
  13071. curr_tmpl = std::string(model_template.data(), model_template.size());
  13072. }
  13073. }
  13074. // format the chat to string
  13075. std::vector<const llama_chat_message *> chat_vec;
  13076. chat_vec.resize(n_msg);
  13077. for (size_t i = 0; i < n_msg; i++) {
  13078. chat_vec[i] = &chat[i];
  13079. }
  13080. std::string formatted_chat;
  13081. int32_t res = llama_chat_apply_template_internal(curr_tmpl, chat_vec, formatted_chat, add_ass);
  13082. if (res < 0) {
  13083. return res;
  13084. }
  13085. if (buf && length > 0) {
  13086. strncpy(buf, formatted_chat.c_str(), length);
  13087. }
  13088. return res;
  13089. }
  13090. LLAMA_API int llama_split_path(char * split_path, size_t maxlen, const char * path_prefix, int split_no, int split_count) {
  13091. static const char * const SPLIT_PATH_FORMAT = "%s-%05d-of-%05d.gguf";
  13092. if (snprintf(split_path, maxlen, SPLIT_PATH_FORMAT, path_prefix, split_no + 1, split_count)) {
  13093. return strlen(split_path);
  13094. }
  13095. return 0;
  13096. }
  13097. int llama_split_prefix(char * dest, size_t maxlen, const char * split_path, int split_no, int split_count) {
  13098. std::string str_split_path(split_path);
  13099. char postfix[32];
  13100. snprintf(postfix, 32, "-%05d-of-%05d.gguf", split_no + 1, split_count);
  13101. std::string str_postfix(postfix);
  13102. // check if dest ends with postfix
  13103. int size_prefix = str_split_path.size() - str_postfix.size();
  13104. if (size_prefix > 0 && str_split_path.find(str_postfix, size_prefix) != std::string::npos) {
  13105. snprintf(dest, std::min((size_t) size_prefix + 1, maxlen), "%s", split_path);
  13106. return size_prefix;
  13107. }
  13108. return 0;
  13109. }
  13110. struct llama_timings llama_get_timings(struct llama_context * ctx) {
  13111. struct llama_timings result = {
  13112. /*.t_start_ms =*/ 1e-3 * ctx->t_start_us,
  13113. /*.t_end_ms =*/ 1.00 * ggml_time_ms(),
  13114. /*.t_load_ms =*/ 1e-3 * ctx->t_load_us,
  13115. /*.t_sample_ms =*/ 1e-3 * ctx->t_sample_us,
  13116. /*.t_p_eval_ms =*/ 1e-3 * ctx->t_p_eval_us,
  13117. /*.t_eval_ms =*/ 1e-3 * ctx->t_eval_us,
  13118. /*.n_sample =*/ std::max(1, ctx->n_sample),
  13119. /*.n_p_eval =*/ std::max(1, ctx->n_p_eval),
  13120. /*.n_eval =*/ std::max(1, ctx->n_eval),
  13121. };
  13122. return result;
  13123. }
  13124. void llama_print_timings(struct llama_context * ctx) {
  13125. const llama_timings timings = llama_get_timings(ctx);
  13126. LLAMA_LOG_INFO("\n");
  13127. LLAMA_LOG_INFO("%s: load time = %10.2f ms\n", __func__, timings.t_load_ms);
  13128. LLAMA_LOG_INFO("%s: sample time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  13129. __func__, timings.t_sample_ms, timings.n_sample, timings.t_sample_ms / timings.n_sample, 1e3 / timings.t_sample_ms * timings.n_sample);
  13130. LLAMA_LOG_INFO("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  13131. __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);
  13132. LLAMA_LOG_INFO("%s: eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  13133. __func__, timings.t_eval_ms, timings.n_eval, timings.t_eval_ms / timings.n_eval, 1e3 / timings.t_eval_ms * timings.n_eval);
  13134. 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));
  13135. }
  13136. void llama_reset_timings(struct llama_context * ctx) {
  13137. ctx->t_start_us = ggml_time_us();
  13138. ctx->t_sample_us = ctx->n_sample = 0;
  13139. ctx->t_eval_us = ctx->n_eval = 0;
  13140. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  13141. }
  13142. const char * llama_print_system_info(void) {
  13143. static std::string s;
  13144. s = "";
  13145. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  13146. s += "AVX_VNNI = " + std::to_string(ggml_cpu_has_avx_vnni()) + " | ";
  13147. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  13148. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  13149. s += "AVX512_VBMI = " + std::to_string(ggml_cpu_has_avx512_vbmi()) + " | ";
  13150. s += "AVX512_VNNI = " + std::to_string(ggml_cpu_has_avx512_vnni()) + " | ";
  13151. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  13152. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  13153. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  13154. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  13155. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  13156. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  13157. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  13158. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  13159. s += "SSSE3 = " + std::to_string(ggml_cpu_has_ssse3()) + " | ";
  13160. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  13161. s += "MATMUL_INT8 = " + std::to_string(ggml_cpu_has_matmul_int8()) + " | ";
  13162. return s.c_str();
  13163. }
  13164. void llama_dump_timing_info_yaml(FILE * stream, const llama_context * ctx) {
  13165. fprintf(stream, "\n");
  13166. fprintf(stream, "###########\n");
  13167. fprintf(stream, "# Timings #\n");
  13168. fprintf(stream, "###########\n");
  13169. fprintf(stream, "\n");
  13170. fprintf(stream, "mst_eval: %.2f # ms / token during generation\n",
  13171. 1.0e-3 * ctx->t_eval_us / ctx->n_eval);
  13172. fprintf(stream, "mst_p_eval: %.2f # ms / token during prompt processing\n",
  13173. 1.0e-3 * ctx->t_p_eval_us / ctx->n_p_eval);
  13174. fprintf(stream, "mst_sample: %.2f # ms / token during sampling\n",
  13175. 1.0e-3 * ctx->t_sample_us / ctx->n_sample);
  13176. fprintf(stream, "n_eval: %d # number of tokens generated (excluding the first one)\n", ctx->n_eval);
  13177. fprintf(stream, "n_p_eval: %d # number of tokens processed in batches at the beginning\n", ctx->n_p_eval);
  13178. fprintf(stream, "n_sample: %d # number of sampled tokens\n", ctx->n_sample);
  13179. fprintf(stream, "t_eval_us: %" PRId64 " # total microseconds spent generating tokens\n", ctx->t_eval_us);
  13180. fprintf(stream, "t_load_us: %" PRId64 " # total microseconds spent loading the model\n", ctx->t_load_us);
  13181. fprintf(stream, "t_p_eval_us: %" PRId64 " # total microseconds spent prompt processing\n", ctx->t_p_eval_us);
  13182. fprintf(stream, "t_sample_us: %" PRId64 " # total microseconds spent sampling\n", ctx->t_sample_us);
  13183. fprintf(stream, "ts_eval: %.2f # tokens / second during generation\n",
  13184. 1.0e6 * ctx->n_eval / ctx->t_eval_us);
  13185. fprintf(stream, "ts_p_eval: %.2f # tokens / second during prompt processing\n",
  13186. 1.0e6 * ctx->n_p_eval / ctx->t_p_eval_us);
  13187. fprintf(stream, "ts_sample: %.2f # tokens / second during sampling\n",
  13188. 1.0e6 * ctx->n_sample / ctx->t_sample_us);
  13189. }
  13190. // For internal test use
  13191. const std::vector<std::pair<std::string, struct ggml_tensor *>> & llama_internal_get_tensor_map(
  13192. struct llama_context * ctx
  13193. ) {
  13194. return ctx->model.tensors_by_name;
  13195. }
  13196. void llama_log_set(ggml_log_callback log_callback, void * user_data) {
  13197. g_state.log_callback = log_callback ? log_callback : llama_log_callback_default;
  13198. g_state.log_callback_user_data = user_data;
  13199. #ifdef GGML_USE_METAL
  13200. ggml_backend_metal_log_set_callback(g_state.log_callback, g_state.log_callback_user_data);
  13201. #endif
  13202. }
  13203. static void llama_log_internal_v(ggml_log_level level, const char * format, va_list args) {
  13204. va_list args_copy;
  13205. va_copy(args_copy, args);
  13206. char buffer[128];
  13207. int len = vsnprintf(buffer, 128, format, args);
  13208. if (len < 128) {
  13209. g_state.log_callback(level, buffer, g_state.log_callback_user_data);
  13210. } else {
  13211. char* buffer2 = new char[len+1];
  13212. vsnprintf(buffer2, len+1, format, args_copy);
  13213. buffer2[len] = 0;
  13214. g_state.log_callback(level, buffer2, g_state.log_callback_user_data);
  13215. delete[] buffer2;
  13216. }
  13217. va_end(args_copy);
  13218. }
  13219. static void llama_log_internal(ggml_log_level level, const char * format, ...) {
  13220. va_list args;
  13221. va_start(args, format);
  13222. llama_log_internal_v(level, format, args);
  13223. va_end(args);
  13224. }
  13225. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data) {
  13226. (void) level;
  13227. (void) user_data;
  13228. fputs(text, stderr);
  13229. fflush(stderr);
  13230. }