llama.cpp 615 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735
  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_COMMAND_R,
  197. LLM_ARCH_UNKNOWN,
  198. };
  199. static const std::map<llm_arch, const char *> LLM_ARCH_NAMES = {
  200. { LLM_ARCH_LLAMA, "llama" },
  201. { LLM_ARCH_FALCON, "falcon" },
  202. { LLM_ARCH_GROK, "grok" },
  203. { LLM_ARCH_GPT2, "gpt2" },
  204. { LLM_ARCH_GPTJ, "gptj" },
  205. { LLM_ARCH_GPTNEOX, "gptneox" },
  206. { LLM_ARCH_MPT, "mpt" },
  207. { LLM_ARCH_BAICHUAN, "baichuan" },
  208. { LLM_ARCH_STARCODER, "starcoder" },
  209. { LLM_ARCH_PERSIMMON, "persimmon" },
  210. { LLM_ARCH_REFACT, "refact" },
  211. { LLM_ARCH_BERT, "bert" },
  212. { LLM_ARCH_NOMIC_BERT, "nomic-bert" },
  213. { LLM_ARCH_BLOOM, "bloom" },
  214. { LLM_ARCH_STABLELM, "stablelm" },
  215. { LLM_ARCH_QWEN, "qwen" },
  216. { LLM_ARCH_QWEN2, "qwen2" },
  217. { LLM_ARCH_PHI2, "phi2" },
  218. { LLM_ARCH_PLAMO, "plamo" },
  219. { LLM_ARCH_CODESHELL, "codeshell" },
  220. { LLM_ARCH_ORION, "orion" },
  221. { LLM_ARCH_INTERNLM2, "internlm2" },
  222. { LLM_ARCH_MINICPM, "minicpm" },
  223. { LLM_ARCH_GEMMA, "gemma" },
  224. { LLM_ARCH_STARCODER2, "starcoder2" },
  225. { LLM_ARCH_MAMBA, "mamba" },
  226. { LLM_ARCH_COMMAND_R, "command-r" },
  227. { LLM_ARCH_UNKNOWN, "(unknown)" },
  228. };
  229. enum llm_kv {
  230. LLM_KV_GENERAL_ARCHITECTURE,
  231. LLM_KV_GENERAL_QUANTIZATION_VERSION,
  232. LLM_KV_GENERAL_ALIGNMENT,
  233. LLM_KV_GENERAL_NAME,
  234. LLM_KV_GENERAL_AUTHOR,
  235. LLM_KV_GENERAL_URL,
  236. LLM_KV_GENERAL_DESCRIPTION,
  237. LLM_KV_GENERAL_LICENSE,
  238. LLM_KV_GENERAL_SOURCE_URL,
  239. LLM_KV_GENERAL_SOURCE_HF_REPO,
  240. LLM_KV_VOCAB_SIZE,
  241. LLM_KV_CONTEXT_LENGTH,
  242. LLM_KV_EMBEDDING_LENGTH,
  243. LLM_KV_BLOCK_COUNT,
  244. LLM_KV_FEED_FORWARD_LENGTH,
  245. LLM_KV_USE_PARALLEL_RESIDUAL,
  246. LLM_KV_TENSOR_DATA_LAYOUT,
  247. LLM_KV_EXPERT_COUNT,
  248. LLM_KV_EXPERT_USED_COUNT,
  249. LLM_KV_POOLING_TYPE,
  250. LLM_KV_LOGIT_SCALE,
  251. LLM_KV_ATTENTION_HEAD_COUNT,
  252. LLM_KV_ATTENTION_HEAD_COUNT_KV,
  253. LLM_KV_ATTENTION_MAX_ALIBI_BIAS,
  254. LLM_KV_ATTENTION_CLAMP_KQV,
  255. LLM_KV_ATTENTION_KEY_LENGTH,
  256. LLM_KV_ATTENTION_VALUE_LENGTH,
  257. LLM_KV_ATTENTION_LAYERNORM_EPS,
  258. LLM_KV_ATTENTION_LAYERNORM_RMS_EPS,
  259. LLM_KV_ATTENTION_CAUSAL,
  260. LLM_KV_ROPE_DIMENSION_COUNT,
  261. LLM_KV_ROPE_FREQ_BASE,
  262. LLM_KV_ROPE_SCALE_LINEAR,
  263. LLM_KV_ROPE_SCALING_TYPE,
  264. LLM_KV_ROPE_SCALING_FACTOR,
  265. LLM_KV_ROPE_SCALING_ORIG_CTX_LEN,
  266. LLM_KV_ROPE_SCALING_FINETUNED,
  267. LLM_KV_SPLIT_NO,
  268. LLM_KV_SPLIT_COUNT,
  269. LLM_KV_SPLIT_TENSORS_COUNT,
  270. LLM_KV_SSM_INNER_SIZE,
  271. LLM_KV_SSM_CONV_KERNEL,
  272. LLM_KV_SSM_STATE_SIZE,
  273. LLM_KV_SSM_TIME_STEP_RANK,
  274. LLM_KV_TOKENIZER_MODEL,
  275. LLM_KV_TOKENIZER_LIST,
  276. LLM_KV_TOKENIZER_TOKEN_TYPE,
  277. LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT,
  278. LLM_KV_TOKENIZER_SCORES,
  279. LLM_KV_TOKENIZER_MERGES,
  280. LLM_KV_TOKENIZER_BOS_ID,
  281. LLM_KV_TOKENIZER_EOS_ID,
  282. LLM_KV_TOKENIZER_UNK_ID,
  283. LLM_KV_TOKENIZER_SEP_ID,
  284. LLM_KV_TOKENIZER_PAD_ID,
  285. LLM_KV_TOKENIZER_ADD_BOS,
  286. LLM_KV_TOKENIZER_ADD_EOS,
  287. LLM_KV_TOKENIZER_ADD_PREFIX,
  288. LLM_KV_TOKENIZER_HF_JSON,
  289. LLM_KV_TOKENIZER_RWKV,
  290. };
  291. static const std::map<llm_kv, const char *> LLM_KV_NAMES = {
  292. { LLM_KV_GENERAL_ARCHITECTURE, "general.architecture" },
  293. { LLM_KV_GENERAL_QUANTIZATION_VERSION, "general.quantization_version" },
  294. { LLM_KV_GENERAL_ALIGNMENT, "general.alignment" },
  295. { LLM_KV_GENERAL_NAME, "general.name" },
  296. { LLM_KV_GENERAL_AUTHOR, "general.author" },
  297. { LLM_KV_GENERAL_URL, "general.url" },
  298. { LLM_KV_GENERAL_DESCRIPTION, "general.description" },
  299. { LLM_KV_GENERAL_LICENSE, "general.license" },
  300. { LLM_KV_GENERAL_SOURCE_URL, "general.source.url" },
  301. { LLM_KV_GENERAL_SOURCE_HF_REPO, "general.source.huggingface.repository" },
  302. { LLM_KV_VOCAB_SIZE, "%s.vocab_size" },
  303. { LLM_KV_CONTEXT_LENGTH, "%s.context_length" },
  304. { LLM_KV_EMBEDDING_LENGTH, "%s.embedding_length" },
  305. { LLM_KV_BLOCK_COUNT, "%s.block_count" },
  306. { LLM_KV_FEED_FORWARD_LENGTH, "%s.feed_forward_length" },
  307. { LLM_KV_USE_PARALLEL_RESIDUAL, "%s.use_parallel_residual" },
  308. { LLM_KV_TENSOR_DATA_LAYOUT, "%s.tensor_data_layout" },
  309. { LLM_KV_EXPERT_COUNT, "%s.expert_count" },
  310. { LLM_KV_EXPERT_USED_COUNT, "%s.expert_used_count" },
  311. { LLM_KV_POOLING_TYPE , "%s.pooling_type" },
  312. { LLM_KV_LOGIT_SCALE, "%s.logit_scale" },
  313. { LLM_KV_ATTENTION_HEAD_COUNT, "%s.attention.head_count" },
  314. { LLM_KV_ATTENTION_HEAD_COUNT_KV, "%s.attention.head_count_kv" },
  315. { LLM_KV_ATTENTION_MAX_ALIBI_BIAS, "%s.attention.max_alibi_bias" },
  316. { LLM_KV_ATTENTION_CLAMP_KQV, "%s.attention.clamp_kqv" },
  317. { LLM_KV_ATTENTION_KEY_LENGTH, "%s.attention.key_length" },
  318. { LLM_KV_ATTENTION_VALUE_LENGTH, "%s.attention.value_length" },
  319. { LLM_KV_ATTENTION_LAYERNORM_EPS, "%s.attention.layer_norm_epsilon" },
  320. { LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, "%s.attention.layer_norm_rms_epsilon" },
  321. { LLM_KV_ATTENTION_CAUSAL, "%s.attention.causal" },
  322. { LLM_KV_ROPE_DIMENSION_COUNT, "%s.rope.dimension_count" },
  323. { LLM_KV_ROPE_FREQ_BASE, "%s.rope.freq_base" },
  324. { LLM_KV_ROPE_SCALE_LINEAR, "%s.rope.scale_linear" },
  325. { LLM_KV_ROPE_SCALING_TYPE, "%s.rope.scaling.type" },
  326. { LLM_KV_ROPE_SCALING_FACTOR, "%s.rope.scaling.factor" },
  327. { LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, "%s.rope.scaling.original_context_length" },
  328. { LLM_KV_ROPE_SCALING_FINETUNED, "%s.rope.scaling.finetuned" },
  329. { LLM_KV_SPLIT_NO, "split.no" },
  330. { LLM_KV_SPLIT_COUNT, "split.count" },
  331. { LLM_KV_SPLIT_TENSORS_COUNT, "split.tensors.count" },
  332. { LLM_KV_SSM_CONV_KERNEL, "%s.ssm.conv_kernel" },
  333. { LLM_KV_SSM_INNER_SIZE, "%s.ssm.inner_size" },
  334. { LLM_KV_SSM_STATE_SIZE, "%s.ssm.state_size" },
  335. { LLM_KV_SSM_TIME_STEP_RANK, "%s.ssm.time_step_rank" },
  336. { LLM_KV_TOKENIZER_MODEL, "tokenizer.ggml.model" },
  337. { LLM_KV_TOKENIZER_LIST, "tokenizer.ggml.tokens" },
  338. { LLM_KV_TOKENIZER_TOKEN_TYPE, "tokenizer.ggml.token_type" },
  339. { LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, "tokenizer.ggml.token_type_count" },
  340. { LLM_KV_TOKENIZER_SCORES, "tokenizer.ggml.scores" },
  341. { LLM_KV_TOKENIZER_MERGES, "tokenizer.ggml.merges" },
  342. { LLM_KV_TOKENIZER_BOS_ID, "tokenizer.ggml.bos_token_id" },
  343. { LLM_KV_TOKENIZER_EOS_ID, "tokenizer.ggml.eos_token_id" },
  344. { LLM_KV_TOKENIZER_UNK_ID, "tokenizer.ggml.unknown_token_id" },
  345. { LLM_KV_TOKENIZER_SEP_ID, "tokenizer.ggml.seperator_token_id" },
  346. { LLM_KV_TOKENIZER_PAD_ID, "tokenizer.ggml.padding_token_id" },
  347. { LLM_KV_TOKENIZER_ADD_BOS, "tokenizer.ggml.add_bos_token" },
  348. { LLM_KV_TOKENIZER_ADD_EOS, "tokenizer.ggml.add_eos_token" },
  349. { LLM_KV_TOKENIZER_ADD_PREFIX, "tokenizer.ggml.add_space_prefix" },
  350. { LLM_KV_TOKENIZER_HF_JSON, "tokenizer.huggingface.json" },
  351. { LLM_KV_TOKENIZER_RWKV, "tokenizer.rwkv.world" },
  352. };
  353. struct LLM_KV {
  354. LLM_KV(llm_arch arch) : arch(arch) {}
  355. llm_arch arch;
  356. std::string operator()(llm_kv kv) const {
  357. return ::format(LLM_KV_NAMES.at(kv), LLM_ARCH_NAMES.at(arch));
  358. }
  359. };
  360. enum llm_tensor {
  361. LLM_TENSOR_TOKEN_EMBD,
  362. LLM_TENSOR_TOKEN_EMBD_NORM,
  363. LLM_TENSOR_TOKEN_TYPES,
  364. LLM_TENSOR_POS_EMBD,
  365. LLM_TENSOR_OUTPUT,
  366. LLM_TENSOR_OUTPUT_NORM,
  367. LLM_TENSOR_ROPE_FREQS,
  368. LLM_TENSOR_ATTN_Q,
  369. LLM_TENSOR_ATTN_K,
  370. LLM_TENSOR_ATTN_V,
  371. LLM_TENSOR_ATTN_QKV,
  372. LLM_TENSOR_ATTN_OUT,
  373. LLM_TENSOR_ATTN_NORM,
  374. LLM_TENSOR_ATTN_NORM_2,
  375. LLM_TENSOR_ATTN_OUT_NORM,
  376. LLM_TENSOR_ATTN_ROT_EMBD,
  377. LLM_TENSOR_FFN_GATE_INP,
  378. LLM_TENSOR_FFN_NORM,
  379. LLM_TENSOR_FFN_GATE,
  380. LLM_TENSOR_FFN_DOWN,
  381. LLM_TENSOR_FFN_UP,
  382. LLM_TENSOR_FFN_ACT,
  383. LLM_TENSOR_FFN_DOWN_EXP,
  384. LLM_TENSOR_FFN_GATE_EXP,
  385. LLM_TENSOR_FFN_UP_EXP,
  386. LLM_TENSOR_ATTN_Q_NORM,
  387. LLM_TENSOR_ATTN_K_NORM,
  388. LLM_TENSOR_LAYER_OUT_NORM,
  389. LLM_TENSOR_SSM_IN,
  390. LLM_TENSOR_SSM_CONV1D,
  391. LLM_TENSOR_SSM_X,
  392. LLM_TENSOR_SSM_DT,
  393. LLM_TENSOR_SSM_A,
  394. LLM_TENSOR_SSM_D,
  395. LLM_TENSOR_SSM_OUT,
  396. };
  397. static const std::map<llm_arch, std::map<llm_tensor, std::string>> LLM_TENSOR_NAMES = {
  398. {
  399. LLM_ARCH_LLAMA,
  400. {
  401. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  402. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  403. { LLM_TENSOR_OUTPUT, "output" },
  404. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  405. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  406. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  407. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  408. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  409. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  410. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  411. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  412. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  413. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  414. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  415. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  416. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  417. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  418. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  419. },
  420. },
  421. {
  422. LLM_ARCH_BAICHUAN,
  423. {
  424. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  425. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  426. { LLM_TENSOR_OUTPUT, "output" },
  427. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  428. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  429. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  430. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  431. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  432. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  433. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  434. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  435. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  436. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  437. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  438. },
  439. },
  440. {
  441. LLM_ARCH_FALCON,
  442. {
  443. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  444. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  445. { LLM_TENSOR_OUTPUT, "output" },
  446. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  447. { LLM_TENSOR_ATTN_NORM_2, "blk.%d.attn_norm_2" },
  448. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  449. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  450. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  451. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  452. },
  453. },
  454. {
  455. LLM_ARCH_GROK,
  456. {
  457. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  458. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  459. { LLM_TENSOR_OUTPUT, "output" },
  460. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  461. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  462. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  463. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  464. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  465. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  466. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  467. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  468. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  469. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  470. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  471. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  472. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  473. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  474. },
  475. },
  476. {
  477. LLM_ARCH_GPT2,
  478. {
  479. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  480. { LLM_TENSOR_POS_EMBD, "position_embd" },
  481. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  482. { LLM_TENSOR_OUTPUT, "output" },
  483. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  484. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  485. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  486. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  487. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  488. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  489. },
  490. },
  491. {
  492. LLM_ARCH_GPTJ,
  493. {
  494. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  495. },
  496. },
  497. {
  498. LLM_ARCH_GPTNEOX,
  499. {
  500. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  501. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  502. { LLM_TENSOR_OUTPUT, "output" },
  503. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  504. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  505. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  506. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  507. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  508. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  509. },
  510. },
  511. {
  512. LLM_ARCH_PERSIMMON,
  513. {
  514. { LLM_TENSOR_TOKEN_EMBD, "token_embd"},
  515. { LLM_TENSOR_OUTPUT_NORM, "output_norm"},
  516. { LLM_TENSOR_OUTPUT, "output"},
  517. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm"},
  518. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv"},
  519. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output"},
  520. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm"},
  521. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm"},
  522. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm"},
  523. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down"},
  524. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up"},
  525. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd"},
  526. },
  527. },
  528. {
  529. LLM_ARCH_MPT,
  530. {
  531. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  532. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  533. { LLM_TENSOR_OUTPUT, "output"},
  534. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  535. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  536. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  537. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  538. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  539. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  540. { LLM_TENSOR_FFN_ACT, "blk.%d.ffn.act" },
  541. },
  542. },
  543. {
  544. LLM_ARCH_STARCODER,
  545. {
  546. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  547. { LLM_TENSOR_POS_EMBD, "position_embd" },
  548. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  549. { LLM_TENSOR_OUTPUT, "output" },
  550. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  551. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  552. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  553. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  554. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  555. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  556. },
  557. },
  558. {
  559. LLM_ARCH_REFACT,
  560. {
  561. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  562. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  563. { LLM_TENSOR_OUTPUT, "output" },
  564. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  565. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  566. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  567. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  568. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  569. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  570. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  571. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  572. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  573. },
  574. },
  575. {
  576. LLM_ARCH_BERT,
  577. {
  578. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  579. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  580. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  581. { LLM_TENSOR_POS_EMBD, "position_embd" },
  582. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  583. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  584. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  585. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  586. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  587. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  588. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  589. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  590. },
  591. },
  592. {
  593. LLM_ARCH_NOMIC_BERT,
  594. {
  595. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  596. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  597. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  598. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  599. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  600. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  601. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  602. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  603. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  604. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  605. },
  606. },
  607. {
  608. LLM_ARCH_BLOOM,
  609. {
  610. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  611. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  612. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  613. { LLM_TENSOR_OUTPUT, "output" },
  614. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  615. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  616. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  617. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  618. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  619. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  620. },
  621. },
  622. {
  623. LLM_ARCH_STABLELM,
  624. {
  625. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  626. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  627. { LLM_TENSOR_OUTPUT, "output" },
  628. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  629. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  630. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  631. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  632. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  633. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  634. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  635. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  636. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  637. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  638. },
  639. },
  640. {
  641. LLM_ARCH_QWEN,
  642. {
  643. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  644. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  645. { LLM_TENSOR_OUTPUT, "output" },
  646. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  647. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  648. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  649. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  650. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  651. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  652. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  653. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  654. },
  655. },
  656. {
  657. LLM_ARCH_QWEN2,
  658. {
  659. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  660. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  661. { LLM_TENSOR_OUTPUT, "output" },
  662. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  663. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  664. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  665. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  666. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  667. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  668. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  669. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  670. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  671. },
  672. },
  673. {
  674. LLM_ARCH_PHI2,
  675. {
  676. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  677. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  678. { LLM_TENSOR_OUTPUT, "output" },
  679. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  680. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  681. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  682. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  683. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  684. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  685. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  686. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  687. },
  688. },
  689. {
  690. LLM_ARCH_PLAMO,
  691. {
  692. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  693. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  694. { LLM_TENSOR_OUTPUT, "output" },
  695. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  696. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  697. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  698. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  699. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  700. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  701. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  702. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  703. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  704. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  705. },
  706. },
  707. {
  708. LLM_ARCH_CODESHELL,
  709. {
  710. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  711. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  712. { LLM_TENSOR_OUTPUT, "output" },
  713. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  714. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  715. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  716. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  717. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  718. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  719. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  720. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  721. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  722. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  723. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  724. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  725. },
  726. },
  727. {
  728. LLM_ARCH_ORION,
  729. {
  730. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  731. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  732. { LLM_TENSOR_OUTPUT, "output" },
  733. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  734. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  735. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  736. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  737. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  738. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  739. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  740. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  741. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  742. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  743. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  744. },
  745. },
  746. {
  747. LLM_ARCH_INTERNLM2,
  748. {
  749. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  750. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  751. { LLM_TENSOR_OUTPUT, "output" },
  752. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  753. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  754. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  755. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  756. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  757. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  758. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  759. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  760. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  761. },
  762. },
  763. {
  764. LLM_ARCH_MINICPM,
  765. {
  766. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  767. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  768. { LLM_TENSOR_OUTPUT, "output" },
  769. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  770. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  771. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  772. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  773. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  774. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  775. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  776. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  777. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  778. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  779. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  780. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  781. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  782. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  783. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  784. },
  785. },
  786. {
  787. LLM_ARCH_GEMMA,
  788. {
  789. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  790. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  791. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  792. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  793. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  794. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  795. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  796. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  797. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  798. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  799. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  800. },
  801. },
  802. {
  803. LLM_ARCH_STARCODER2,
  804. {
  805. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  806. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  807. { LLM_TENSOR_OUTPUT, "output" },
  808. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  809. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  810. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  811. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  812. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  813. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  814. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  815. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  816. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  817. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  818. },
  819. },
  820. {
  821. LLM_ARCH_MAMBA,
  822. {
  823. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  824. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  825. { LLM_TENSOR_OUTPUT, "output" },
  826. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  827. { LLM_TENSOR_SSM_IN, "blk.%d.ssm_in" },
  828. { LLM_TENSOR_SSM_CONV1D, "blk.%d.ssm_conv1d" },
  829. { LLM_TENSOR_SSM_X, "blk.%d.ssm_x" },
  830. { LLM_TENSOR_SSM_DT, "blk.%d.ssm_dt" },
  831. { LLM_TENSOR_SSM_A, "blk.%d.ssm_a" },
  832. { LLM_TENSOR_SSM_D, "blk.%d.ssm_d" },
  833. { LLM_TENSOR_SSM_OUT, "blk.%d.ssm_out" },
  834. },
  835. },
  836. {
  837. LLM_ARCH_COMMAND_R,
  838. {
  839. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  840. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  841. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  842. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  843. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  844. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  845. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  846. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  847. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  848. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  849. },
  850. },
  851. {
  852. LLM_ARCH_UNKNOWN,
  853. {
  854. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  855. },
  856. },
  857. };
  858. static llm_arch llm_arch_from_string(const std::string & name) {
  859. for (const auto & kv : LLM_ARCH_NAMES) { // NOLINT
  860. if (kv.second == name) {
  861. return kv.first;
  862. }
  863. }
  864. return LLM_ARCH_UNKNOWN;
  865. }
  866. // helper to handle gguf constants
  867. // usage:
  868. //
  869. // const auto tn = LLM_TN(LLM_ARCH_LLAMA);
  870. //
  871. // std::string name = tn(LLM_TENSOR_OUTPUT); -> "output"
  872. // std::string name = tn(LLM_TENSOR_TOKEN_EMBD, "bias"); -> "token_embd.bias"
  873. // std::string name = tn(LLM_TENSOR_ATTN_NORM, "weight", 3); -> "blk.3.attn_norm.weight"
  874. //
  875. struct LLM_TN {
  876. LLM_TN(llm_arch arch) : arch(arch) {}
  877. llm_arch arch;
  878. std::string operator()(llm_tensor tensor) const {
  879. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  880. return "__missing__";
  881. }
  882. return LLM_TENSOR_NAMES.at(arch).at(tensor);
  883. }
  884. std::string operator()(llm_tensor tensor, const std::string & suffix) const {
  885. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  886. return "__missing__";
  887. }
  888. return LLM_TENSOR_NAMES.at(arch).at(tensor) + "." + suffix;
  889. }
  890. std::string operator()(llm_tensor tensor, int bid) const {
  891. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  892. return "__missing__";
  893. }
  894. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid);
  895. }
  896. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid) const {
  897. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  898. return "__missing__";
  899. }
  900. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid) + "." + suffix;
  901. }
  902. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid, int xid) const {
  903. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  904. return "__missing__";
  905. }
  906. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid, xid) + "." + suffix;
  907. }
  908. };
  909. //
  910. // gguf helpers
  911. //
  912. static const std::map<llama_rope_scaling_type, const char *> LLAMA_ROPE_SCALING_TYPES = {
  913. { LLAMA_ROPE_SCALING_TYPE_NONE, "none" },
  914. { LLAMA_ROPE_SCALING_TYPE_LINEAR, "linear" },
  915. { LLAMA_ROPE_SCALING_TYPE_YARN, "yarn" },
  916. };
  917. static llama_rope_scaling_type llama_rope_scaling_type_from_string(const std::string & name) {
  918. for (const auto & kv : LLAMA_ROPE_SCALING_TYPES) {
  919. if (kv.second == name) {
  920. return (llama_rope_scaling_type) kv.first;
  921. }
  922. }
  923. return LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED;
  924. }
  925. static std::string gguf_data_to_str(enum gguf_type type, const void * data, int i) {
  926. switch (type) {
  927. case GGUF_TYPE_UINT8: return std::to_string(((const uint8_t *)data)[i]);
  928. case GGUF_TYPE_INT8: return std::to_string(((const int8_t *)data)[i]);
  929. case GGUF_TYPE_UINT16: return std::to_string(((const uint16_t *)data)[i]);
  930. case GGUF_TYPE_INT16: return std::to_string(((const int16_t *)data)[i]);
  931. case GGUF_TYPE_UINT32: return std::to_string(((const uint32_t *)data)[i]);
  932. case GGUF_TYPE_INT32: return std::to_string(((const int32_t *)data)[i]);
  933. case GGUF_TYPE_UINT64: return std::to_string(((const uint64_t *)data)[i]);
  934. case GGUF_TYPE_INT64: return std::to_string(((const int64_t *)data)[i]);
  935. case GGUF_TYPE_FLOAT32: return std::to_string(((const float *)data)[i]);
  936. case GGUF_TYPE_FLOAT64: return std::to_string(((const double *)data)[i]);
  937. case GGUF_TYPE_BOOL: return ((const bool *)data)[i] ? "true" : "false";
  938. default: return format("unknown type %d", type);
  939. }
  940. }
  941. static std::string gguf_kv_to_str(const struct gguf_context * ctx_gguf, int i) {
  942. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  943. switch (type) {
  944. case GGUF_TYPE_STRING:
  945. return gguf_get_val_str(ctx_gguf, i);
  946. case GGUF_TYPE_ARRAY:
  947. {
  948. const enum gguf_type arr_type = gguf_get_arr_type(ctx_gguf, i);
  949. int arr_n = gguf_get_arr_n(ctx_gguf, i);
  950. const void * data = gguf_get_arr_data(ctx_gguf, i);
  951. std::stringstream ss;
  952. ss << "[";
  953. for (int j = 0; j < arr_n; j++) {
  954. if (arr_type == GGUF_TYPE_STRING) {
  955. std::string val = gguf_get_arr_str(ctx_gguf, i, j);
  956. // escape quotes
  957. replace_all(val, "\\", "\\\\");
  958. replace_all(val, "\"", "\\\"");
  959. ss << '"' << val << '"';
  960. } else if (arr_type == GGUF_TYPE_ARRAY) {
  961. ss << "???";
  962. } else {
  963. ss << gguf_data_to_str(arr_type, data, j);
  964. }
  965. if (j < arr_n - 1) {
  966. ss << ", ";
  967. }
  968. }
  969. ss << "]";
  970. return ss.str();
  971. }
  972. default:
  973. return gguf_data_to_str(type, gguf_get_val_data(ctx_gguf, i), 0);
  974. }
  975. }
  976. //
  977. // llama helpers
  978. //
  979. #if defined(_WIN32)
  980. static std::string llama_format_win_err(DWORD err) {
  981. LPSTR buf;
  982. size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  983. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, NULL);
  984. if (!size) {
  985. return "FormatMessageA failed";
  986. }
  987. std::string ret(buf, size);
  988. LocalFree(buf);
  989. return ret;
  990. }
  991. #endif
  992. template <typename T>
  993. struct no_init {
  994. T value;
  995. no_init() { /* do nothing */ }
  996. };
  997. struct llama_file {
  998. // use FILE * so we don't have to re-open the file to mmap
  999. FILE * fp;
  1000. size_t size;
  1001. llama_file(const char * fname, const char * mode) {
  1002. fp = ggml_fopen(fname, mode);
  1003. if (fp == NULL) {
  1004. throw std::runtime_error(format("failed to open %s: %s", fname, strerror(errno)));
  1005. }
  1006. seek(0, SEEK_END);
  1007. size = tell();
  1008. seek(0, SEEK_SET);
  1009. }
  1010. size_t tell() const {
  1011. #ifdef _WIN32
  1012. __int64 ret = _ftelli64(fp);
  1013. #else
  1014. long ret = std::ftell(fp);
  1015. #endif
  1016. GGML_ASSERT(ret != -1); // this really shouldn't fail
  1017. return (size_t) ret;
  1018. }
  1019. void seek(size_t offset, int whence) const {
  1020. #ifdef _WIN32
  1021. int ret = _fseeki64(fp, (__int64) offset, whence);
  1022. #else
  1023. int ret = std::fseek(fp, (long) offset, whence);
  1024. #endif
  1025. GGML_ASSERT(ret == 0); // same
  1026. }
  1027. void read_raw(void * ptr, size_t len) const {
  1028. if (len == 0) {
  1029. return;
  1030. }
  1031. errno = 0;
  1032. std::size_t ret = std::fread(ptr, len, 1, fp);
  1033. if (ferror(fp)) {
  1034. throw std::runtime_error(format("read error: %s", strerror(errno)));
  1035. }
  1036. if (ret != 1) {
  1037. throw std::runtime_error("unexpectedly reached end of file");
  1038. }
  1039. }
  1040. uint32_t read_u32() const {
  1041. uint32_t ret;
  1042. read_raw(&ret, sizeof(ret));
  1043. return ret;
  1044. }
  1045. void write_raw(const void * ptr, size_t len) const {
  1046. if (len == 0) {
  1047. return;
  1048. }
  1049. errno = 0;
  1050. size_t ret = std::fwrite(ptr, len, 1, fp);
  1051. if (ret != 1) {
  1052. throw std::runtime_error(format("write error: %s", strerror(errno)));
  1053. }
  1054. }
  1055. void write_u32(std::uint32_t val) const {
  1056. write_raw(&val, sizeof(val));
  1057. }
  1058. ~llama_file() {
  1059. if (fp) {
  1060. std::fclose(fp);
  1061. }
  1062. }
  1063. };
  1064. using llama_files = std::vector<std::unique_ptr<llama_file>>;
  1065. struct llama_mmap {
  1066. void * addr;
  1067. size_t size;
  1068. llama_mmap(const llama_mmap &) = delete;
  1069. #ifdef _POSIX_MAPPED_FILES
  1070. static constexpr bool SUPPORTED = true;
  1071. // list of mapped fragments (first_offset, last_offset)
  1072. std::vector<std::pair<size_t, size_t>> mapped_fragments;
  1073. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1 /* -1 = max value */, bool numa = false) {
  1074. size = file->size;
  1075. int fd = fileno(file->fp);
  1076. int flags = MAP_SHARED;
  1077. // prefetch/readahead impairs performance on NUMA systems
  1078. if (numa) { prefetch = 0; }
  1079. #ifdef __linux__
  1080. // advise the kernel to read the file sequentially (increases readahead)
  1081. if (posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL)) {
  1082. LLAMA_LOG_WARN("warning: posix_fadvise(.., POSIX_FADV_SEQUENTIAL) failed: %s\n",
  1083. strerror(errno));
  1084. }
  1085. if (prefetch) { flags |= MAP_POPULATE; }
  1086. #endif
  1087. addr = mmap(NULL, file->size, PROT_READ, flags, fd, 0);
  1088. if (addr == MAP_FAILED) { // NOLINT
  1089. throw std::runtime_error(format("mmap failed: %s", strerror(errno)));
  1090. }
  1091. if (prefetch > 0) {
  1092. // advise the kernel to preload the mapped memory
  1093. if (posix_madvise(addr, std::min(file->size, prefetch), POSIX_MADV_WILLNEED)) {
  1094. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_WILLNEED) failed: %s\n",
  1095. strerror(errno));
  1096. }
  1097. }
  1098. if (numa) {
  1099. // advise the kernel not to use readahead
  1100. // (because the next page might not belong on the same node)
  1101. if (posix_madvise(addr, file->size, POSIX_MADV_RANDOM)) {
  1102. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_RANDOM) failed: %s\n",
  1103. strerror(errno));
  1104. }
  1105. }
  1106. // initialize list of mapped_fragments
  1107. mapped_fragments.emplace_back(0, file->size);
  1108. }
  1109. static void align_range(size_t * first, size_t * last, size_t page_size) {
  1110. // align first to the next page
  1111. size_t offset_in_page = *first & (page_size - 1);
  1112. size_t offset_to_page = offset_in_page == 0 ? 0 : page_size - offset_in_page;
  1113. *first += offset_to_page;
  1114. // align last to the previous page
  1115. *last = *last & ~(page_size - 1);
  1116. if (*last <= *first) {
  1117. *last = *first;
  1118. }
  1119. }
  1120. // partially unmap the file in the range [first, last)
  1121. void unmap_fragment(size_t first, size_t last) {
  1122. // note: this function must not be called multiple times with overlapping ranges
  1123. // otherwise, there is a risk of invalidating addresses that have been repurposed for other mappings
  1124. int page_size = sysconf(_SC_PAGESIZE);
  1125. align_range(&first, &last, page_size);
  1126. size_t len = last - first;
  1127. if (len == 0) {
  1128. return;
  1129. }
  1130. GGML_ASSERT(first % page_size == 0);
  1131. GGML_ASSERT(last % page_size == 0);
  1132. GGML_ASSERT(last > first);
  1133. void * next_page_start = (uint8_t *) addr + first;
  1134. // unmap the range
  1135. if (munmap(next_page_start, len)) {
  1136. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  1137. }
  1138. // update the list of mapped fragments to avoid unmapping the same range again in the destructor
  1139. std::vector<std::pair<size_t, size_t>> new_mapped_fragments;
  1140. for (const auto & frag : mapped_fragments) {
  1141. if (frag.first < first && frag.second > last) {
  1142. // the range is in the middle of the fragment, split it
  1143. new_mapped_fragments.emplace_back(frag.first, first);
  1144. new_mapped_fragments.emplace_back(last, frag.second);
  1145. } else if (frag.first < first && frag.second > first) {
  1146. // the range starts in the middle of the fragment
  1147. new_mapped_fragments.emplace_back(frag.first, first);
  1148. } else if (frag.first < last && frag.second > last) {
  1149. // the range ends in the middle of the fragment
  1150. new_mapped_fragments.emplace_back(last, frag.second);
  1151. } else if (frag.first >= first && frag.second <= last) {
  1152. // the range covers the entire fragment
  1153. } else {
  1154. // the range is outside the fragment
  1155. new_mapped_fragments.push_back(frag);
  1156. }
  1157. }
  1158. mapped_fragments = std::move(new_mapped_fragments);
  1159. }
  1160. ~llama_mmap() {
  1161. for (const auto & frag : mapped_fragments) {
  1162. if (munmap((char *) addr + frag.first, frag.second - frag.first)) {
  1163. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  1164. }
  1165. }
  1166. }
  1167. #elif defined(_WIN32)
  1168. static constexpr bool SUPPORTED = true;
  1169. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1, bool numa = false) {
  1170. GGML_UNUSED(numa);
  1171. size = file->size;
  1172. HANDLE hFile = (HANDLE) _get_osfhandle(_fileno(file->fp));
  1173. HANDLE hMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
  1174. if (hMapping == NULL) {
  1175. DWORD error = GetLastError();
  1176. throw std::runtime_error(format("CreateFileMappingA failed: %s", llama_format_win_err(error).c_str()));
  1177. }
  1178. addr = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
  1179. DWORD error = GetLastError();
  1180. CloseHandle(hMapping);
  1181. if (addr == NULL) {
  1182. throw std::runtime_error(format("MapViewOfFile failed: %s", llama_format_win_err(error).c_str()));
  1183. }
  1184. if (prefetch > 0) {
  1185. #if _WIN32_WINNT >= 0x602
  1186. // PrefetchVirtualMemory is only present on Windows 8 and above, so we dynamically load it
  1187. BOOL (WINAPI *pPrefetchVirtualMemory) (HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG);
  1188. HMODULE hKernel32 = GetModuleHandleW(L"kernel32.dll");
  1189. // may fail on pre-Windows 8 systems
  1190. pPrefetchVirtualMemory = reinterpret_cast<decltype(pPrefetchVirtualMemory)> (GetProcAddress(hKernel32, "PrefetchVirtualMemory"));
  1191. if (pPrefetchVirtualMemory) {
  1192. // advise the kernel to preload the mapped memory
  1193. WIN32_MEMORY_RANGE_ENTRY range;
  1194. range.VirtualAddress = addr;
  1195. range.NumberOfBytes = (SIZE_T) std::min(size, prefetch);
  1196. if (!pPrefetchVirtualMemory(GetCurrentProcess(), 1, &range, 0)) {
  1197. LLAMA_LOG_WARN("warning: PrefetchVirtualMemory failed: %s\n",
  1198. llama_format_win_err(GetLastError()).c_str());
  1199. }
  1200. }
  1201. #else
  1202. throw std::runtime_error("PrefetchVirtualMemory unavailable");
  1203. #endif
  1204. }
  1205. }
  1206. void unmap_fragment(size_t first, size_t last) {
  1207. // not supported
  1208. GGML_UNUSED(first);
  1209. GGML_UNUSED(last);
  1210. }
  1211. ~llama_mmap() {
  1212. if (!UnmapViewOfFile(addr)) {
  1213. LLAMA_LOG_WARN("warning: UnmapViewOfFile failed: %s\n",
  1214. llama_format_win_err(GetLastError()).c_str());
  1215. }
  1216. }
  1217. #else
  1218. static constexpr bool SUPPORTED = false;
  1219. llama_mmap(struct llama_file * file, size_t prefetch = -1, bool numa = false) {
  1220. GGML_UNUSED(file);
  1221. GGML_UNUSED(prefetch);
  1222. GGML_UNUSED(numa);
  1223. throw std::runtime_error("mmap not supported");
  1224. }
  1225. void unmap_fragment(size_t first, size_t last) {
  1226. GGML_UNUSED(first);
  1227. GGML_UNUSED(last);
  1228. throw std::runtime_error("mmap not supported");
  1229. }
  1230. #endif
  1231. };
  1232. using llama_mmaps = std::vector<std::unique_ptr<llama_mmap>>;
  1233. // Represents some region of memory being locked using mlock or VirtualLock;
  1234. // will automatically unlock on destruction.
  1235. struct llama_mlock {
  1236. void * addr = NULL;
  1237. size_t size = 0;
  1238. bool failed_already = false;
  1239. llama_mlock() {}
  1240. llama_mlock(const llama_mlock &) = delete;
  1241. ~llama_mlock() {
  1242. if (size) {
  1243. raw_unlock(addr, size);
  1244. }
  1245. }
  1246. void init(void * ptr) {
  1247. GGML_ASSERT(addr == NULL && size == 0); // NOLINT
  1248. addr = ptr;
  1249. }
  1250. void grow_to(size_t target_size) {
  1251. GGML_ASSERT(addr);
  1252. if (failed_already) {
  1253. return;
  1254. }
  1255. size_t granularity = lock_granularity();
  1256. target_size = (target_size + granularity - 1) & ~(granularity - 1);
  1257. if (target_size > size) {
  1258. if (raw_lock((uint8_t *) addr + size, target_size - size)) {
  1259. size = target_size;
  1260. } else {
  1261. failed_already = true;
  1262. }
  1263. }
  1264. }
  1265. #ifdef _POSIX_MEMLOCK_RANGE
  1266. static constexpr bool SUPPORTED = true;
  1267. static size_t lock_granularity() {
  1268. return (size_t) sysconf(_SC_PAGESIZE);
  1269. }
  1270. #ifdef __APPLE__
  1271. #define MLOCK_SUGGESTION \
  1272. "Try increasing the sysctl values 'vm.user_wire_limit' and 'vm.global_user_wire_limit' and/or " \
  1273. "decreasing 'vm.global_no_user_wire_amount'. Also try increasing RLIMIT_MEMLOCK (ulimit -l).\n"
  1274. #else
  1275. #define MLOCK_SUGGESTION \
  1276. "Try increasing RLIMIT_MEMLOCK ('ulimit -l' as root).\n"
  1277. #endif
  1278. bool raw_lock(const void * addr, size_t size) const {
  1279. if (!mlock(addr, size)) {
  1280. return true;
  1281. }
  1282. char* errmsg = std::strerror(errno);
  1283. bool suggest = (errno == ENOMEM);
  1284. // Check if the resource limit is fine after all
  1285. struct rlimit lock_limit;
  1286. if (suggest && getrlimit(RLIMIT_MEMLOCK, &lock_limit)) {
  1287. suggest = false;
  1288. }
  1289. if (suggest && (lock_limit.rlim_max > lock_limit.rlim_cur + size)) {
  1290. suggest = false;
  1291. }
  1292. LLAMA_LOG_WARN("warning: failed to mlock %zu-byte buffer (after previously locking %zu bytes): %s\n%s",
  1293. size, this->size, errmsg, suggest ? MLOCK_SUGGESTION : "");
  1294. return false;
  1295. }
  1296. #undef MLOCK_SUGGESTION
  1297. static void raw_unlock(void * addr, size_t size) {
  1298. if (munlock(addr, size)) {
  1299. LLAMA_LOG_WARN("warning: failed to munlock buffer: %s\n", std::strerror(errno));
  1300. }
  1301. }
  1302. #elif defined(_WIN32)
  1303. static constexpr bool SUPPORTED = true;
  1304. static size_t lock_granularity() {
  1305. SYSTEM_INFO si;
  1306. GetSystemInfo(&si);
  1307. return (size_t) si.dwPageSize;
  1308. }
  1309. bool raw_lock(void * ptr, size_t len) const {
  1310. for (int tries = 1; ; tries++) {
  1311. if (VirtualLock(ptr, len)) {
  1312. return true;
  1313. }
  1314. if (tries == 2) {
  1315. LLAMA_LOG_WARN("warning: failed to VirtualLock %zu-byte buffer (after previously locking %zu bytes): %s\n",
  1316. len, size, llama_format_win_err(GetLastError()).c_str());
  1317. return false;
  1318. }
  1319. // It failed but this was only the first try; increase the working
  1320. // set size and try again.
  1321. SIZE_T min_ws_size, max_ws_size;
  1322. if (!GetProcessWorkingSetSize(GetCurrentProcess(), &min_ws_size, &max_ws_size)) {
  1323. LLAMA_LOG_WARN("warning: GetProcessWorkingSetSize failed: %s\n",
  1324. llama_format_win_err(GetLastError()).c_str());
  1325. return false;
  1326. }
  1327. // Per MSDN: "The maximum number of pages that a process can lock
  1328. // is equal to the number of pages in its minimum working set minus
  1329. // a small overhead."
  1330. // Hopefully a megabyte is enough overhead:
  1331. size_t increment = len + 1048576;
  1332. // The minimum must be <= the maximum, so we need to increase both:
  1333. min_ws_size += increment;
  1334. max_ws_size += increment;
  1335. if (!SetProcessWorkingSetSize(GetCurrentProcess(), min_ws_size, max_ws_size)) {
  1336. LLAMA_LOG_WARN("warning: SetProcessWorkingSetSize failed: %s\n",
  1337. llama_format_win_err(GetLastError()).c_str());
  1338. return false;
  1339. }
  1340. }
  1341. }
  1342. static void raw_unlock(void * ptr, size_t len) {
  1343. if (!VirtualUnlock(ptr, len)) {
  1344. LLAMA_LOG_WARN("warning: failed to VirtualUnlock buffer: %s\n",
  1345. llama_format_win_err(GetLastError()).c_str());
  1346. }
  1347. }
  1348. #else
  1349. static constexpr bool SUPPORTED = false;
  1350. static size_t lock_granularity() {
  1351. return (size_t) 65536;
  1352. }
  1353. bool raw_lock(const void * addr, size_t len) const {
  1354. LLAMA_LOG_WARN("warning: mlock not supported on this system\n");
  1355. return false;
  1356. }
  1357. static void raw_unlock(const void * addr, size_t len) {}
  1358. #endif
  1359. };
  1360. using llama_mlocks = std::vector<std::unique_ptr<llama_mlock>>;
  1361. static std::string llama_token_to_piece(const struct llama_context * ctx, llama_token token) {
  1362. std::vector<char> result(8, 0);
  1363. const int n_tokens = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1364. if (n_tokens < 0) {
  1365. result.resize(-n_tokens);
  1366. int check = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1367. GGML_ASSERT(check == -n_tokens);
  1368. }
  1369. else {
  1370. result.resize(n_tokens);
  1371. }
  1372. return std::string(result.data(), result.size());
  1373. }
  1374. static ggml_backend_buffer_type_t llama_default_buffer_type_cpu(bool host_buffer) {
  1375. ggml_backend_buffer_type_t buft = nullptr;
  1376. #if defined(GGML_USE_CUDA)
  1377. // host buffers should only be used when data is expected to be copied to/from the GPU
  1378. if (host_buffer) {
  1379. buft = ggml_backend_cuda_host_buffer_type();
  1380. }
  1381. #elif defined(GGML_USE_SYCL)
  1382. if (host_buffer) {
  1383. buft = ggml_backend_sycl_host_buffer_type();
  1384. }
  1385. #elif defined(GGML_USE_CPU_HBM)
  1386. buft = ggml_backend_cpu_hbm_buffer_type();
  1387. #elif defined(GGML_USE_VULKAN)
  1388. if (host_buffer) {
  1389. buft = ggml_backend_vk_host_buffer_type();
  1390. }
  1391. #endif
  1392. if (buft == nullptr) {
  1393. buft = ggml_backend_cpu_buffer_type();
  1394. }
  1395. return buft;
  1396. GGML_UNUSED(host_buffer);
  1397. }
  1398. static ggml_backend_buffer_type_t llama_default_buffer_type_offload(int gpu) {
  1399. ggml_backend_buffer_type_t buft = nullptr;
  1400. #ifdef GGML_USE_METAL
  1401. buft = ggml_backend_metal_buffer_type();
  1402. #elif defined(GGML_USE_CUDA)
  1403. buft = ggml_backend_cuda_buffer_type(gpu);
  1404. #elif defined(GGML_USE_VULKAN)
  1405. buft = ggml_backend_vk_buffer_type(gpu);
  1406. #elif defined(GGML_USE_SYCL)
  1407. buft = ggml_backend_sycl_buffer_type(gpu);
  1408. #elif defined(GGML_USE_CLBLAST)
  1409. buft = ggml_backend_opencl_buffer_type();
  1410. #elif defined(GGML_USE_KOMPUTE)
  1411. buft = ggml_backend_kompute_buffer_type(gpu);
  1412. if (buft == nullptr) {
  1413. LLAMA_LOG_WARN("%s: cannot use GPU %d, check `vulkaninfo --summary`\n", __func__, gpu);
  1414. }
  1415. #endif
  1416. if (buft == nullptr) {
  1417. buft = llama_default_buffer_type_cpu(true);
  1418. }
  1419. return buft;
  1420. GGML_UNUSED(gpu);
  1421. }
  1422. static ggml_backend_buffer_type_t llama_default_buffer_type_split(int fallback_gpu, const float * tensor_split) {
  1423. ggml_backend_buffer_type_t buft = nullptr;
  1424. #ifdef GGML_USE_CUDA
  1425. if (ggml_backend_cuda_get_device_count() > 1) {
  1426. buft = ggml_backend_cuda_split_buffer_type(tensor_split);
  1427. }
  1428. #endif
  1429. #ifdef GGML_USE_SYCL
  1430. if (ggml_backend_sycl_get_device_count() > 1) {
  1431. buft = ggml_backend_sycl_split_buffer_type(tensor_split);
  1432. }
  1433. #endif
  1434. if (buft == nullptr) {
  1435. buft = llama_default_buffer_type_offload(fallback_gpu);
  1436. }
  1437. return buft;
  1438. GGML_UNUSED(tensor_split);
  1439. }
  1440. static size_t llama_get_device_count() {
  1441. #if defined(GGML_USE_CUDA)
  1442. return ggml_backend_cuda_get_device_count();
  1443. #elif defined(GGML_USE_SYCL)
  1444. return ggml_backend_sycl_get_device_count();
  1445. #elif defined(GGML_USE_VULKAN)
  1446. return ggml_backend_vk_get_device_count();
  1447. #else
  1448. return 1;
  1449. #endif
  1450. }
  1451. static size_t llama_get_device_memory(int device) {
  1452. #if defined(GGML_USE_CUDA)
  1453. size_t total;
  1454. size_t free;
  1455. ggml_backend_cuda_get_device_memory(device, &total, &free);
  1456. return free;
  1457. #elif defined(GGML_USE_SYCL)
  1458. size_t total;
  1459. size_t free;
  1460. ggml_backend_sycl_get_device_memory(device, &total, &free);
  1461. return free;
  1462. #elif defined(GGML_USE_VULKAN)
  1463. size_t total;
  1464. size_t free;
  1465. ggml_backend_vk_get_device_memory(device, &total, &free);
  1466. return free;
  1467. #else
  1468. return 1;
  1469. GGML_UNUSED(device);
  1470. #endif
  1471. }
  1472. //
  1473. // globals
  1474. //
  1475. struct llama_state {
  1476. llama_state() {
  1477. #ifdef GGML_USE_METAL
  1478. ggml_backend_metal_log_set_callback(log_callback, log_callback_user_data);
  1479. #endif
  1480. }
  1481. // We save the log callback globally
  1482. ggml_log_callback log_callback = llama_log_callback_default;
  1483. void * log_callback_user_data = nullptr;
  1484. };
  1485. static llama_state g_state;
  1486. // available llama models
  1487. enum e_model {
  1488. MODEL_UNKNOWN,
  1489. MODEL_17M,
  1490. MODEL_22M,
  1491. MODEL_33M,
  1492. MODEL_109M,
  1493. MODEL_137M,
  1494. MODEL_335M,
  1495. MODEL_0_5B,
  1496. MODEL_1B,
  1497. MODEL_2B,
  1498. MODEL_3B,
  1499. MODEL_4B,
  1500. MODEL_7B,
  1501. MODEL_8B,
  1502. MODEL_13B,
  1503. MODEL_14B,
  1504. MODEL_15B,
  1505. MODEL_20B,
  1506. MODEL_30B,
  1507. MODEL_34B,
  1508. MODEL_35B,
  1509. MODEL_40B,
  1510. MODEL_65B,
  1511. MODEL_70B,
  1512. MODEL_314B,
  1513. MODEL_SMALL,
  1514. MODEL_MEDIUM,
  1515. MODEL_LARGE,
  1516. MODEL_XL,
  1517. };
  1518. static const size_t kiB = 1024;
  1519. static const size_t MiB = 1024*kiB;
  1520. static const size_t GiB = 1024*MiB;
  1521. struct llama_hparams {
  1522. bool vocab_only;
  1523. bool rope_finetuned;
  1524. uint32_t n_vocab;
  1525. uint32_t n_ctx_train; // context size the model was trained on
  1526. uint32_t n_embd;
  1527. uint32_t n_head;
  1528. uint32_t n_head_kv;
  1529. uint32_t n_layer;
  1530. uint32_t n_rot;
  1531. 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
  1532. uint32_t n_embd_head_v; // dimension of values (d_v) aka n_embd_head
  1533. uint32_t n_ff;
  1534. uint32_t n_expert = 0;
  1535. uint32_t n_expert_used = 0;
  1536. uint32_t n_vocab_type = 0; // for BERT-style token types
  1537. float f_norm_eps;
  1538. float f_norm_rms_eps;
  1539. float rope_freq_base_train;
  1540. float rope_freq_scale_train;
  1541. uint32_t n_yarn_orig_ctx;
  1542. // for State Space Models
  1543. uint32_t ssm_d_conv = 0;
  1544. uint32_t ssm_d_inner = 0;
  1545. uint32_t ssm_d_state = 0;
  1546. uint32_t ssm_dt_rank = 0;
  1547. float f_clamp_kqv = 0.0f;
  1548. float f_max_alibi_bias = 0.0f;
  1549. float f_logit_scale = 0.0f;
  1550. bool causal_attn = true;
  1551. bool need_kq_pos = false;
  1552. enum llama_pooling_type pooling_type = LLAMA_POOLING_TYPE_NONE;
  1553. enum llama_rope_type rope_type = LLAMA_ROPE_TYPE_NONE;
  1554. enum llama_rope_scaling_type rope_scaling_type_train = LLAMA_ROPE_SCALING_TYPE_NONE;
  1555. bool operator!=(const llama_hparams & other) const {
  1556. if (this->vocab_only != other.vocab_only) return true;
  1557. if (this->n_vocab != other.n_vocab) return true;
  1558. if (this->n_ctx_train != other.n_ctx_train) return true;
  1559. if (this->n_embd != other.n_embd) return true;
  1560. if (this->n_head != other.n_head) return true;
  1561. if (this->n_head_kv != other.n_head_kv) return true;
  1562. if (this->n_layer != other.n_layer) return true;
  1563. if (this->n_rot != other.n_rot) return true;
  1564. if (this->n_embd_head_k != other.n_embd_head_k) return true;
  1565. if (this->n_embd_head_v != other.n_embd_head_v) return true;
  1566. if (this->n_ff != other.n_ff) return true;
  1567. if (this->n_expert != other.n_expert) return true;
  1568. if (this->n_expert_used != other.n_expert_used) return true;
  1569. if (this->rope_finetuned != other.rope_finetuned) return true;
  1570. if (this->n_yarn_orig_ctx != other.n_yarn_orig_ctx) return true;
  1571. if (this->ssm_d_conv != other.ssm_d_conv) return true;
  1572. if (this->ssm_d_inner != other.ssm_d_inner) return true;
  1573. if (this->ssm_d_state != other.ssm_d_state) return true;
  1574. if (this->ssm_dt_rank != other.ssm_dt_rank) return true;
  1575. const float EPSILON = 1e-9f;
  1576. if (!is_float_close(this->f_norm_eps, other.f_norm_eps, EPSILON)) return true;
  1577. if (!is_float_close(this->f_norm_rms_eps, other.f_norm_rms_eps, EPSILON)) return true;
  1578. if (!is_float_close(this->rope_freq_base_train, other.rope_freq_base_train, EPSILON)) return true;
  1579. if (!is_float_close(this->rope_freq_scale_train, other.rope_freq_scale_train, EPSILON)) return true;
  1580. return false;
  1581. }
  1582. uint32_t n_gqa() const {
  1583. if (n_head_kv == 0) {
  1584. return 0;
  1585. }
  1586. return n_head/n_head_kv;
  1587. }
  1588. uint32_t n_embd_k_gqa() const { // dimension of key embeddings across all k-v heads
  1589. return n_embd_head_k * n_head_kv;
  1590. }
  1591. uint32_t n_embd_v_gqa() const { // dimension of value embeddings across all k-v heads
  1592. return n_embd_head_v * n_head_kv;
  1593. }
  1594. uint32_t n_embd_k_s() const { // dimension of the rolling state embeddings
  1595. // corresponds to Mamba's conv_states size
  1596. // TODO: maybe support other convolution strides than 1
  1597. // NOTE: since the first column of the conv_state is shifted out each time, it's not actually needed
  1598. return (ssm_d_conv > 0 ? ssm_d_conv - 1 : 0) * ssm_d_inner;
  1599. }
  1600. uint32_t n_embd_v_s() const { // dimension of the recurrent state embeddings
  1601. // corresponds to Mamba's ssm_states size
  1602. return ssm_d_state * ssm_d_inner;
  1603. }
  1604. };
  1605. struct llama_cparams {
  1606. uint32_t n_ctx; // context size used during inference
  1607. uint32_t n_batch;
  1608. uint32_t n_ubatch;
  1609. uint32_t n_seq_max;
  1610. uint32_t n_threads; // number of threads to use for generation
  1611. uint32_t n_threads_batch; // number of threads to use for batch processing
  1612. float rope_freq_base;
  1613. float rope_freq_scale;
  1614. uint32_t n_yarn_orig_ctx;
  1615. // These hyperparameters are not exposed in GGUF, because all
  1616. // existing YaRN models use the same values for them.
  1617. float yarn_ext_factor;
  1618. float yarn_attn_factor;
  1619. float yarn_beta_fast;
  1620. float yarn_beta_slow;
  1621. float defrag_thold;
  1622. bool embeddings;
  1623. bool causal_attn;
  1624. bool offload_kqv;
  1625. enum llama_pooling_type pooling_type;
  1626. ggml_backend_sched_eval_callback cb_eval;
  1627. void * cb_eval_user_data;
  1628. };
  1629. struct llama_layer {
  1630. // normalization
  1631. struct ggml_tensor * attn_norm;
  1632. struct ggml_tensor * attn_norm_b;
  1633. struct ggml_tensor * attn_norm_2;
  1634. struct ggml_tensor * attn_norm_2_b;
  1635. struct ggml_tensor * attn_q_norm;
  1636. struct ggml_tensor * attn_q_norm_b;
  1637. struct ggml_tensor * attn_k_norm;
  1638. struct ggml_tensor * attn_k_norm_b;
  1639. struct ggml_tensor * attn_out_norm;
  1640. struct ggml_tensor * attn_out_norm_b;
  1641. // attention
  1642. struct ggml_tensor * wq;
  1643. struct ggml_tensor * wk;
  1644. struct ggml_tensor * wv;
  1645. struct ggml_tensor * wo;
  1646. struct ggml_tensor * wqkv;
  1647. // attention bias
  1648. struct ggml_tensor * bq;
  1649. struct ggml_tensor * bk;
  1650. struct ggml_tensor * bv;
  1651. struct ggml_tensor * bo;
  1652. struct ggml_tensor * bqkv;
  1653. // normalization
  1654. struct ggml_tensor * ffn_norm;
  1655. struct ggml_tensor * ffn_norm_b;
  1656. struct ggml_tensor * layer_out_norm;
  1657. struct ggml_tensor * layer_out_norm_b;
  1658. // ff
  1659. struct ggml_tensor * ffn_gate; // w1
  1660. struct ggml_tensor * ffn_down; // w2
  1661. struct ggml_tensor * ffn_up; // w3
  1662. // ff MoE
  1663. struct ggml_tensor * ffn_gate_inp;
  1664. struct ggml_tensor * ffn_gate_exp[LLAMA_MAX_EXPERTS];
  1665. struct ggml_tensor * ffn_down_exp[LLAMA_MAX_EXPERTS];
  1666. struct ggml_tensor * ffn_up_exp [LLAMA_MAX_EXPERTS];
  1667. // ff bias
  1668. struct ggml_tensor * ffn_down_b; // b2
  1669. struct ggml_tensor * ffn_up_b; // b3
  1670. struct ggml_tensor * ffn_act;
  1671. // mamba proj
  1672. struct ggml_tensor * ssm_in;
  1673. struct ggml_tensor * ssm_x;
  1674. struct ggml_tensor * ssm_dt;
  1675. struct ggml_tensor * ssm_out;
  1676. // mamba
  1677. struct ggml_tensor * ssm_conv1d;
  1678. struct ggml_tensor * ssm_a;
  1679. struct ggml_tensor * ssm_d;
  1680. // mamba bias
  1681. struct ggml_tensor * ssm_conv1d_b;
  1682. struct ggml_tensor * ssm_dt_b;
  1683. };
  1684. struct llama_kv_cell {
  1685. llama_pos pos = -1;
  1686. llama_pos delta = 0;
  1687. int32_t src = 0; // used by recurrent state models to copy states
  1688. std::set<llama_seq_id> seq_id;
  1689. bool has_seq_id(const llama_seq_id & id) const {
  1690. return seq_id.find(id) != seq_id.end();
  1691. }
  1692. bool is_empty() const {
  1693. return seq_id.empty();
  1694. }
  1695. bool is_same_seq(const llama_kv_cell & other) const {
  1696. return seq_id == other.seq_id;
  1697. }
  1698. };
  1699. // ring-buffer of cached KV data
  1700. struct llama_kv_cache {
  1701. bool has_shift = false;
  1702. bool do_defrag = false;
  1703. bool do_copy = false;
  1704. // with recurrent state models, a cell can hold the state for more than one past token
  1705. bool recurrent = false;
  1706. // Note: The value of head isn't only used to optimize searching
  1707. // for a free KV slot. llama_decode_internal also uses it, so it
  1708. // cannot be freely changed after a slot has been allocated.
  1709. uint32_t head = 0;
  1710. uint32_t size = 0;
  1711. uint32_t used = 0; // used cells (i.e. at least one seq_id)
  1712. // computed before each graph build
  1713. uint32_t n = 0;
  1714. ggml_type type_k = GGML_TYPE_F16;
  1715. ggml_type type_v = GGML_TYPE_F16;
  1716. std::vector<llama_kv_cell> cells;
  1717. std::vector<struct ggml_tensor *> k_l; // per layer
  1718. std::vector<struct ggml_tensor *> v_l;
  1719. std::vector<struct ggml_context *> ctxs;
  1720. std::vector<ggml_backend_buffer_t> bufs;
  1721. size_t total_size() const {
  1722. size_t size = 0;
  1723. for (ggml_backend_buffer_t buf : bufs) {
  1724. size += ggml_backend_buffer_get_size(buf);
  1725. }
  1726. return size;
  1727. }
  1728. ~llama_kv_cache() {
  1729. for (struct ggml_context * ctx : ctxs) {
  1730. ggml_free(ctx);
  1731. }
  1732. for (ggml_backend_buffer_t buf : bufs) {
  1733. ggml_backend_buffer_free(buf);
  1734. }
  1735. }
  1736. };
  1737. struct llama_control_vector {
  1738. std::vector<struct ggml_tensor *> tensors; // per layer
  1739. std::vector<struct ggml_context *> ctxs;
  1740. std::vector<ggml_backend_buffer_t> bufs;
  1741. int32_t layer_start = -1;
  1742. int32_t layer_end = -1;
  1743. ggml_tensor * tensor_for(int il) const {
  1744. if (il < 0 || il < layer_start || il > layer_end || (size_t) il >= tensors.size()) {
  1745. return nullptr;
  1746. }
  1747. return tensors[il];
  1748. }
  1749. ~llama_control_vector() {
  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_vocab {
  1759. using id = int32_t;
  1760. using token = std::string;
  1761. using ttype = llama_token_type;
  1762. struct token_data {
  1763. token text;
  1764. float score;
  1765. ttype type;
  1766. };
  1767. enum llama_vocab_type type = LLAMA_VOCAB_TYPE_SPM;
  1768. std::unordered_map<token, id> token_to_id;
  1769. std::vector<token_data> id_to_token;
  1770. std::unordered_map<token, id> special_tokens_cache;
  1771. std::map<std::pair<std::string, std::string>, int> bpe_ranks;
  1772. // default LLaMA special tokens
  1773. id special_bos_id = 1;
  1774. id special_eos_id = 2;
  1775. id special_unk_id = 0;
  1776. id special_sep_id = -1;
  1777. id special_pad_id = -1;
  1778. int special_add_bos = -1; // -1 unknown, 1 add, 0 don't add.
  1779. int special_add_eos = -1; // -1 unknown, 1 add, 0 don't add.
  1780. id linefeed_id = 13;
  1781. id special_prefix_id = 32007;
  1782. id special_middle_id = 32009;
  1783. id special_suffix_id = 32008;
  1784. id special_eot_id = 32010;
  1785. bool add_space_prefix = true;
  1786. int find_bpe_rank(const std::string & token_left, const std::string & token_right) const {
  1787. GGML_ASSERT(token_left.find(' ') == std::string::npos);
  1788. GGML_ASSERT(token_left.find('\n') == std::string::npos);
  1789. GGML_ASSERT(token_right.find(' ') == std::string::npos);
  1790. GGML_ASSERT(token_right.find('\n') == std::string::npos);
  1791. auto it = bpe_ranks.find(std::make_pair(token_left, token_right));
  1792. if (it == bpe_ranks.end()) {
  1793. return -1;
  1794. }
  1795. return it->second;
  1796. }
  1797. };
  1798. struct llama_model {
  1799. e_model type = MODEL_UNKNOWN;
  1800. llm_arch arch = LLM_ARCH_UNKNOWN;
  1801. llama_ftype ftype = LLAMA_FTYPE_ALL_F32;
  1802. std::string name = "n/a";
  1803. llama_hparams hparams = {};
  1804. llama_vocab vocab;
  1805. struct ggml_tensor * tok_embd;
  1806. struct ggml_tensor * type_embd;
  1807. struct ggml_tensor * pos_embd;
  1808. struct ggml_tensor * tok_norm;
  1809. struct ggml_tensor * tok_norm_b;
  1810. struct ggml_tensor * output_norm;
  1811. struct ggml_tensor * output_norm_b;
  1812. struct ggml_tensor * output;
  1813. struct ggml_tensor * output_b;
  1814. std::vector<llama_layer> layers;
  1815. llama_split_mode split_mode;
  1816. int main_gpu;
  1817. int n_gpu_layers;
  1818. // gguf metadata
  1819. std::unordered_map<std::string, std::string> gguf_kv;
  1820. // layer -> buffer type mapping
  1821. struct layer_buft {
  1822. layer_buft() : buft_matrix(nullptr), buft(nullptr) {}
  1823. layer_buft(ggml_backend_buffer_type_t matrix) : buft_matrix(matrix), buft(matrix) {}
  1824. layer_buft(ggml_backend_buffer_type_t matrix, ggml_backend_buffer_type_t other) : buft_matrix(matrix), buft(other) {}
  1825. ggml_backend_buffer_type_t buft_matrix; // matrices only - used by split buffers and backends that support only matrix multiplication
  1826. ggml_backend_buffer_type_t buft; // everything else
  1827. };
  1828. layer_buft buft_input;
  1829. layer_buft buft_output;
  1830. std::vector<layer_buft> buft_layer;
  1831. // contexts where the model tensors metadata is stored
  1832. std::vector<struct ggml_context *> ctxs;
  1833. // the model memory buffers for the tensor data
  1834. std::vector<ggml_backend_buffer_t> bufs;
  1835. // model memory mapped files
  1836. llama_mmaps mappings;
  1837. // objects representing data potentially being locked in memory
  1838. llama_mlocks mlock_bufs;
  1839. llama_mlocks mlock_mmaps;
  1840. // for quantize-stats only
  1841. std::vector<std::pair<std::string, struct ggml_tensor *>> tensors_by_name;
  1842. int64_t t_load_us = 0;
  1843. int64_t t_start_us = 0;
  1844. ~llama_model() {
  1845. for (struct ggml_context * ctx : ctxs) {
  1846. ggml_free(ctx);
  1847. }
  1848. for (ggml_backend_buffer_t buf : bufs) {
  1849. #ifdef GGML_USE_CUDA
  1850. if (ggml_backend_buffer_get_type(buf) == ggml_backend_cpu_buffer_type()) {
  1851. ggml_backend_cuda_unregister_host_buffer(ggml_backend_buffer_get_base(buf));
  1852. }
  1853. #endif
  1854. ggml_backend_buffer_free(buf);
  1855. }
  1856. }
  1857. };
  1858. struct llama_context {
  1859. llama_context(const llama_model & model) : model(model), t_start_us(model.t_start_us), t_load_us(model.t_load_us) {}
  1860. ~llama_context() {
  1861. ggml_backend_sched_free(sched);
  1862. for (ggml_backend_t backend : backends) {
  1863. ggml_backend_free(backend);
  1864. }
  1865. #ifdef GGML_USE_VULKAN
  1866. ggml_vk_free_cpu_assist();
  1867. #endif
  1868. ggml_backend_buffer_free(buf_output);
  1869. }
  1870. llama_cparams cparams;
  1871. std::vector<ggml_backend_t> backends;
  1872. #ifdef GGML_USE_METAL
  1873. ggml_backend_t backend_metal = nullptr;
  1874. #endif
  1875. ggml_backend_t backend_cpu = nullptr;
  1876. const llama_model & model;
  1877. // key + value cache for the self attention
  1878. struct llama_kv_cache kv_self;
  1879. std::mt19937 rng;
  1880. bool has_evaluated_once = false;
  1881. int64_t t_start_us;
  1882. int64_t t_load_us;
  1883. int64_t t_sample_us = 0;
  1884. int64_t t_p_eval_us = 0;
  1885. int64_t t_eval_us = 0;
  1886. int64_t t_compute_start_us = 0;
  1887. int64_t n_queued_tokens = 0;
  1888. int32_t n_sample = 0; // number of tokens sampled
  1889. int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1)
  1890. int32_t n_eval = 0; // number of eval calls
  1891. // host buffer for the model output (logits and embeddings)
  1892. ggml_backend_buffer_t buf_output = nullptr;
  1893. // decode output (2-dimensional array: [n_outputs][n_vocab])
  1894. size_t logits_size = 0; // capacity (of floats) for logits
  1895. float * logits = nullptr;
  1896. std::vector<int32_t> output_ids; // map batch token positions to ids of the logits and embd buffers
  1897. size_t output_size = 0; // capacity (of tokens positions) for the output buffers
  1898. int32_t n_outputs = 0; // number of actually-used outputs in the current ubatch
  1899. bool logits_all = false;
  1900. // embeddings output (2-dimensional array: [n_outputs][n_embd])
  1901. // populated only when pooling_type == LLAMA_POOLING_TYPE_NONE
  1902. size_t embd_size = 0; // capacity (of floats) for embeddings
  1903. float * embd = nullptr;
  1904. // sequence embeddings output (map of [n_embd] vectors)
  1905. // populated only when pooling_type != LLAMA_POOLING_TYPE_NONE
  1906. std::map<llama_seq_id, std::vector<float>> embd_seq;
  1907. // memory buffers used to evaluate the model
  1908. std::vector<uint8_t> buf_compute_meta;
  1909. ggml_backend_sched_t sched = nullptr;
  1910. ggml_abort_callback abort_callback = nullptr;
  1911. void * abort_callback_data = nullptr;
  1912. // input tensors
  1913. struct ggml_tensor * inp_tokens; // I32 [n_batch]
  1914. struct ggml_tensor * inp_embd; // F32 [n_embd, n_batch]
  1915. struct ggml_tensor * inp_pos; // I32 [n_batch]
  1916. struct ggml_tensor * inp_out_ids; // I32 [n_outputs]
  1917. struct ggml_tensor * inp_KQ_mask; // F32 [kv_size, n_batch]
  1918. struct ggml_tensor * inp_KQ_pos; // F32 [n_kv]
  1919. struct ggml_tensor * inp_K_shift; // I32 [kv_size]
  1920. struct ggml_tensor * inp_mean; // F32 [n_batch, n_batch]
  1921. struct ggml_tensor * inp_cls; // I32 [n_batch]
  1922. struct ggml_tensor * inp_s_copy; // I32 [kv_size]
  1923. struct ggml_tensor * inp_s_mask; // F32 [1, n_kv]
  1924. struct ggml_tensor * inp_s_seq; // I32 [n_kv, n_batch]
  1925. // control vectors
  1926. struct llama_control_vector cvec;
  1927. #ifdef GGML_USE_MPI
  1928. ggml_mpi_context * ctx_mpi = NULL;
  1929. #endif
  1930. };
  1931. //
  1932. // kv cache helpers
  1933. //
  1934. static bool llama_kv_cache_init(
  1935. struct llama_kv_cache & cache,
  1936. const llama_model & model,
  1937. ggml_type type_k,
  1938. ggml_type type_v,
  1939. uint32_t kv_size,
  1940. bool offload) {
  1941. const struct llama_hparams & hparams = model.hparams;
  1942. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  1943. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  1944. const int64_t n_layer = hparams.n_layer;
  1945. cache.has_shift = false;
  1946. // TODO: find a nicer way to add other recurrent model architectures
  1947. cache.recurrent = model.arch == LLM_ARCH_MAMBA;
  1948. // TODO: support mixed reccurent Transformer architectues
  1949. // NOTE: (!a || b) is a logical implication (a -> b)
  1950. GGML_ASSERT(!cache.recurrent || n_embd_k_gqa == hparams.n_embd_k_s());
  1951. GGML_ASSERT(!cache.recurrent || n_embd_v_gqa == hparams.n_embd_v_s());
  1952. GGML_ASSERT( cache.recurrent || n_embd_k_gqa == hparams.n_embd_k_gqa());
  1953. GGML_ASSERT( cache.recurrent || n_embd_v_gqa == hparams.n_embd_v_gqa());
  1954. cache.head = 0;
  1955. cache.size = kv_size;
  1956. cache.used = 0;
  1957. cache.type_k = type_k;
  1958. cache.type_v = type_v;
  1959. cache.cells.clear();
  1960. cache.cells.resize(kv_size);
  1961. if (cache.recurrent) {
  1962. // init state copy sources
  1963. for (uint32_t i = 0; i < cache.size; ++i) {
  1964. cache.cells[i].src = i;
  1965. }
  1966. }
  1967. #ifdef GGML_USE_CLBLAST
  1968. offload = false;
  1969. #endif
  1970. // count used buffer types
  1971. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  1972. if (offload) {
  1973. for (int64_t i = 0; i < n_layer; ++i) {
  1974. buft_layer_count[model.buft_layer[i].buft]++;
  1975. }
  1976. } else {
  1977. buft_layer_count[llama_default_buffer_type_cpu(true)] = n_layer;
  1978. }
  1979. // create a context for each buffer type
  1980. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  1981. for (auto & it : buft_layer_count) {
  1982. int n_layers = it.second;
  1983. struct ggml_init_params params = {
  1984. /*.mem_size =*/ 2u*n_layers*ggml_tensor_overhead(),
  1985. /*.mem_buffer =*/ NULL,
  1986. /*.no_alloc =*/ true,
  1987. };
  1988. ggml_context * ctx = ggml_init(params);
  1989. if (!ctx) {
  1990. LLAMA_LOG_ERROR("%s: failed to allocate context for kv cache\n", __func__);
  1991. return false;
  1992. }
  1993. ctx_map[it.first] = ctx;
  1994. cache.ctxs.push_back(ctx);
  1995. }
  1996. cache.k_l.reserve(n_layer);
  1997. cache.v_l.reserve(n_layer);
  1998. for (int i = 0; i < (int) n_layer; i++) {
  1999. struct ggml_context * ctx = offload ? ctx_map.at(model.buft_layer[i].buft) : cache.ctxs.front();
  2000. ggml_tensor * k = ggml_new_tensor_1d(ctx, type_k, n_embd_k_gqa*kv_size);
  2001. ggml_tensor * v = ggml_new_tensor_1d(ctx, type_v, n_embd_v_gqa*kv_size);
  2002. ggml_format_name(k, "cache_k_l%d", i);
  2003. ggml_format_name(v, "cache_v_l%d", i);
  2004. cache.k_l.push_back(k);
  2005. cache.v_l.push_back(v);
  2006. }
  2007. // allocate tensors and initialize the buffers to avoid NaNs in the padding
  2008. for (auto it : ctx_map) {
  2009. ggml_backend_buffer_type_t buft = it.first;
  2010. ggml_context * ctx = it.second;
  2011. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  2012. if (!buf) {
  2013. LLAMA_LOG_ERROR("%s: failed to allocate buffer for kv cache\n", __func__);
  2014. return false;
  2015. }
  2016. ggml_backend_buffer_clear(buf, 0);
  2017. 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);
  2018. cache.bufs.push_back(buf);
  2019. }
  2020. return true;
  2021. }
  2022. // find an empty slot of size "n_tokens" in the cache
  2023. // updates the cache head
  2024. // Note: On success, it's important that cache.head points
  2025. // to the first cell of the slot.
  2026. static bool llama_kv_cache_find_slot(
  2027. struct llama_kv_cache & cache,
  2028. const struct llama_batch & batch) {
  2029. const uint32_t n_ctx = cache.size;
  2030. const uint32_t n_tokens = batch.n_tokens;
  2031. if (cache.recurrent) {
  2032. // For recurrent state architectures (like Mamba),
  2033. // each KV cache cell can store the state for a whole sequence.
  2034. llama_seq_id min = cache.size - 1;
  2035. llama_seq_id max = 0;
  2036. for (uint32_t i = 0; i < n_tokens; ++i) {
  2037. for (int32_t j = 0; j < batch.n_seq_id[i]; ++j) {
  2038. llama_seq_id seq_id = batch.seq_id[i][j];
  2039. // make sure it's a valid seq_id
  2040. if ((uint32_t) seq_id < cache.size) {
  2041. if (seq_id > max) {
  2042. max = seq_id;
  2043. }
  2044. if (seq_id < min) {
  2045. min = seq_id;
  2046. }
  2047. // Assuming the tokens are in-order
  2048. if (batch.pos[i] != cache.cells[seq_id].pos + 1) {
  2049. // What should happen when the pos backtracks or skips a value?
  2050. // Clearing the state mid-batch would require special-casing which isn't done.
  2051. LLAMA_LOG_WARN("%s: non-consecutive token position %d after %d for sequence %d\n",
  2052. __func__, batch.pos[i], cache.cells[seq_id].pos, seq_id);
  2053. }
  2054. if (cache.cells[seq_id].pos < 0 && 0 <= batch.pos[i]) {
  2055. cache.used += 1;
  2056. }
  2057. cache.cells[seq_id].pos = batch.pos[i];
  2058. // NOTE: seq_ids are not inserted here; they are handled when the input tensors are set
  2059. } else {
  2060. // too big seq_id
  2061. // TODO: would it be possible to resize the KV cache size instead?
  2062. LLAMA_LOG_ERROR("%s: seq_id=%d >= kv_size=%d Try using a bigger --parallel value\n", __func__, seq_id, cache.size);
  2063. return false;
  2064. }
  2065. }
  2066. }
  2067. // allow getting the range of used cells, from head to head + n
  2068. cache.head = min;
  2069. cache.n = max - min + 1;
  2070. // sanity check
  2071. return max >= min;
  2072. }
  2073. // otherwise, one cell per token.
  2074. if (n_tokens > n_ctx) {
  2075. LLAMA_LOG_ERROR("%s: n_tokens=%d > n_ctx=%d\n", __func__, n_tokens, n_ctx);
  2076. return false;
  2077. }
  2078. uint32_t n_tested = 0;
  2079. while (true) {
  2080. if (cache.head + n_tokens > n_ctx) {
  2081. n_tested += n_ctx - cache.head;
  2082. cache.head = 0;
  2083. continue;
  2084. }
  2085. bool found = true;
  2086. for (uint32_t i = 0; i < n_tokens; i++) {
  2087. if (cache.cells[cache.head + i].pos >= 0) {
  2088. found = false;
  2089. cache.head += i + 1;
  2090. n_tested += i + 1;
  2091. break;
  2092. }
  2093. }
  2094. if (found) {
  2095. break;
  2096. }
  2097. if (n_tested >= n_ctx) {
  2098. //LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens);
  2099. return false;
  2100. }
  2101. }
  2102. for (uint32_t i = 0; i < n_tokens; i++) {
  2103. cache.cells[cache.head + i].pos = batch.pos[i];
  2104. for (int32_t j = 0; j < batch.n_seq_id[i]; j++) {
  2105. cache.cells[cache.head + i].seq_id.insert(batch.seq_id[i][j]);
  2106. }
  2107. }
  2108. cache.used += n_tokens;
  2109. return true;
  2110. }
  2111. // find how many cells are currently in use
  2112. static uint32_t llama_kv_cache_cell_max(const struct llama_kv_cache & cache) {
  2113. for (uint32_t i = cache.size; i > 0; --i) {
  2114. const llama_kv_cell & cell = cache.cells[i - 1];
  2115. if (cell.pos >= 0 && !cell.is_empty()) {
  2116. return i;
  2117. }
  2118. }
  2119. return 0;
  2120. }
  2121. static void llama_kv_cache_clear(struct llama_kv_cache & cache) {
  2122. for (int32_t i = 0; i < (int32_t) cache.size; ++i) {
  2123. cache.cells[i].pos = -1;
  2124. cache.cells[i].seq_id.clear();
  2125. }
  2126. cache.head = 0;
  2127. cache.used = 0;
  2128. }
  2129. static bool llama_kv_cache_seq_rm(
  2130. struct llama_kv_cache & cache,
  2131. llama_seq_id seq_id,
  2132. llama_pos p0,
  2133. llama_pos p1) {
  2134. uint32_t new_head = cache.size;
  2135. if (p0 < 0) p0 = 0;
  2136. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2137. // models like Mamba can't have a state partially erased
  2138. if (cache.recurrent) {
  2139. if (seq_id >= (int64_t) cache.size) {
  2140. // could be fatal
  2141. return false;
  2142. }
  2143. if (0 <= seq_id) {
  2144. // partial intersection is invalid
  2145. if ((0 < p0 && p0 <= cache.cells[seq_id].pos) || (0 < p1 && p1 <= cache.cells[seq_id].pos)) {
  2146. return false;
  2147. }
  2148. } else {
  2149. // seq_id is negative, then the range should include everything or nothing
  2150. if (p0 != p1 && (p0 != 0 || p1 != std::numeric_limits<llama_pos>::max())) {
  2151. return false;
  2152. }
  2153. }
  2154. }
  2155. for (uint32_t i = 0; i < cache.size; ++i) {
  2156. if (cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2157. if (seq_id < 0) {
  2158. cache.cells[i].seq_id.clear();
  2159. } else if (cache.cells[i].has_seq_id(seq_id)) {
  2160. cache.cells[i].seq_id.erase(seq_id);
  2161. } else {
  2162. continue;
  2163. }
  2164. if (cache.cells[i].is_empty()) {
  2165. // keep count of the number of used cells
  2166. if (cache.cells[i].pos >= 0) cache.used--;
  2167. cache.cells[i].pos = -1;
  2168. if (new_head == cache.size) new_head = i;
  2169. }
  2170. }
  2171. }
  2172. // If we freed up a slot, set head to it so searching can start there.
  2173. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  2174. return true;
  2175. }
  2176. static void llama_kv_cache_seq_cp(
  2177. struct llama_kv_cache & cache,
  2178. llama_seq_id seq_id_src,
  2179. llama_seq_id seq_id_dst,
  2180. llama_pos p0,
  2181. llama_pos p1) {
  2182. if (p0 < 0) p0 = 0;
  2183. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2184. if (cache.recurrent) {
  2185. if ((uint32_t) seq_id_dst < cache.size && (uint32_t) seq_id_src < cache.size) {
  2186. seq_id_src = cache.cells[seq_id_src].src;
  2187. GGML_ASSERT((uint32_t) seq_id_src < cache.size);
  2188. // intent to "copy from"
  2189. // supports copy chains thanks to taking the source of the source
  2190. cache.cells[seq_id_dst].src = seq_id_src;
  2191. // preserve the "keep or clear" status of the copied sequence
  2192. if (cache.cells[seq_id_src].has_seq_id(seq_id_src)) {
  2193. cache.cells[seq_id_dst].seq_id.insert(seq_id_dst);
  2194. } else {
  2195. cache.cells[seq_id_dst].seq_id.erase(seq_id_dst);
  2196. }
  2197. cache.do_copy = true;
  2198. cache.cells[seq_id_dst].pos = cache.cells[seq_id_src].pos;
  2199. }
  2200. return;
  2201. }
  2202. // otherwise, this is the KV cache of a Transformer-like model
  2203. cache.head = 0;
  2204. for (uint32_t i = 0; i < cache.size; ++i) {
  2205. if (cache.cells[i].has_seq_id(seq_id_src) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2206. cache.cells[i].seq_id.insert(seq_id_dst);
  2207. }
  2208. }
  2209. }
  2210. static void llama_kv_cache_seq_keep(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  2211. uint32_t new_head = cache.size;
  2212. for (uint32_t i = 0; i < cache.size; ++i) {
  2213. if (!cache.cells[i].has_seq_id(seq_id)) {
  2214. if (cache.cells[i].pos >= 0) cache.used--;
  2215. cache.cells[i].pos = -1;
  2216. cache.cells[i].seq_id.clear();
  2217. if (new_head == cache.size) new_head = i;
  2218. } else {
  2219. cache.cells[i].seq_id.clear();
  2220. cache.cells[i].seq_id.insert(seq_id);
  2221. }
  2222. }
  2223. // If we freed up a slot, set head to it so searching can start there.
  2224. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  2225. }
  2226. static void llama_kv_cache_seq_add(
  2227. struct llama_kv_cache & cache,
  2228. llama_seq_id seq_id,
  2229. llama_pos p0,
  2230. llama_pos p1,
  2231. llama_pos delta) {
  2232. uint32_t new_head = cache.size;
  2233. if (p0 < 0) p0 = 0;
  2234. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2235. if (cache.recurrent) {
  2236. // for Mamba-like models, only the pos needs to be shifted
  2237. if (0 <= seq_id && seq_id < (int64_t) cache.size) {
  2238. llama_kv_cell & cell = cache.cells[seq_id];
  2239. if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
  2240. cell.pos += delta;
  2241. }
  2242. }
  2243. return;
  2244. }
  2245. for (uint32_t i = 0; i < cache.size; ++i) {
  2246. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2247. cache.has_shift = true;
  2248. cache.cells[i].pos += delta;
  2249. cache.cells[i].delta += delta;
  2250. if (cache.cells[i].pos < 0) {
  2251. if (!cache.cells[i].is_empty()) {
  2252. cache.used--;
  2253. }
  2254. cache.cells[i].pos = -1;
  2255. cache.cells[i].seq_id.clear();
  2256. if (new_head == cache.size) {
  2257. new_head = i;
  2258. }
  2259. }
  2260. }
  2261. }
  2262. // If we freed up a slot, set head to it so searching can start there.
  2263. // Otherwise we just start the next search from the beginning.
  2264. cache.head = new_head != cache.size ? new_head : 0;
  2265. }
  2266. static void llama_kv_cache_seq_div(
  2267. struct llama_kv_cache & cache,
  2268. llama_seq_id seq_id,
  2269. llama_pos p0,
  2270. llama_pos p1,
  2271. int d) {
  2272. if (p0 < 0) p0 = 0;
  2273. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2274. if (cache.recurrent) {
  2275. // for Mamba-like models, only the pos needs to be changed
  2276. if (0 <= seq_id && seq_id < (int64_t) cache.size) {
  2277. llama_kv_cell & cell = cache.cells[seq_id];
  2278. if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
  2279. cell.pos /= d;
  2280. }
  2281. }
  2282. return;
  2283. }
  2284. for (uint32_t i = 0; i < cache.size; ++i) {
  2285. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2286. cache.has_shift = true;
  2287. {
  2288. llama_pos p_old = cache.cells[i].pos;
  2289. cache.cells[i].pos /= d;
  2290. cache.cells[i].delta += cache.cells[i].pos - p_old;
  2291. }
  2292. }
  2293. }
  2294. }
  2295. static llama_pos llama_kv_cache_seq_pos_max(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  2296. llama_pos result = 0;
  2297. for (uint32_t i = 0; i < cache.size; ++i) {
  2298. if (cache.cells[i].has_seq_id(seq_id)) {
  2299. result = std::max(result, cache.cells[i].pos);
  2300. }
  2301. }
  2302. return result;
  2303. }
  2304. static void llama_kv_cache_defrag(struct llama_kv_cache & cache) {
  2305. cache.do_defrag = true;
  2306. }
  2307. //
  2308. // model loading and saving
  2309. //
  2310. enum llama_fver {
  2311. GGUF_FILE_VERSION_V1 = 1,
  2312. GGUF_FILE_VERSION_V2 = 2,
  2313. GGUF_FILE_VERSION_V3 = 3,
  2314. };
  2315. static const char * llama_file_version_name(llama_fver version) {
  2316. switch (version) {
  2317. case GGUF_FILE_VERSION_V1: return "GGUF V1 (support until nov 2023)";
  2318. case GGUF_FILE_VERSION_V2: return "GGUF V2";
  2319. case GGUF_FILE_VERSION_V3: return "GGUF V3 (latest)";
  2320. }
  2321. return "unknown";
  2322. }
  2323. static std::string llama_format_tensor_shape(const std::vector<int64_t> & ne) {
  2324. char buf[256];
  2325. snprintf(buf, sizeof(buf), "%5" PRId64, ne.at(0));
  2326. for (size_t i = 1; i < ne.size(); i++) {
  2327. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, ne.at(i));
  2328. }
  2329. return buf;
  2330. }
  2331. static std::string llama_format_tensor_shape(const struct ggml_tensor * t) {
  2332. char buf[256];
  2333. snprintf(buf, sizeof(buf), "%5" PRId64, t->ne[0]);
  2334. for (int i = 1; i < GGML_MAX_DIMS; i++) {
  2335. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, t->ne[i]);
  2336. }
  2337. return buf;
  2338. }
  2339. namespace GGUFMeta {
  2340. template <typename T, gguf_type gt_, T (*gfun)(const gguf_context *, const int)>
  2341. struct GKV_Base_Type {
  2342. static constexpr gguf_type gt = gt_;
  2343. static T getter(const gguf_context * ctx, const int kid) {
  2344. return gfun(ctx, kid);
  2345. }
  2346. };
  2347. template<typename T> struct GKV_Base;
  2348. template<> struct GKV_Base<bool >: GKV_Base_Type<bool, GGUF_TYPE_BOOL, gguf_get_val_bool> {};
  2349. template<> struct GKV_Base<uint8_t >: GKV_Base_Type<uint8_t, GGUF_TYPE_UINT8, gguf_get_val_u8 > {};
  2350. template<> struct GKV_Base<uint16_t >: GKV_Base_Type<uint16_t, GGUF_TYPE_UINT16, gguf_get_val_u16 > {};
  2351. template<> struct GKV_Base<uint32_t >: GKV_Base_Type<uint32_t, GGUF_TYPE_UINT32, gguf_get_val_u32 > {};
  2352. template<> struct GKV_Base<uint64_t >: GKV_Base_Type<uint64_t, GGUF_TYPE_UINT64, gguf_get_val_u64 > {};
  2353. template<> struct GKV_Base<int8_t >: GKV_Base_Type<int8_t, GGUF_TYPE_INT8, gguf_get_val_i8 > {};
  2354. template<> struct GKV_Base<int16_t >: GKV_Base_Type<int16_t, GGUF_TYPE_INT16, gguf_get_val_i16 > {};
  2355. template<> struct GKV_Base<int32_t >: GKV_Base_Type<int32_t, GGUF_TYPE_INT32, gguf_get_val_i32 > {};
  2356. template<> struct GKV_Base<int64_t >: GKV_Base_Type<int64_t, GGUF_TYPE_INT64, gguf_get_val_i64 > {};
  2357. template<> struct GKV_Base<float >: GKV_Base_Type<float, GGUF_TYPE_FLOAT32, gguf_get_val_f32 > {};
  2358. template<> struct GKV_Base<double >: GKV_Base_Type<double, GGUF_TYPE_FLOAT64, gguf_get_val_f64 > {};
  2359. template<> struct GKV_Base<const char *>: GKV_Base_Type<const char *, GGUF_TYPE_STRING, gguf_get_val_str > {};
  2360. template<> struct GKV_Base<std::string> {
  2361. static constexpr gguf_type gt = GGUF_TYPE_STRING;
  2362. static std::string getter(const gguf_context * ctx, const int kid) {
  2363. return gguf_get_val_str(ctx, kid);
  2364. }
  2365. };
  2366. struct ArrayInfo {
  2367. const gguf_type gt;
  2368. const size_t length;
  2369. const void * data;
  2370. };
  2371. template<> struct GKV_Base<ArrayInfo> {
  2372. public:
  2373. static constexpr gguf_type gt = GGUF_TYPE_ARRAY;
  2374. static ArrayInfo getter(const gguf_context *ctx, const int k) {
  2375. return ArrayInfo {
  2376. gguf_get_arr_type(ctx, k),
  2377. size_t(gguf_get_arr_n(ctx, k)),
  2378. gguf_get_arr_data(ctx, k),
  2379. };
  2380. }
  2381. };
  2382. template<typename T>
  2383. class GKV : public GKV_Base<T> {
  2384. GKV() = delete;
  2385. public:
  2386. static T get_kv(const gguf_context * ctx, const int k) {
  2387. const enum gguf_type kt = gguf_get_kv_type(ctx, k);
  2388. if (kt != GKV::gt) {
  2389. throw std::runtime_error(format("key %s has wrong type %s but expected type %s",
  2390. gguf_get_key(ctx, k), gguf_type_name(kt), gguf_type_name(GKV::gt)));
  2391. }
  2392. return GKV::getter(ctx, k);
  2393. }
  2394. static const char * override_type_to_str(const llama_model_kv_override_type ty) {
  2395. switch (ty) {
  2396. case LLAMA_KV_OVERRIDE_TYPE_BOOL: return "bool";
  2397. case LLAMA_KV_OVERRIDE_TYPE_INT: return "int";
  2398. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: return "float";
  2399. }
  2400. return "unknown";
  2401. }
  2402. static bool validate_override(const llama_model_kv_override_type expected_type, const struct llama_model_kv_override * ovrd) {
  2403. if (!ovrd) { return false; }
  2404. if (ovrd->tag == expected_type) {
  2405. LLAMA_LOG_INFO("%s: Using metadata override (%5s) '%s' = ",
  2406. __func__, override_type_to_str(ovrd->tag), ovrd->key);
  2407. switch (ovrd->tag) {
  2408. case LLAMA_KV_OVERRIDE_TYPE_BOOL: {
  2409. LLAMA_LOG_INFO("%s\n", ovrd->bool_value ? "true" : "false");
  2410. } break;
  2411. case LLAMA_KV_OVERRIDE_TYPE_INT: {
  2412. LLAMA_LOG_INFO("%" PRId64 "\n", ovrd->int_value);
  2413. } break;
  2414. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: {
  2415. LLAMA_LOG_INFO("%.6f\n", ovrd->float_value);
  2416. } break;
  2417. default:
  2418. // Shouldn't be possible to end up here, but just in case...
  2419. throw std::runtime_error(
  2420. format("Unsupported attempt to override %s type for metadata key %s\n",
  2421. override_type_to_str(ovrd->tag), ovrd->key));
  2422. }
  2423. return true;
  2424. }
  2425. LLAMA_LOG_WARN("%s: Warning: Bad metadata override type for key '%s', expected %s but got %s\n",
  2426. __func__, ovrd->key, override_type_to_str(expected_type), override_type_to_str(ovrd->tag));
  2427. return false;
  2428. }
  2429. template<typename OT>
  2430. static typename std::enable_if<std::is_same<OT, bool>::value, bool>::type
  2431. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  2432. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_BOOL, ovrd)) {
  2433. target = ovrd->bool_value;
  2434. return true;
  2435. }
  2436. return false;
  2437. }
  2438. template<typename OT>
  2439. static typename std::enable_if<!std::is_same<OT, bool>::value && std::is_integral<OT>::value, bool>::type
  2440. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  2441. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_INT, ovrd)) {
  2442. target = ovrd->int_value;
  2443. return true;
  2444. }
  2445. return false;
  2446. }
  2447. template<typename OT>
  2448. static typename std::enable_if<std::is_floating_point<OT>::value, bool>::type
  2449. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  2450. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_FLOAT, ovrd)) {
  2451. target = ovrd->float_value;
  2452. return true;
  2453. }
  2454. return false;
  2455. }
  2456. template<typename OT>
  2457. static typename std::enable_if<std::is_same<OT, std::string>::value, bool>::type
  2458. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  2459. (void)target;
  2460. (void)ovrd;
  2461. if (!ovrd) { return false; }
  2462. // Currently, we should never end up here so it would be a bug if we do.
  2463. throw std::runtime_error(format("Unsupported attempt to override string type for metadata key %s\n",
  2464. ovrd ? ovrd->key : "NULL"));
  2465. }
  2466. static bool set(const gguf_context * ctx, const int k, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  2467. if (try_override<T>(target, ovrd)) {
  2468. return true;
  2469. }
  2470. if (k < 0) { return false; }
  2471. target = get_kv(ctx, k);
  2472. return true;
  2473. }
  2474. static bool set(const gguf_context * ctx, const char * key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  2475. return set(ctx, gguf_find_key(ctx, key), target, ovrd);
  2476. }
  2477. static bool set(const gguf_context * ctx, const std::string & key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  2478. return set(ctx, key.c_str(), target, ovrd);
  2479. }
  2480. };
  2481. }
  2482. using llama_buf_map = std::unordered_map<uint32_t, ggml_backend_buffer_t>;
  2483. struct llama_model_loader {
  2484. int n_kv = 0;
  2485. int n_tensors = 0;
  2486. int n_created = 0;
  2487. int64_t n_elements = 0;
  2488. size_t n_bytes = 0;
  2489. bool use_mmap = false;
  2490. llama_files files;
  2491. llama_ftype ftype;
  2492. llama_fver fver;
  2493. llama_mmaps mappings;
  2494. // Holds information on a model weights
  2495. struct llama_tensor_weights {
  2496. uint16_t idx; // source file index
  2497. size_t offs; // tensor data offset in the original file
  2498. ggml_tensor * tensor;
  2499. llama_tensor_weights(uint16_t idx, const char * name, const struct gguf_context * gguf_ctx, ggml_tensor * tensor) : idx(idx), tensor(tensor) {
  2500. const int tensor_idx = gguf_find_tensor(gguf_ctx, name);
  2501. offs = gguf_get_data_offset(gguf_ctx) + gguf_get_tensor_offset(gguf_ctx, tensor_idx);
  2502. }
  2503. };
  2504. std::vector<llama_tensor_weights> weights;
  2505. std::unordered_map<std::string, struct llama_model_kv_override> kv_overrides;
  2506. struct gguf_context * meta = NULL;
  2507. std::vector<ggml_context *> contexts;
  2508. std::string arch_name;
  2509. LLM_KV llm_kv = LLM_KV(LLM_ARCH_UNKNOWN);
  2510. llama_model_loader(const std::string & fname, bool use_mmap, const struct llama_model_kv_override * param_overrides_p) {
  2511. int trace = 0;
  2512. if (getenv("LLAMA_TRACE")) {
  2513. trace = atoi(getenv("LLAMA_TRACE"));
  2514. }
  2515. if (param_overrides_p != nullptr) {
  2516. for (const struct llama_model_kv_override *p = param_overrides_p; p->key[0] != 0; p++) {
  2517. kv_overrides.insert({std::string(p->key), *p});
  2518. }
  2519. }
  2520. struct ggml_context * ctx = NULL;
  2521. struct gguf_init_params params = {
  2522. /*.no_alloc = */ true,
  2523. /*.ctx = */ &ctx,
  2524. };
  2525. meta = gguf_init_from_file(fname.c_str(), params);
  2526. if (!meta) {
  2527. throw std::runtime_error(format("%s: failed to load model from %s\n", __func__, fname.c_str()));
  2528. }
  2529. get_key(llm_kv(LLM_KV_GENERAL_ARCHITECTURE), arch_name, false);
  2530. llm_kv = LLM_KV(llm_arch_from_string(arch_name));
  2531. // Save tensors data offset of the main file.
  2532. // For subsidiary files, `meta` tensor data offset must not be used,
  2533. // so we build a unified tensors index for weights.
  2534. for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  2535. weights.emplace_back(llama_tensor_weights(0, cur->name, meta, cur));
  2536. }
  2537. files.emplace_back(new llama_file(fname.c_str(), "rb"));
  2538. contexts.emplace_back(ctx);
  2539. uint16_t n_split = 0;
  2540. get_key(llm_kv(LLM_KV_SPLIT_COUNT), n_split, false);
  2541. // Load additional GGML contexts
  2542. if (n_split > 1) {
  2543. uint16_t idx = 0;
  2544. get_key(llm_kv(LLM_KV_SPLIT_NO), idx);
  2545. if (idx != 0) {
  2546. throw std::runtime_error(format("illegal split file: %d, model must be loaded with the first split", idx));
  2547. }
  2548. char split_prefix[PATH_MAX] = {0};
  2549. if (!llama_split_prefix(split_prefix, sizeof(split_prefix), fname.c_str(), idx, n_split)) {
  2550. throw std::runtime_error(format("invalid split file: %s", fname.c_str()));
  2551. }
  2552. if (trace > 0) {
  2553. LLAMA_LOG_INFO("%s: loading additional %d GGUFs\n", __func__, n_split);
  2554. }
  2555. char split_path[PATH_MAX] = {0};
  2556. for (idx = 1; idx < n_split; idx++) {
  2557. llama_split_path(split_path, sizeof(split_path), split_prefix, idx, n_split);
  2558. struct gguf_init_params split_params = {
  2559. /*.no_alloc = */ true,
  2560. /*.ctx = */ &ctx,
  2561. };
  2562. struct gguf_context * ctx_gguf = gguf_init_from_file(split_path, split_params);
  2563. if (!ctx_gguf) {
  2564. throw std::runtime_error(format("%s: failed to load GGUF split from %s\n", __func__, split_path));
  2565. }
  2566. // Save tensors data offset info of the shard.
  2567. for (ggml_tensor * cur = ggml_get_first_tensor(ctx); cur; cur = ggml_get_next_tensor(ctx, cur)) {
  2568. weights.emplace_back(llama_tensor_weights(idx, cur->name, ctx_gguf, cur));
  2569. }
  2570. files.emplace_back(new llama_file(split_path, "rb"));
  2571. contexts.emplace_back(ctx);
  2572. gguf_free(ctx_gguf);
  2573. }
  2574. get_key(llm_kv(LLM_KV_SPLIT_TENSORS_COUNT), n_tensors);
  2575. // sanity check
  2576. {
  2577. const int n_tensors_loaded = (int) weights.size();
  2578. if (n_tensors != n_tensors_loaded) {
  2579. throw std::runtime_error(format("corrupted model: %d tensors expected but %d found", n_tensors, n_tensors_loaded));
  2580. }
  2581. }
  2582. LLAMA_LOG_INFO("%s: additional %d GGUFs metadata loaded.\n", __func__, n_split - 1);
  2583. }
  2584. n_kv = gguf_get_n_kv(meta);
  2585. n_tensors = weights.size();
  2586. fver = (enum llama_fver) gguf_get_version(meta);
  2587. for (auto & w : weights) {
  2588. n_elements += ggml_nelements(w.tensor);
  2589. n_bytes += ggml_nbytes(w.tensor);
  2590. }
  2591. LLAMA_LOG_INFO("%s: loaded meta data with %d key-value pairs and %d tensors from %s (version %s)\n",
  2592. __func__, n_kv, n_tensors, fname.c_str(), llama_file_version_name(fver));
  2593. // determine file type based on the number of tensors for each quantization and print meta data
  2594. // TODO: make optional
  2595. {
  2596. std::map<enum ggml_type, uint32_t> n_type;
  2597. uint32_t n_type_max = 0;
  2598. enum ggml_type type_max = GGML_TYPE_F32;
  2599. for (int i = 0; i < n_tensors; i++) {
  2600. const ggml_tensor * tensor = weights.at(i).tensor;
  2601. enum ggml_type type = tensor->type;
  2602. n_type[type]++;
  2603. if (n_type_max < n_type[type]) {
  2604. n_type_max = n_type[type];
  2605. type_max = type;
  2606. }
  2607. if (trace > 0) {
  2608. const uint16_t sid = weights.at(i).idx;
  2609. 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());
  2610. }
  2611. }
  2612. switch (type_max) {
  2613. case GGML_TYPE_F32: ftype = LLAMA_FTYPE_ALL_F32; break;
  2614. case GGML_TYPE_F16: ftype = LLAMA_FTYPE_MOSTLY_F16; break;
  2615. case GGML_TYPE_Q4_0: ftype = LLAMA_FTYPE_MOSTLY_Q4_0; break;
  2616. case GGML_TYPE_Q4_1: ftype = LLAMA_FTYPE_MOSTLY_Q4_1; break;
  2617. case GGML_TYPE_Q5_0: ftype = LLAMA_FTYPE_MOSTLY_Q5_0; break;
  2618. case GGML_TYPE_Q5_1: ftype = LLAMA_FTYPE_MOSTLY_Q5_1; break;
  2619. case GGML_TYPE_Q8_0: ftype = LLAMA_FTYPE_MOSTLY_Q8_0; break;
  2620. case GGML_TYPE_Q2_K: ftype = LLAMA_FTYPE_MOSTLY_Q2_K; break;
  2621. case GGML_TYPE_Q3_K: ftype = LLAMA_FTYPE_MOSTLY_Q3_K_M; break;
  2622. case GGML_TYPE_Q4_K: ftype = LLAMA_FTYPE_MOSTLY_Q4_K_M; break;
  2623. case GGML_TYPE_Q5_K: ftype = LLAMA_FTYPE_MOSTLY_Q5_K_M; break;
  2624. case GGML_TYPE_Q6_K: ftype = LLAMA_FTYPE_MOSTLY_Q6_K; break;
  2625. case GGML_TYPE_IQ2_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XXS; break;
  2626. case GGML_TYPE_IQ2_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XS; break;
  2627. case GGML_TYPE_IQ2_S: ftype = LLAMA_FTYPE_MOSTLY_IQ2_S; break;
  2628. case GGML_TYPE_IQ3_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ3_XXS; break;
  2629. case GGML_TYPE_IQ1_S: ftype = LLAMA_FTYPE_MOSTLY_IQ1_S; break;
  2630. case GGML_TYPE_IQ1_M: ftype = LLAMA_FTYPE_MOSTLY_IQ1_M; break;
  2631. case GGML_TYPE_IQ4_NL: ftype = LLAMA_FTYPE_MOSTLY_IQ4_NL; break;
  2632. case GGML_TYPE_IQ4_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ4_XS; break;
  2633. case GGML_TYPE_IQ3_S: ftype = LLAMA_FTYPE_MOSTLY_IQ3_S; break;
  2634. default:
  2635. {
  2636. LLAMA_LOG_WARN("%s: unknown type %s\n", __func__, ggml_type_name(type_max));
  2637. ftype = LLAMA_FTYPE_ALL_F32;
  2638. } break;
  2639. }
  2640. // this is a way to mark that we have "guessed" the file type
  2641. ftype = (llama_ftype) (ftype | LLAMA_FTYPE_GUESSED);
  2642. {
  2643. const int kid = gguf_find_key(meta, "general.file_type");
  2644. if (kid >= 0) {
  2645. ftype = (llama_ftype) gguf_get_val_u32(meta, kid);
  2646. }
  2647. }
  2648. LLAMA_LOG_INFO("%s: Dumping metadata keys/values. Note: KV overrides do not apply in this output.\n", __func__);
  2649. for (int i = 0; i < n_kv; i++) {
  2650. const char * name = gguf_get_key(meta, i);
  2651. const enum gguf_type type = gguf_get_kv_type(meta, i);
  2652. const std::string type_name =
  2653. type == GGUF_TYPE_ARRAY
  2654. ? format("%s[%s,%d]", gguf_type_name(type), gguf_type_name(gguf_get_arr_type(meta, i)), gguf_get_arr_n(meta, i))
  2655. : gguf_type_name(type);
  2656. std::string value = gguf_kv_to_str(meta, i);
  2657. const size_t MAX_VALUE_LEN = 40;
  2658. if (value.size() > MAX_VALUE_LEN) {
  2659. value = format("%s...", value.substr(0, MAX_VALUE_LEN - 3).c_str());
  2660. }
  2661. replace_all(value, "\n", "\\n");
  2662. LLAMA_LOG_INFO("%s: - kv %3d: %42s %-16s = %s\n", __func__, i, name, type_name.c_str(), value.c_str());
  2663. }
  2664. // print type counts
  2665. for (auto & kv : n_type) {
  2666. if (kv.second == 0) {
  2667. continue;
  2668. }
  2669. LLAMA_LOG_INFO("%s: - type %4s: %4d tensors\n", __func__, ggml_type_name(kv.first), kv.second);
  2670. }
  2671. }
  2672. if (!llama_mmap::SUPPORTED) {
  2673. LLAMA_LOG_WARN("%s: mmap is not supported on this platform\n", __func__);
  2674. use_mmap = false;
  2675. }
  2676. this->use_mmap = use_mmap;
  2677. }
  2678. ~llama_model_loader() {
  2679. if (meta) {
  2680. gguf_free(meta);
  2681. }
  2682. for (auto * ctx : contexts) {
  2683. ggml_free(ctx);
  2684. }
  2685. }
  2686. template<typename T>
  2687. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2688. get_arr_n(const std::string & key, T & result, const bool required = true) {
  2689. const int kid = gguf_find_key(meta, key.c_str());
  2690. if (kid < 0) {
  2691. if (required) {
  2692. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2693. }
  2694. return false;
  2695. }
  2696. struct GGUFMeta::ArrayInfo arr_info =
  2697. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(meta, kid);
  2698. result = arr_info.length;
  2699. return true;
  2700. }
  2701. template<typename T>
  2702. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2703. get_arr_n(const enum llm_kv kid, T & result, const bool required = true) {
  2704. return get_arr_n(llm_kv(kid), result, required);
  2705. }
  2706. template<typename T>
  2707. bool get_key(const std::string & key, T & result, const bool required = true) {
  2708. auto it = kv_overrides.find(key);
  2709. const struct llama_model_kv_override * override =
  2710. it != kv_overrides.end() ? &it->second : nullptr;
  2711. const bool found = GGUFMeta::GKV<T>::set(meta, key, result, override);
  2712. if (required && !found) {
  2713. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2714. }
  2715. return found;
  2716. }
  2717. template<typename T>
  2718. bool get_key(const enum llm_kv kid, T & result, const bool required = true) {
  2719. return get_key(llm_kv(kid), result, required);
  2720. }
  2721. std::string get_arch_name() const {
  2722. return arch_name;
  2723. }
  2724. enum llm_arch get_arch() const {
  2725. return llm_kv.arch;
  2726. }
  2727. const char * get_tensor_name(int i) const {
  2728. return weights.at(i).tensor->name;
  2729. }
  2730. const llama_tensor_weights & get_weights(const char * name) const {
  2731. for (const auto & weight : weights) {
  2732. if (strcmp(name, weight.tensor->name) == 0) {
  2733. return weight;
  2734. }
  2735. }
  2736. throw std::runtime_error(format("tensor %s not found", name));
  2737. }
  2738. struct ggml_tensor * get_tensor_meta(const char * name) const {
  2739. try {
  2740. return get_weights(name).tensor;
  2741. } catch (const std::runtime_error & e) {
  2742. return NULL;
  2743. }
  2744. }
  2745. struct ggml_tensor * get_tensor_meta(int i) const {
  2746. return get_tensor_meta(get_tensor_name(i));
  2747. }
  2748. struct ggml_tensor * create_tensor_for(struct ggml_context * ctx, const struct ggml_tensor * cur) {
  2749. struct ggml_tensor * tensor = ggml_dup_tensor(ctx, cur);
  2750. ggml_set_name(tensor, ggml_get_name(cur));
  2751. n_created++;
  2752. return tensor;
  2753. }
  2754. struct ggml_tensor * create_tensor(struct ggml_context * ctx, const std::string & name, const std::vector<int64_t> & ne, bool required = true) {
  2755. const struct ggml_tensor * cur = get_tensor_meta(name.c_str());
  2756. if (cur == NULL) {
  2757. if (!required) {
  2758. return NULL;
  2759. }
  2760. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
  2761. }
  2762. {
  2763. bool is_ok = true;
  2764. for (size_t i = 0; i < ne.size(); ++i) {
  2765. if (ne[i] != cur->ne[i]) {
  2766. is_ok = false;
  2767. break;
  2768. }
  2769. }
  2770. if (!is_ok) {
  2771. throw std::runtime_error(
  2772. format("%s: tensor '%s' has wrong shape; expected %s, got %s",
  2773. __func__, name.c_str(),
  2774. llama_format_tensor_shape(ne).c_str(),
  2775. llama_format_tensor_shape(cur).c_str()));
  2776. }
  2777. }
  2778. return create_tensor_for(ctx, cur);
  2779. }
  2780. void done_getting_tensors() const {
  2781. if (n_created != n_tensors) {
  2782. throw std::runtime_error(format("%s: wrong number of tensors; expected %d, got %d", __func__, n_tensors, n_created));
  2783. }
  2784. }
  2785. void init_mappings(bool prefetch = true, llama_mlocks * mlock_mmaps = nullptr) {
  2786. if (use_mmap) {
  2787. mappings.reserve(files.size());
  2788. mmaps_used.reserve(files.size());
  2789. for (const auto & file : files) {
  2790. std::unique_ptr<llama_mmap> mapping(new llama_mmap(file.get(), prefetch ? -1 : 0, ggml_is_numa()));
  2791. mmaps_used.emplace_back(std::make_pair(mapping->size, 0));
  2792. if (mlock_mmaps) {
  2793. std::unique_ptr<llama_mlock> mlock_mmap(new llama_mlock());
  2794. mlock_mmap->init(mapping->addr);
  2795. mlock_mmaps->emplace_back(std::move(mlock_mmap));
  2796. }
  2797. mappings.emplace_back(std::move(mapping));
  2798. }
  2799. }
  2800. // compute the total size of all tensors for progress reporting
  2801. for (auto & w : weights) {
  2802. size_data += ggml_nbytes(w.tensor);
  2803. }
  2804. }
  2805. void get_mapping_range(size_t * first, size_t * last, void ** addr, int idx, ggml_context * ctx) const {
  2806. GGML_ASSERT(!mappings.empty());
  2807. const auto & mapping = mappings.at(idx);
  2808. *first = mapping->size;
  2809. *last = 0;
  2810. *addr = mapping->addr;
  2811. for (ggml_tensor * tensor = ggml_get_first_tensor(ctx); tensor; tensor = ggml_get_next_tensor(ctx, tensor)) {
  2812. const auto & w = get_weights(ggml_get_name(tensor));
  2813. if (w.idx != idx) {
  2814. continue;
  2815. }
  2816. *first = std::min(*first, w.offs);
  2817. *last = std::max(*last, w.offs + ggml_nbytes(tensor));
  2818. }
  2819. }
  2820. // for backwards compatibility, does not support ggml-backend
  2821. void load_data_for(struct ggml_tensor * cur) const {
  2822. const auto & w = get_weights(ggml_get_name(cur));
  2823. if (use_mmap) {
  2824. const auto & mapping = mappings.at(w.idx);
  2825. if (cur->data == nullptr) {
  2826. cur->data = (uint8_t *)mapping->addr + w.offs;
  2827. } else {
  2828. memcpy(cur->data, (uint8_t *)mapping->addr + w.offs, ggml_nbytes(cur));
  2829. }
  2830. } else {
  2831. GGML_ASSERT(cur->data != nullptr);
  2832. GGML_ASSERT(w.idx < files.size());
  2833. const auto & file = files.at(w.idx);
  2834. file->seek(w.offs, SEEK_SET);
  2835. file->read_raw(cur->data, ggml_nbytes(cur));
  2836. }
  2837. }
  2838. size_t size_done = 0;
  2839. size_t size_data = 0;
  2840. std::vector<std::pair<size_t, size_t>> mmaps_used;
  2841. // Returns false if cancelled by progress_callback
  2842. bool load_all_data(
  2843. struct ggml_context * ctx,
  2844. llama_buf_map & bufs_mmap,
  2845. llama_mlocks * lmlocks,
  2846. llama_progress_callback progress_callback,
  2847. void * progress_callback_user_data) {
  2848. GGML_ASSERT(size_data != 0 && "call init_mappings() first");
  2849. std::vector<no_init<uint8_t>> read_buf;
  2850. for (struct ggml_tensor * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  2851. if (progress_callback) {
  2852. if (!progress_callback((float) size_done / size_data, progress_callback_user_data)) {
  2853. return false;
  2854. }
  2855. }
  2856. const auto & w = get_weights(ggml_get_name(cur));
  2857. size_t n_size = ggml_nbytes(cur);
  2858. if (use_mmap) {
  2859. const auto & mapping = mappings.at(w.idx);
  2860. ggml_backend_buffer_t buf_mmap = nullptr;
  2861. if (bufs_mmap.count(w.idx)) {
  2862. buf_mmap = bufs_mmap.at(w.idx);
  2863. }
  2864. GGML_ASSERT(buf_mmap || cur->data); // either we have a buffer to allocate the tensor in, or it is already allocated
  2865. if (buf_mmap && cur->data == nullptr) {
  2866. ggml_backend_tensor_alloc(buf_mmap, cur, (uint8_t *) mapping->addr + w.offs);
  2867. if (lmlocks) {
  2868. const auto & lmlock = lmlocks->at(w.idx);
  2869. lmlock->grow_to(w.offs + ggml_nbytes(cur));
  2870. }
  2871. auto & mmap_used = mmaps_used[w.idx];
  2872. mmap_used.first = std::min(mmap_used.first, w.offs);
  2873. mmap_used.second = std::max(mmap_used.second, w.offs + n_size);
  2874. } else {
  2875. ggml_backend_tensor_set(cur, (uint8_t *) mapping->addr + w.offs, 0, n_size);
  2876. }
  2877. } else {
  2878. GGML_ASSERT(w.idx < files.size());
  2879. const auto & file = files.at(w.idx);
  2880. if (ggml_backend_buffer_is_host(cur->buffer)) {
  2881. file->seek(w.offs, SEEK_SET);
  2882. file->read_raw(cur->data, ggml_nbytes(cur));
  2883. } else {
  2884. read_buf.resize(ggml_nbytes(cur));
  2885. file->seek(w.offs, SEEK_SET);
  2886. file->read_raw(read_buf.data(), ggml_nbytes(cur));
  2887. ggml_backend_tensor_set(cur, read_buf.data(), 0, n_size);
  2888. }
  2889. }
  2890. size_done += n_size;
  2891. }
  2892. // check if this is the last call and do final cleanup
  2893. if (size_done >= size_data) {
  2894. // unmap offloaded tensors and metadata
  2895. if (use_mmap) {
  2896. for (uint32_t idx = 0; idx < mappings.size(); idx++) {
  2897. const auto & mmap_used = mmaps_used.at(idx);
  2898. auto & mapping = mappings.at(idx);
  2899. mapping->unmap_fragment(0, mmap_used.first);
  2900. if (mmap_used.second != 0) {
  2901. mapping->unmap_fragment(mmap_used.second, mapping->size);
  2902. }
  2903. }
  2904. }
  2905. if (progress_callback) {
  2906. // Even though the model is done loading, we still honor
  2907. // cancellation since we need to free allocations.
  2908. return progress_callback(1.0f, progress_callback_user_data);
  2909. }
  2910. }
  2911. return true;
  2912. }
  2913. };
  2914. template<>
  2915. bool llama_model_loader::get_key(const enum llm_kv kid, enum llama_pooling_type & result, const bool required) {
  2916. uint32_t tmp;
  2917. const bool found = get_key(kid, tmp, required);
  2918. if (found) {
  2919. result = (enum llama_pooling_type) tmp;
  2920. } else {
  2921. result = LLAMA_POOLING_TYPE_UNSPECIFIED;
  2922. }
  2923. return found;
  2924. }
  2925. //
  2926. // load LLaMA models
  2927. //
  2928. static const char * llama_model_arch_name(llm_arch arch) {
  2929. auto it = LLM_ARCH_NAMES.find(arch);
  2930. if (it == LLM_ARCH_NAMES.end()) {
  2931. return "unknown";
  2932. }
  2933. return it->second;
  2934. }
  2935. static std::string llama_model_ftype_name(llama_ftype ftype) {
  2936. if (ftype & LLAMA_FTYPE_GUESSED) {
  2937. return llama_model_ftype_name((enum llama_ftype) (ftype & ~LLAMA_FTYPE_GUESSED)) + " (guessed)";
  2938. }
  2939. switch (ftype) {
  2940. case LLAMA_FTYPE_ALL_F32: return "all F32";
  2941. case LLAMA_FTYPE_MOSTLY_F16: return "F16";
  2942. case LLAMA_FTYPE_MOSTLY_Q4_0: return "Q4_0";
  2943. case LLAMA_FTYPE_MOSTLY_Q4_1: return "Q4_1";
  2944. case LLAMA_FTYPE_MOSTLY_Q4_1_SOME_F16:
  2945. return "Q4_1, some F16";
  2946. case LLAMA_FTYPE_MOSTLY_Q5_0: return "Q5_0";
  2947. case LLAMA_FTYPE_MOSTLY_Q5_1: return "Q5_1";
  2948. case LLAMA_FTYPE_MOSTLY_Q8_0: return "Q8_0";
  2949. // K-quants
  2950. case LLAMA_FTYPE_MOSTLY_Q2_K: return "Q2_K - Medium";
  2951. case LLAMA_FTYPE_MOSTLY_Q2_K_S: return "Q2_K - Small";
  2952. case LLAMA_FTYPE_MOSTLY_Q3_K_S: return "Q3_K - Small";
  2953. case LLAMA_FTYPE_MOSTLY_Q3_K_M: return "Q3_K - Medium";
  2954. case LLAMA_FTYPE_MOSTLY_Q3_K_L: return "Q3_K - Large";
  2955. case LLAMA_FTYPE_MOSTLY_Q4_K_S: return "Q4_K - Small";
  2956. case LLAMA_FTYPE_MOSTLY_Q4_K_M: return "Q4_K - Medium";
  2957. case LLAMA_FTYPE_MOSTLY_Q5_K_S: return "Q5_K - Small";
  2958. case LLAMA_FTYPE_MOSTLY_Q5_K_M: return "Q5_K - Medium";
  2959. case LLAMA_FTYPE_MOSTLY_Q6_K: return "Q6_K";
  2960. case LLAMA_FTYPE_MOSTLY_IQ2_XXS:return "IQ2_XXS - 2.0625 bpw";
  2961. case LLAMA_FTYPE_MOSTLY_IQ2_XS: return "IQ2_XS - 2.3125 bpw";
  2962. case LLAMA_FTYPE_MOSTLY_IQ2_S: return "IQ2_S - 2.5 bpw";
  2963. case LLAMA_FTYPE_MOSTLY_IQ2_M: return "IQ2_M - 2.7 bpw";
  2964. case LLAMA_FTYPE_MOSTLY_IQ3_XS: return "IQ3_XS - 3.3 bpw";
  2965. case LLAMA_FTYPE_MOSTLY_IQ3_XXS:return "IQ3_XXS - 3.0625 bpw";
  2966. case LLAMA_FTYPE_MOSTLY_IQ1_S :return "IQ1_S - 1.5625 bpw";
  2967. case LLAMA_FTYPE_MOSTLY_IQ1_M :return "IQ1_M - 1.75 bpw";
  2968. case LLAMA_FTYPE_MOSTLY_IQ4_NL: return "IQ4_NL - 4.5 bpw";
  2969. case LLAMA_FTYPE_MOSTLY_IQ4_XS: return "IQ4_XS - 4.25 bpw";
  2970. case LLAMA_FTYPE_MOSTLY_IQ3_S: return "IQ3_S - 3.4375 bpw";
  2971. case LLAMA_FTYPE_MOSTLY_IQ3_M: return "IQ3_S mix - 3.66 bpw";
  2972. default: return "unknown, may not work";
  2973. }
  2974. }
  2975. static const char * llama_model_type_name(e_model type) {
  2976. switch (type) {
  2977. case MODEL_22M: return "22M";
  2978. case MODEL_33M: return "33M";
  2979. case MODEL_109M: return "109M";
  2980. case MODEL_137M: return "137M";
  2981. case MODEL_0_5B: return "0.5B";
  2982. case MODEL_1B: return "1B";
  2983. case MODEL_2B: return "2B";
  2984. case MODEL_3B: return "3B";
  2985. case MODEL_7B: return "7B";
  2986. case MODEL_8B: return "8B";
  2987. case MODEL_13B: return "13B";
  2988. case MODEL_14B: return "14B";
  2989. case MODEL_15B: return "15B";
  2990. case MODEL_20B: return "20B";
  2991. case MODEL_30B: return "30B";
  2992. case MODEL_34B: return "34B";
  2993. case MODEL_35B: return "35B";
  2994. case MODEL_40B: return "40B";
  2995. case MODEL_65B: return "65B";
  2996. case MODEL_70B: return "70B";
  2997. case MODEL_314B: return "314B";
  2998. case MODEL_SMALL: return "0.1B";
  2999. case MODEL_MEDIUM: return "0.4B";
  3000. case MODEL_LARGE: return "0.8B";
  3001. case MODEL_XL: return "1.5B";
  3002. default: return "?B";
  3003. }
  3004. }
  3005. static const char * llama_model_vocab_type_name(enum llama_vocab_type type){
  3006. switch (type) {
  3007. case LLAMA_VOCAB_TYPE_NONE: return "no vocab";
  3008. case LLAMA_VOCAB_TYPE_SPM: return "SPM";
  3009. case LLAMA_VOCAB_TYPE_BPE: return "BPE";
  3010. case LLAMA_VOCAB_TYPE_WPM: return "WPM";
  3011. default: return "unknown";
  3012. }
  3013. }
  3014. static void llm_load_arch(llama_model_loader & ml, llama_model & model) {
  3015. model.arch = ml.get_arch();
  3016. if (model.arch == LLM_ARCH_UNKNOWN) {
  3017. throw std::runtime_error("unknown model architecture: '" + ml.get_arch_name() + "'");
  3018. }
  3019. }
  3020. static void llm_load_hparams(
  3021. llama_model_loader & ml,
  3022. llama_model & model) {
  3023. auto & hparams = model.hparams;
  3024. const gguf_context * ctx = ml.meta;
  3025. // get metadata as string
  3026. for (int i = 0; i < gguf_get_n_kv(ctx); i++) {
  3027. enum gguf_type type = gguf_get_kv_type(ctx, i);
  3028. if (type == GGUF_TYPE_ARRAY) {
  3029. continue;
  3030. }
  3031. const char * name = gguf_get_key(ctx, i);
  3032. const std::string value = gguf_kv_to_str(ctx, i);
  3033. model.gguf_kv.emplace(name, value);
  3034. }
  3035. // get general kv
  3036. ml.get_key(LLM_KV_GENERAL_NAME, model.name, false);
  3037. // get hparams kv
  3038. ml.get_key(LLM_KV_VOCAB_SIZE, hparams.n_vocab, false) || ml.get_arr_n(LLM_KV_TOKENIZER_LIST, hparams.n_vocab);
  3039. ml.get_key(LLM_KV_CONTEXT_LENGTH, hparams.n_ctx_train);
  3040. ml.get_key(LLM_KV_EMBEDDING_LENGTH, hparams.n_embd);
  3041. ml.get_key(LLM_KV_FEED_FORWARD_LENGTH, hparams.n_ff);
  3042. ml.get_key(LLM_KV_ATTENTION_HEAD_COUNT, hparams.n_head);
  3043. ml.get_key(LLM_KV_BLOCK_COUNT, hparams.n_layer);
  3044. ml.get_key(LLM_KV_EXPERT_COUNT, hparams.n_expert, false);
  3045. ml.get_key(LLM_KV_EXPERT_USED_COUNT, hparams.n_expert_used, false);
  3046. GGML_ASSERT(hparams.n_expert <= LLAMA_MAX_EXPERTS);
  3047. GGML_ASSERT(hparams.n_expert_used <= hparams.n_expert);
  3048. if (hparams.n_expert > 0) {
  3049. GGML_ASSERT(hparams.n_expert_used > 0);
  3050. } else {
  3051. GGML_ASSERT(hparams.n_expert_used == 0);
  3052. }
  3053. // n_head_kv is optional, default to n_head
  3054. hparams.n_head_kv = hparams.n_head;
  3055. ml.get_key(LLM_KV_ATTENTION_HEAD_COUNT_KV, hparams.n_head_kv, false);
  3056. bool rope_finetuned = false;
  3057. ml.get_key(LLM_KV_ROPE_SCALING_FINETUNED, rope_finetuned, false);
  3058. hparams.rope_finetuned = rope_finetuned;
  3059. hparams.n_yarn_orig_ctx = hparams.n_ctx_train;
  3060. ml.get_key(LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, hparams.n_yarn_orig_ctx, false);
  3061. // rope_freq_base (optional)
  3062. hparams.rope_freq_base_train = 10000.0f;
  3063. ml.get_key(LLM_KV_ROPE_FREQ_BASE, hparams.rope_freq_base_train, false);
  3064. std::string rope_scaling("linear");
  3065. ml.get_key(LLM_KV_ROPE_SCALING_TYPE, rope_scaling, false);
  3066. hparams.rope_scaling_type_train = llama_rope_scaling_type_from_string(rope_scaling);
  3067. GGML_ASSERT(hparams.rope_scaling_type_train != LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED);
  3068. // rope_freq_scale (inverse of the kv) is optional
  3069. float ropescale = 0.0f;
  3070. if (!ml.get_key(LLM_KV_ROPE_SCALING_FACTOR, ropescale, false)) {
  3071. // try the old key name
  3072. ml.get_key(LLM_KV_ROPE_SCALE_LINEAR, ropescale, false);
  3073. }
  3074. hparams.rope_freq_scale_train = ropescale == 0.0f ? 1.0f : 1.0f/ropescale;
  3075. // sanity check for n_rot (optional)
  3076. {
  3077. hparams.n_rot = (hparams.n_head == 0) ? 0 : hparams.n_embd / hparams.n_head;
  3078. ml.get_key(LLM_KV_ROPE_DIMENSION_COUNT, hparams.n_rot, false);
  3079. if (model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON) {
  3080. if (hparams.n_rot != hparams.n_embd / hparams.n_head) {
  3081. throw std::runtime_error(format("invalid n_rot: %u, expected %u", hparams.n_rot, hparams.n_embd / hparams.n_head));
  3082. }
  3083. }
  3084. // gpt-neox n_rot = rotary_pct * (n_embd / n_head)
  3085. // gpt-j n_rot = rotary_dim
  3086. }
  3087. hparams.n_embd_head_k = (hparams.n_head == 0) ? 0 : hparams.n_embd / hparams.n_head;
  3088. ml.get_key(LLM_KV_ATTENTION_KEY_LENGTH, hparams.n_embd_head_k, false);
  3089. hparams.n_embd_head_v = (hparams.n_head == 0) ? 0 : hparams.n_embd / hparams.n_head;
  3090. ml.get_key(LLM_KV_ATTENTION_VALUE_LENGTH, hparams.n_embd_head_v, false);
  3091. // arch-specific KVs
  3092. switch (model.arch) {
  3093. case LLM_ARCH_LLAMA:
  3094. {
  3095. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3096. switch (hparams.n_layer) {
  3097. case 22: model.type = e_model::MODEL_1B; break;
  3098. case 26: model.type = e_model::MODEL_3B; break;
  3099. case 32: model.type = e_model::MODEL_7B; break;
  3100. case 40: model.type = e_model::MODEL_13B; break;
  3101. case 48: model.type = e_model::MODEL_34B; break;
  3102. case 60: model.type = e_model::MODEL_30B; break;
  3103. case 80: model.type = hparams.n_head == hparams.n_head_kv ? e_model::MODEL_65B : e_model::MODEL_70B; break;
  3104. default: model.type = e_model::MODEL_UNKNOWN;
  3105. }
  3106. } break;
  3107. case LLM_ARCH_MINICPM:
  3108. {
  3109. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3110. switch (hparams.n_layer) {
  3111. case 40: model.type = e_model::MODEL_2B; break;
  3112. default: model.type = e_model::MODEL_UNKNOWN;
  3113. }
  3114. } break;
  3115. case LLM_ARCH_GROK:
  3116. {
  3117. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3118. switch (hparams.n_layer) {
  3119. case 64: model.type = e_model::MODEL_314B; break;
  3120. default: model.type = e_model::MODEL_UNKNOWN;
  3121. }
  3122. } break;
  3123. case LLM_ARCH_FALCON:
  3124. {
  3125. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3126. switch (hparams.n_layer) {
  3127. case 32: model.type = e_model::MODEL_7B; break;
  3128. case 60: model.type = e_model::MODEL_40B; break;
  3129. default: model.type = e_model::MODEL_UNKNOWN;
  3130. }
  3131. } break;
  3132. case LLM_ARCH_BAICHUAN:
  3133. {
  3134. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3135. switch (hparams.n_layer) {
  3136. case 32: model.type = e_model::MODEL_7B; break;
  3137. case 40: model.type = e_model::MODEL_13B; break;
  3138. default: model.type = e_model::MODEL_UNKNOWN;
  3139. }
  3140. if (model.type == e_model::MODEL_13B) {
  3141. // TODO: become GGUF KV parameter
  3142. hparams.f_max_alibi_bias = 8.0f;
  3143. }
  3144. } break;
  3145. case LLM_ARCH_STARCODER:
  3146. {
  3147. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3148. switch (hparams.n_layer) {
  3149. case 24: model.type = e_model::MODEL_1B; break;
  3150. case 36: model.type = e_model::MODEL_3B; break;
  3151. case 42: model.type = e_model::MODEL_7B; break;
  3152. case 40: model.type = e_model::MODEL_15B; break;
  3153. default: model.type = e_model::MODEL_UNKNOWN;
  3154. }
  3155. } break;
  3156. case LLM_ARCH_PERSIMMON:
  3157. {
  3158. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3159. switch (hparams.n_layer) {
  3160. case 36: model.type = e_model::MODEL_8B; break;
  3161. default: model.type = e_model::MODEL_UNKNOWN;
  3162. }
  3163. } break;
  3164. case LLM_ARCH_REFACT:
  3165. {
  3166. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3167. switch (hparams.n_layer) {
  3168. case 32: model.type = e_model::MODEL_1B; break;
  3169. default: model.type = e_model::MODEL_UNKNOWN;
  3170. }
  3171. // TODO: become GGUF KV parameter
  3172. hparams.f_max_alibi_bias = 8.0f;
  3173. } break;
  3174. case LLM_ARCH_BERT:
  3175. {
  3176. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3177. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  3178. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  3179. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type, false);
  3180. switch (hparams.n_layer) {
  3181. case 3:
  3182. model.type = e_model::MODEL_17M; break; // bge-micro
  3183. case 6:
  3184. model.type = e_model::MODEL_22M; break; // MiniLM-L6
  3185. case 12:
  3186. switch (hparams.n_embd) {
  3187. case 384: model.type = e_model::MODEL_33M; break; // MiniLM-L12, bge-small
  3188. case 768: model.type = e_model::MODEL_109M; break; // bge-base
  3189. } break;
  3190. case 24:
  3191. model.type = e_model::MODEL_335M; break; // bge-large
  3192. }
  3193. } break;
  3194. case LLM_ARCH_NOMIC_BERT:
  3195. {
  3196. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3197. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  3198. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  3199. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type);
  3200. if (hparams.n_layer == 12 && hparams.n_embd == 768) {
  3201. model.type = e_model::MODEL_137M;
  3202. }
  3203. } break;
  3204. case LLM_ARCH_BLOOM:
  3205. {
  3206. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3207. switch (hparams.n_layer) {
  3208. case 24: model.type = e_model::MODEL_1B; break;
  3209. case 30:
  3210. switch (hparams.n_embd) {
  3211. case 2560: model.type = e_model::MODEL_3B; break;
  3212. case 4096: model.type = e_model::MODEL_7B; break;
  3213. } break;
  3214. }
  3215. // TODO: become GGUF KV parameter
  3216. hparams.f_max_alibi_bias = 8.0f;
  3217. } break;
  3218. case LLM_ARCH_MPT:
  3219. {
  3220. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3221. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv, false);
  3222. ml.get_key(LLM_KV_ATTENTION_MAX_ALIBI_BIAS, hparams.f_max_alibi_bias);
  3223. switch (hparams.n_layer) {
  3224. case 32: model.type = e_model::MODEL_7B; break;
  3225. case 48: model.type = e_model::MODEL_30B; break;
  3226. default: model.type = e_model::MODEL_UNKNOWN;
  3227. }
  3228. } break;
  3229. case LLM_ARCH_STABLELM:
  3230. {
  3231. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3232. switch (hparams.n_layer) {
  3233. case 24: model.type = e_model::MODEL_1B; break;
  3234. case 32: model.type = e_model::MODEL_3B; break;
  3235. default: model.type = e_model::MODEL_UNKNOWN;
  3236. }
  3237. } break;
  3238. case LLM_ARCH_QWEN:
  3239. {
  3240. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3241. switch (hparams.n_layer) {
  3242. case 32: model.type = e_model::MODEL_7B; break;
  3243. case 40: model.type = e_model::MODEL_13B; break;
  3244. default: model.type = e_model::MODEL_UNKNOWN;
  3245. }
  3246. } break;
  3247. case LLM_ARCH_QWEN2:
  3248. {
  3249. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3250. switch (hparams.n_layer) {
  3251. case 24: model.type = hparams.n_embd == 1024 ? e_model::MODEL_0_5B : e_model::MODEL_1B; break;
  3252. case 32: model.type = e_model::MODEL_7B; break;
  3253. case 40: model.type = hparams.n_head == 20 ? e_model::MODEL_4B : e_model::MODEL_13B; break;
  3254. case 80: model.type = e_model::MODEL_70B; break;
  3255. default: model.type = e_model::MODEL_UNKNOWN;
  3256. }
  3257. } break;
  3258. case LLM_ARCH_PHI2:
  3259. {
  3260. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3261. switch (hparams.n_layer) {
  3262. case 24: model.type = e_model::MODEL_1B; break;
  3263. case 32: model.type = e_model::MODEL_3B; break;
  3264. default: model.type = e_model::MODEL_UNKNOWN;
  3265. }
  3266. } break;
  3267. case LLM_ARCH_PLAMO:
  3268. {
  3269. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3270. switch (hparams.n_layer) {
  3271. case 40: model.type = e_model::MODEL_13B; break;
  3272. default: model.type = e_model::MODEL_UNKNOWN;
  3273. }
  3274. } break;
  3275. case LLM_ARCH_GPT2:
  3276. {
  3277. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3278. switch (hparams.n_layer) {
  3279. case 12: model.type = e_model::MODEL_SMALL; break;
  3280. case 24: model.type = e_model::MODEL_MEDIUM; break;
  3281. case 36: model.type = e_model::MODEL_LARGE; break;
  3282. case 48: model.type = e_model::MODEL_XL; break;
  3283. default: model.type = e_model::MODEL_UNKNOWN;
  3284. }
  3285. } break;
  3286. case LLM_ARCH_CODESHELL:
  3287. {
  3288. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3289. switch (hparams.n_layer) {
  3290. case 42: model.type = e_model::MODEL_SMALL; break;
  3291. default: model.type = e_model::MODEL_UNKNOWN;
  3292. }
  3293. } break;
  3294. case LLM_ARCH_ORION:
  3295. {
  3296. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3297. switch (hparams.n_layer) {
  3298. case 40: model.type = e_model::MODEL_14B; break;
  3299. default: model.type = e_model::MODEL_UNKNOWN;
  3300. }
  3301. } break;
  3302. case LLM_ARCH_INTERNLM2:
  3303. {
  3304. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3305. switch (hparams.n_layer) {
  3306. case 32: model.type = e_model::MODEL_7B; break;
  3307. case 48: model.type = e_model::MODEL_20B; break;
  3308. default: model.type = e_model::MODEL_UNKNOWN;
  3309. }
  3310. } break;
  3311. case LLM_ARCH_GEMMA:
  3312. {
  3313. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3314. switch (hparams.n_layer) {
  3315. case 18: model.type = e_model::MODEL_2B; break;
  3316. case 28: model.type = e_model::MODEL_7B; break;
  3317. default: model.type = e_model::MODEL_UNKNOWN;
  3318. }
  3319. } break;
  3320. case LLM_ARCH_STARCODER2:
  3321. {
  3322. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3323. switch (hparams.n_layer) {
  3324. case 30: model.type = e_model::MODEL_3B; break;
  3325. case 32: model.type = e_model::MODEL_7B; break;
  3326. case 40: model.type = e_model::MODEL_15B; break;
  3327. default: model.type = e_model::MODEL_UNKNOWN;
  3328. }
  3329. } break;
  3330. case LLM_ARCH_MAMBA:
  3331. {
  3332. ml.get_key(LLM_KV_SSM_CONV_KERNEL, hparams.ssm_d_conv);
  3333. ml.get_key(LLM_KV_SSM_INNER_SIZE, hparams.ssm_d_inner);
  3334. ml.get_key(LLM_KV_SSM_STATE_SIZE, hparams.ssm_d_state);
  3335. ml.get_key(LLM_KV_SSM_TIME_STEP_RANK, hparams.ssm_dt_rank);
  3336. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3337. switch (hparams.n_layer) {
  3338. case 24:
  3339. switch (hparams.n_embd) {
  3340. case 768: model.type = e_model::MODEL_SMALL; break;
  3341. default: model.type = e_model::MODEL_UNKNOWN;
  3342. } break;
  3343. case 48:
  3344. switch (hparams.n_embd) {
  3345. case 1024: model.type = e_model::MODEL_MEDIUM; break;
  3346. case 1536: model.type = e_model::MODEL_LARGE; break;
  3347. case 2048: model.type = e_model::MODEL_XL; break;
  3348. default: model.type = e_model::MODEL_UNKNOWN;
  3349. } break;
  3350. case 64:
  3351. switch (hparams.n_embd) {
  3352. case 2560: model.type = e_model::MODEL_3B; break;
  3353. default: model.type = e_model::MODEL_UNKNOWN;
  3354. } break;
  3355. default: model.type = e_model::MODEL_UNKNOWN;
  3356. }
  3357. } break;
  3358. case LLM_ARCH_COMMAND_R:
  3359. {
  3360. ml.get_key(LLM_KV_LOGIT_SCALE, hparams.f_logit_scale);
  3361. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3362. switch (hparams.n_layer) {
  3363. case 40: model.type = e_model::MODEL_35B; break;
  3364. default: model.type = e_model::MODEL_UNKNOWN;
  3365. }
  3366. } break;
  3367. default: (void)0;
  3368. }
  3369. model.ftype = ml.ftype;
  3370. if (hparams.f_max_alibi_bias > 0.0f) {
  3371. hparams.need_kq_pos = true;
  3372. }
  3373. hparams.rope_type = llama_rope_type(&model);
  3374. }
  3375. // TODO: This should probably be in llama.h
  3376. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special = false);
  3377. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch);
  3378. static void llm_load_vocab(
  3379. llama_model_loader & ml,
  3380. llama_model & model) {
  3381. auto & vocab = model.vocab;
  3382. struct gguf_context * ctx = ml.meta;
  3383. const auto kv = LLM_KV(model.arch);
  3384. // determine vocab type
  3385. {
  3386. std::string tokenizer_name;
  3387. ml.get_key(LLM_KV_TOKENIZER_MODEL, tokenizer_name);
  3388. if (tokenizer_name == "no_vocab") {
  3389. vocab.type = LLAMA_VOCAB_TYPE_NONE;
  3390. // default special tokens
  3391. vocab.special_bos_id = -1;
  3392. vocab.special_eos_id = -1;
  3393. vocab.special_unk_id = -1;
  3394. vocab.special_sep_id = -1;
  3395. vocab.special_pad_id = -1;
  3396. vocab.linefeed_id = -1;
  3397. return;
  3398. } else if (tokenizer_name == "llama") {
  3399. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  3400. // default special tokens
  3401. vocab.special_bos_id = 1;
  3402. vocab.special_eos_id = 2;
  3403. vocab.special_unk_id = 0;
  3404. vocab.special_sep_id = -1;
  3405. vocab.special_pad_id = -1;
  3406. const int add_space_prefix_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_ADD_PREFIX).c_str());
  3407. if (add_space_prefix_keyidx != -1) {
  3408. vocab.add_space_prefix = gguf_get_val_bool(ctx, add_space_prefix_keyidx);
  3409. } // The default value of add_space_prefix is true.
  3410. } else if (tokenizer_name == "gpt2") {
  3411. vocab.type = LLAMA_VOCAB_TYPE_BPE;
  3412. // read bpe merges and populate bpe ranks
  3413. const int merges_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_MERGES).c_str());
  3414. if (merges_keyidx == -1) {
  3415. throw std::runtime_error("cannot find tokenizer merges in model file\n");
  3416. }
  3417. const int n_merges = gguf_get_arr_n(ctx, merges_keyidx);
  3418. for (int i = 0; i < n_merges; i++) {
  3419. const std::string word = gguf_get_arr_str(ctx, merges_keyidx, i);
  3420. GGML_ASSERT(unicode_cpts_from_utf8(word).size() > 0);
  3421. std::string first;
  3422. std::string second;
  3423. const size_t pos = word.find(' ', 1);
  3424. if (pos != std::string::npos) {
  3425. first = word.substr(0, pos);
  3426. second = word.substr(pos + 1);
  3427. }
  3428. vocab.bpe_ranks.emplace(std::make_pair(first, second), i);
  3429. }
  3430. // default special tokens
  3431. vocab.special_bos_id = 11;
  3432. vocab.special_eos_id = 11;
  3433. vocab.special_unk_id = -1;
  3434. vocab.special_sep_id = -1;
  3435. vocab.special_pad_id = -1;
  3436. } else if (tokenizer_name == "bert") {
  3437. vocab.type = LLAMA_VOCAB_TYPE_WPM;
  3438. // default special tokens
  3439. vocab.special_bos_id = 101;
  3440. vocab.special_eos_id = 102;
  3441. vocab.special_unk_id = 100;
  3442. vocab.special_sep_id = -1;
  3443. vocab.special_pad_id = -1;
  3444. vocab.add_space_prefix = false;
  3445. } else {
  3446. LLAMA_LOG_WARN("%s: unknown tokenizer: '%s'", __func__, tokenizer_name.c_str());
  3447. LLAMA_LOG_WARN("%s: using default tokenizer: 'llama'", __func__);
  3448. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  3449. }
  3450. }
  3451. const int token_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_LIST).c_str());
  3452. if (token_idx == -1) {
  3453. throw std::runtime_error("cannot find tokenizer vocab in model file\n");
  3454. }
  3455. const float * scores = nullptr;
  3456. const int score_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_SCORES).c_str());
  3457. if (score_idx != -1) {
  3458. scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
  3459. }
  3460. const int * toktypes = nullptr;
  3461. const int toktype_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE).c_str());
  3462. if (toktype_idx != -1) {
  3463. toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
  3464. }
  3465. const uint32_t n_vocab = gguf_get_arr_n(ctx, token_idx);
  3466. vocab.id_to_token.resize(n_vocab);
  3467. for (uint32_t i = 0; i < n_vocab; i++) {
  3468. std::string word = gguf_get_arr_str(ctx, token_idx, i);
  3469. GGML_ASSERT(unicode_cpts_from_utf8(word).size() > 0);
  3470. vocab.token_to_id[word] = i;
  3471. auto & token_data = vocab.id_to_token[i];
  3472. token_data.text = std::move(word);
  3473. token_data.score = scores ? scores[i] : 0.0f;
  3474. token_data.type = toktypes ? (llama_token_type) toktypes[i] : LLAMA_TOKEN_TYPE_NORMAL;
  3475. }
  3476. GGML_ASSERT(vocab.id_to_token.size() == vocab.token_to_id.size());
  3477. // determine the newline token: LLaMA "<0x0A>" == 10 == '\n', Falcon 193 == '\n'
  3478. if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  3479. try {
  3480. vocab.linefeed_id = llama_byte_to_token(vocab, '\n');
  3481. } catch (const std::exception & e) {
  3482. LLAMA_LOG_WARN("%s: SPM vocabulary, but newline token not found: %s! Using special_pad_id instead.", __func__, e.what());
  3483. vocab.linefeed_id = vocab.special_pad_id;
  3484. }
  3485. } else if (vocab.type == LLAMA_VOCAB_TYPE_WPM) {
  3486. vocab.linefeed_id = vocab.special_pad_id;
  3487. } else {
  3488. const std::vector<int> ids = llama_tokenize_internal(vocab, "\xC4\x8A", false); // U+010A
  3489. GGML_ASSERT(!ids.empty() && "model vocab missing newline token");
  3490. vocab.linefeed_id = ids[0];
  3491. }
  3492. // special tokens
  3493. {
  3494. const std::vector<std::pair<enum llm_kv, int32_t &>> special_token_types = {
  3495. { LLM_KV_TOKENIZER_BOS_ID, vocab.special_bos_id },
  3496. { LLM_KV_TOKENIZER_EOS_ID, vocab.special_eos_id },
  3497. { LLM_KV_TOKENIZER_UNK_ID, vocab.special_unk_id },
  3498. { LLM_KV_TOKENIZER_SEP_ID, vocab.special_sep_id },
  3499. { LLM_KV_TOKENIZER_PAD_ID, vocab.special_pad_id },
  3500. };
  3501. for (const auto & it : special_token_types) {
  3502. const std::string & key = kv(std::get<0>(it));
  3503. int32_t & id = std::get<1>(it);
  3504. uint32_t new_id;
  3505. if (!ml.get_key(std::get<0>(it), new_id, false)) {
  3506. continue;
  3507. }
  3508. if (new_id >= vocab.id_to_token.size()) {
  3509. LLAMA_LOG_WARN("%s: bad special token: '%s' = %ud, using default id %d\n",
  3510. __func__, key.c_str(), new_id, id);
  3511. } else {
  3512. id = new_id;
  3513. }
  3514. }
  3515. // Handle add_bos_token and add_eos_token
  3516. {
  3517. bool temp = true;
  3518. if (ml.get_key(LLM_KV_TOKENIZER_ADD_BOS, temp, false)) {
  3519. vocab.special_add_bos = int(temp);
  3520. }
  3521. if (ml.get_key(LLM_KV_TOKENIZER_ADD_EOS, temp, false)) {
  3522. vocab.special_add_eos = int(temp);
  3523. }
  3524. }
  3525. }
  3526. // build special tokens cache
  3527. {
  3528. // TODO: It is unclear (to me) at this point, whether special tokes are guaranteed to be of a deterministic type,
  3529. // and will always be correctly labeled in 'added_tokens.json' etc.
  3530. // The assumption is, since special tokens aren't meant to be exposed to end user, they are designed
  3531. // to be unmatchable by the tokenizer, therefore tokens from the vocab, which are unmatchable by the tokenizer
  3532. // are special tokens.
  3533. // From testing, this appears to correlate 1:1 with special tokens.
  3534. //
  3535. // Counting special tokens and verifying in only one direction
  3536. // is sufficient to detect difference in those two sets.
  3537. //
  3538. uint32_t special_tokens_count_by_type = 0;
  3539. uint32_t special_tokens_count_from_verification = 0;
  3540. bool special_tokens_definition_mismatch = false;
  3541. for (const auto & t : vocab.token_to_id) {
  3542. const auto & token = t.first;
  3543. const auto & id = t.second;
  3544. // Count all non-normal tokens in the vocab while iterating
  3545. if (vocab.id_to_token[id].type != LLAMA_TOKEN_TYPE_NORMAL) {
  3546. special_tokens_count_by_type++;
  3547. }
  3548. // Skip single character tokens
  3549. if (token.length() > 1) {
  3550. bool is_tokenizable = false;
  3551. // Split token string representation in two, in all possible ways
  3552. // and check if both halves can be matched to a valid token
  3553. for (unsigned i = 1; i < token.length();) {
  3554. const auto left = token.substr(0, i);
  3555. const auto right = token.substr(i);
  3556. // check if we didnt partition in the middle of a utf sequence
  3557. auto utf = utf8_len(left.at(left.length() - 1));
  3558. if (utf == 1) {
  3559. if (vocab.token_to_id.find(left) != vocab.token_to_id.end() &&
  3560. vocab.token_to_id.find(right) != vocab.token_to_id.end() ) {
  3561. is_tokenizable = true;
  3562. break;
  3563. }
  3564. i++;
  3565. } else {
  3566. // skip over the rest of multibyte utf sequence
  3567. i += utf - 1;
  3568. }
  3569. }
  3570. if (!is_tokenizable) {
  3571. // Some tokens are multibyte, but they are utf sequences with equivalent text length of 1
  3572. // it's faster to re-filter them here, since there are way less candidates now
  3573. // Calculate a total "utf" length of a token string representation
  3574. size_t utf8_str_len = 0;
  3575. for (unsigned i = 0; i < token.length();) {
  3576. utf8_str_len++;
  3577. i += utf8_len(token.at(i));
  3578. }
  3579. // And skip the ones which are one character
  3580. if (utf8_str_len > 1) {
  3581. // At this point what we have left are special tokens only
  3582. vocab.special_tokens_cache[token] = id;
  3583. // Count manually found special tokens
  3584. special_tokens_count_from_verification++;
  3585. // If this manually found special token is not marked as such, flag a mismatch
  3586. if (vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL) {
  3587. special_tokens_definition_mismatch = true;
  3588. }
  3589. }
  3590. }
  3591. }
  3592. }
  3593. if (special_tokens_definition_mismatch || special_tokens_count_from_verification != special_tokens_count_by_type) {
  3594. LLAMA_LOG_WARN("%s: mismatch in special tokens definition ( %u/%zu vs %u/%zu ).\n",
  3595. __func__,
  3596. special_tokens_count_from_verification, vocab.id_to_token.size(),
  3597. special_tokens_count_by_type, vocab.id_to_token.size()
  3598. );
  3599. } else {
  3600. LLAMA_LOG_INFO("%s: special tokens definition check successful ( %u/%zu ).\n",
  3601. __func__,
  3602. special_tokens_count_from_verification, vocab.id_to_token.size()
  3603. );
  3604. }
  3605. }
  3606. }
  3607. static void llm_load_print_meta(llama_model_loader & ml, llama_model & model) {
  3608. const auto & hparams = model.hparams;
  3609. const auto & vocab = model.vocab;
  3610. const char * rope_scaling_type = LLAMA_ROPE_SCALING_TYPES.at(hparams.rope_scaling_type_train);
  3611. // hparams
  3612. LLAMA_LOG_INFO("%s: format = %s\n", __func__, llama_file_version_name(ml.fver));
  3613. LLAMA_LOG_INFO("%s: arch = %s\n", __func__, LLM_ARCH_NAMES.at(model.arch));
  3614. LLAMA_LOG_INFO("%s: vocab type = %s\n", __func__, llama_model_vocab_type_name(vocab.type));
  3615. LLAMA_LOG_INFO("%s: n_vocab = %u\n", __func__, hparams.n_vocab);
  3616. LLAMA_LOG_INFO("%s: n_merges = %u\n", __func__, (int) vocab.bpe_ranks.size());
  3617. LLAMA_LOG_INFO("%s: n_ctx_train = %u\n", __func__, hparams.n_ctx_train);
  3618. LLAMA_LOG_INFO("%s: n_embd = %u\n", __func__, hparams.n_embd);
  3619. LLAMA_LOG_INFO("%s: n_head = %u\n", __func__, hparams.n_head);
  3620. LLAMA_LOG_INFO("%s: n_head_kv = %u\n", __func__, hparams.n_head_kv);
  3621. LLAMA_LOG_INFO("%s: n_layer = %u\n", __func__, hparams.n_layer);
  3622. LLAMA_LOG_INFO("%s: n_rot = %u\n", __func__, hparams.n_rot);
  3623. LLAMA_LOG_INFO("%s: n_embd_head_k = %u\n", __func__, hparams.n_embd_head_k);
  3624. LLAMA_LOG_INFO("%s: n_embd_head_v = %u\n", __func__, hparams.n_embd_head_v);
  3625. LLAMA_LOG_INFO("%s: n_gqa = %u\n", __func__, hparams.n_gqa());
  3626. LLAMA_LOG_INFO("%s: n_embd_k_gqa = %u\n", __func__, hparams.n_embd_k_gqa());
  3627. LLAMA_LOG_INFO("%s: n_embd_v_gqa = %u\n", __func__, hparams.n_embd_v_gqa());
  3628. LLAMA_LOG_INFO("%s: f_norm_eps = %.1e\n", __func__, hparams.f_norm_eps);
  3629. LLAMA_LOG_INFO("%s: f_norm_rms_eps = %.1e\n", __func__, hparams.f_norm_rms_eps);
  3630. LLAMA_LOG_INFO("%s: f_clamp_kqv = %.1e\n", __func__, hparams.f_clamp_kqv);
  3631. LLAMA_LOG_INFO("%s: f_max_alibi_bias = %.1e\n", __func__, hparams.f_max_alibi_bias);
  3632. LLAMA_LOG_INFO("%s: f_logit_scale = %.1e\n", __func__, hparams.f_logit_scale);
  3633. LLAMA_LOG_INFO("%s: n_ff = %u\n", __func__, hparams.n_ff);
  3634. LLAMA_LOG_INFO("%s: n_expert = %u\n", __func__, hparams.n_expert);
  3635. LLAMA_LOG_INFO("%s: n_expert_used = %u\n", __func__, hparams.n_expert_used);
  3636. LLAMA_LOG_INFO("%s: causal attn = %d\n", __func__, hparams.causal_attn);
  3637. LLAMA_LOG_INFO("%s: pooling type = %d\n", __func__, hparams.pooling_type);
  3638. LLAMA_LOG_INFO("%s: rope type = %d\n", __func__, hparams.rope_type);
  3639. LLAMA_LOG_INFO("%s: rope scaling = %s\n", __func__, rope_scaling_type);
  3640. LLAMA_LOG_INFO("%s: freq_base_train = %.1f\n", __func__, hparams.rope_freq_base_train);
  3641. LLAMA_LOG_INFO("%s: freq_scale_train = %g\n", __func__, hparams.rope_freq_scale_train);
  3642. LLAMA_LOG_INFO("%s: n_yarn_orig_ctx = %u\n", __func__, hparams.n_yarn_orig_ctx);
  3643. LLAMA_LOG_INFO("%s: rope_finetuned = %s\n", __func__, hparams.rope_finetuned ? "yes" : "unknown");
  3644. LLAMA_LOG_INFO("%s: ssm_d_conv = %u\n", __func__, hparams.ssm_d_conv);
  3645. LLAMA_LOG_INFO("%s: ssm_d_inner = %u\n", __func__, hparams.ssm_d_inner);
  3646. LLAMA_LOG_INFO("%s: ssm_d_state = %u\n", __func__, hparams.ssm_d_state);
  3647. LLAMA_LOG_INFO("%s: ssm_dt_rank = %u\n", __func__, hparams.ssm_dt_rank);
  3648. LLAMA_LOG_INFO("%s: model type = %s\n", __func__, llama_model_type_name(model.type));
  3649. LLAMA_LOG_INFO("%s: model ftype = %s\n", __func__, llama_model_ftype_name(model.ftype).c_str());
  3650. if (ml.n_elements >= 1e12) {
  3651. LLAMA_LOG_INFO("%s: model params = %.2f T\n", __func__, ml.n_elements*1e-12);
  3652. } else if (ml.n_elements >= 1e9) {
  3653. LLAMA_LOG_INFO("%s: model params = %.2f B\n", __func__, ml.n_elements*1e-9);
  3654. } else if (ml.n_elements >= 1e6) {
  3655. LLAMA_LOG_INFO("%s: model params = %.2f M\n", __func__, ml.n_elements*1e-6);
  3656. } else {
  3657. LLAMA_LOG_INFO("%s: model params = %.2f K\n", __func__, ml.n_elements*1e-3);
  3658. }
  3659. if (ml.n_bytes < GiB) {
  3660. 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);
  3661. } else {
  3662. 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);
  3663. }
  3664. // general kv
  3665. LLAMA_LOG_INFO("%s: general.name = %s\n", __func__, model.name.c_str());
  3666. // special tokens
  3667. 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() ); }
  3668. 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() ); }
  3669. 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() ); }
  3670. 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() ); }
  3671. 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() ); }
  3672. 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() ); }
  3673. }
  3674. // Returns false if cancelled by progress_callback
  3675. static bool llm_load_tensors(
  3676. llama_model_loader & ml,
  3677. llama_model & model,
  3678. int n_gpu_layers,
  3679. enum llama_split_mode split_mode,
  3680. int main_gpu,
  3681. const float * tensor_split,
  3682. bool use_mlock,
  3683. llama_progress_callback progress_callback,
  3684. void * progress_callback_user_data) {
  3685. model.t_start_us = ggml_time_us();
  3686. auto & hparams = model.hparams;
  3687. model.split_mode = split_mode;
  3688. model.main_gpu = main_gpu;
  3689. model.n_gpu_layers = n_gpu_layers;
  3690. const int64_t n_layer = hparams.n_layer;
  3691. const int64_t i_gpu_start = std::max((int64_t) hparams.n_layer - n_gpu_layers, (int64_t) 0);
  3692. // there is very little benefit to offloading the input layer, so always keep it on the CPU
  3693. model.buft_input = llama_default_buffer_type_cpu(true);
  3694. //model.buft_input = llama_default_buffer_type_offload(main_gpu);
  3695. model.buft_layer.resize(n_layer);
  3696. // assign cpu layers
  3697. for (int64_t i = 0; i < i_gpu_start; ++i) {
  3698. model.buft_layer[i] = llama_default_buffer_type_cpu(true);
  3699. }
  3700. if (split_mode == LLAMA_SPLIT_MODE_LAYER) {
  3701. // calculate the split points
  3702. int device_count = llama_get_device_count();
  3703. bool all_zero = tensor_split == nullptr || std::all_of(tensor_split, tensor_split + device_count, [](float x) { return x == 0.0f; });
  3704. std::vector<float> splits(device_count);
  3705. if (all_zero) {
  3706. // default split, by free memory
  3707. for (int i = 0; i < device_count; ++i) {
  3708. splits[i] = llama_get_device_memory(i);
  3709. }
  3710. } else {
  3711. std::copy(tensor_split, tensor_split + device_count, splits.begin());
  3712. }
  3713. // sum and normalize the splits to get the split points
  3714. float split_sum = 0.0f;
  3715. for (int i = 0; i < device_count; ++i) {
  3716. split_sum += splits[i];
  3717. splits[i] = split_sum;
  3718. }
  3719. for (int i = 0; i < device_count; ++i) {
  3720. splits[i] /= split_sum;
  3721. }
  3722. // assign the repeating layers to the devices according to the splits
  3723. int act_gpu_layers = std::min(n_gpu_layers, (int)n_layer + 1);
  3724. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  3725. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(i - i_gpu_start)/act_gpu_layers) - splits.begin();
  3726. model.buft_layer[i] = llama_default_buffer_type_offload(layer_gpu);
  3727. }
  3728. // assign the output layer
  3729. if (n_gpu_layers > n_layer) {
  3730. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(act_gpu_layers - 1)/act_gpu_layers) - splits.begin();
  3731. model.buft_output = llama_default_buffer_type_offload(layer_gpu);
  3732. } else {
  3733. model.buft_output = llama_default_buffer_type_cpu(true);
  3734. }
  3735. } else {
  3736. ggml_backend_buffer_type_t split_buft;
  3737. if (split_mode == LLAMA_SPLIT_MODE_ROW) {
  3738. split_buft = llama_default_buffer_type_split(main_gpu, tensor_split);
  3739. } else {
  3740. // LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_LAYER in backends where it is not supported
  3741. split_buft = llama_default_buffer_type_offload(main_gpu);
  3742. }
  3743. // assign the repeating layers
  3744. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  3745. model.buft_layer[i] = {
  3746. split_buft,
  3747. llama_default_buffer_type_offload(main_gpu)
  3748. };
  3749. }
  3750. // assign the output layer
  3751. if (n_gpu_layers > n_layer) {
  3752. model.buft_output = {
  3753. split_buft,
  3754. llama_default_buffer_type_offload(main_gpu)
  3755. };
  3756. } else {
  3757. model.buft_output = llama_default_buffer_type_cpu(true);
  3758. }
  3759. }
  3760. // count used buffer types
  3761. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  3762. buft_layer_count[model.buft_input.buft]++;
  3763. buft_layer_count[model.buft_input.buft_matrix]++;
  3764. buft_layer_count[model.buft_output.buft]++;
  3765. buft_layer_count[model.buft_output.buft_matrix]++;
  3766. for (int64_t i = 0; i < n_layer; ++i) {
  3767. buft_layer_count[model.buft_layer[i].buft]++;
  3768. buft_layer_count[model.buft_layer[i].buft_matrix]++;
  3769. }
  3770. // create one context per buffer type
  3771. size_t ctx_size = ggml_tensor_overhead()*(ml.n_tensors + 1); // +1 for models where tok_embd is duplicated as output
  3772. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  3773. for (auto & it : buft_layer_count) {
  3774. struct ggml_init_params params = {
  3775. /*.mem_size =*/ ctx_size,
  3776. /*.mem_buffer =*/ NULL,
  3777. /*.no_alloc =*/ true,
  3778. };
  3779. ggml_context * ctx = ggml_init(params);
  3780. if (!ctx) {
  3781. throw std::runtime_error(format("failed to create context"));
  3782. }
  3783. ctx_map[it.first] = ctx;
  3784. model.ctxs.push_back(ctx);
  3785. }
  3786. LLAMA_LOG_INFO("%s: ggml ctx size = %7.2f MiB\n", __func__, model.ctxs.size()*ctx_size/1024.0/1024.0);
  3787. // create tensors for the weights
  3788. {
  3789. const int64_t n_embd = hparams.n_embd;
  3790. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3791. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  3792. const int64_t n_embd_gqa = n_embd_v_gqa;
  3793. const int64_t n_vocab = hparams.n_vocab;
  3794. const int64_t n_vocab_type = hparams.n_vocab_type;
  3795. const int64_t n_ff = hparams.n_ff;
  3796. GGML_ASSERT(n_embd_gqa == n_embd_k_gqa);
  3797. ggml_context * ctx_input = ctx_map.at(model.buft_input.buft);
  3798. ggml_context * ctx_output = ctx_map.at(model.buft_output.buft);
  3799. ggml_context * ctx_output_split = ctx_map.at(model.buft_output.buft_matrix);
  3800. auto ctx_for_layer = [&](int i) { return ctx_map.at(model.buft_layer[i].buft); };
  3801. auto ctx_for_layer_split = [&](int i) { return ctx_map.at(model.buft_layer[i].buft_matrix); };
  3802. model.layers.resize(n_layer);
  3803. const auto tn = LLM_TN(model.arch);
  3804. switch (model.arch) {
  3805. case LLM_ARCH_LLAMA:
  3806. case LLM_ARCH_REFACT:
  3807. case LLM_ARCH_MINICPM:
  3808. {
  3809. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3810. // output
  3811. {
  3812. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3813. if (model.arch != LLM_ARCH_MINICPM){
  3814. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  3815. // if output is NULL, init from the input tok embed
  3816. if (model.output == NULL) {
  3817. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3818. ml.n_created--; // artificial tensor
  3819. ml.size_data += ggml_nbytes(model.output);
  3820. }
  3821. }
  3822. }
  3823. for (int i = 0; i < n_layer; ++i) {
  3824. ggml_context * ctx_layer = ctx_for_layer(i);
  3825. ggml_context * ctx_split = ctx_for_layer_split(i);
  3826. auto & layer = model.layers[i];
  3827. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3828. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3829. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3830. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3831. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3832. // optional bias tensors
  3833. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, false);
  3834. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, false);
  3835. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, false);
  3836. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, false);
  3837. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3838. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd}, false);
  3839. if (layer.ffn_gate_inp == nullptr) {
  3840. GGML_ASSERT(hparams.n_expert == 0);
  3841. GGML_ASSERT(hparams.n_expert_used == 0);
  3842. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3843. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3844. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3845. } else {
  3846. GGML_ASSERT(hparams.n_expert > 0);
  3847. GGML_ASSERT(hparams.n_expert_used > 0);
  3848. // MoE branch
  3849. for (uint32_t x = 0; x < hparams.n_expert; ++x) {
  3850. layer.ffn_gate_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, x), {n_embd, n_ff});
  3851. layer.ffn_down_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, x), { n_ff, n_embd});
  3852. layer.ffn_up_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, x), {n_embd, n_ff});
  3853. }
  3854. }
  3855. }
  3856. } break;
  3857. case LLM_ARCH_GROK:
  3858. {
  3859. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3860. // output
  3861. {
  3862. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3863. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  3864. // if output is NULL, init from the input tok embed
  3865. if (model.output == NULL) {
  3866. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3867. ml.n_created--; // artificial tensor
  3868. ml.size_data += ggml_nbytes(model.output);
  3869. }
  3870. }
  3871. for (int i = 0; i < n_layer; ++i) {
  3872. ggml_context * ctx_layer = ctx_for_layer(i);
  3873. ggml_context * ctx_split = ctx_for_layer_split(i);
  3874. auto & layer = model.layers[i];
  3875. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3876. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3877. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3878. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3879. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3880. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  3881. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3882. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd});
  3883. GGML_ASSERT(hparams.n_expert > 0);
  3884. GGML_ASSERT(hparams.n_expert_used > 0);
  3885. // MoE branch
  3886. for (uint32_t x = 0; x < hparams.n_expert; ++x) {
  3887. layer.ffn_gate_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, x), {n_embd, n_ff});
  3888. layer.ffn_down_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, x), { n_ff, n_embd});
  3889. layer.ffn_up_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, x), {n_embd, n_ff});
  3890. }
  3891. layer.layer_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd});
  3892. }
  3893. } break;
  3894. case LLM_ARCH_BAICHUAN:
  3895. {
  3896. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3897. {
  3898. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3899. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3900. }
  3901. for (int i = 0; i < n_layer; ++i) {
  3902. ggml_context * ctx_layer = ctx_for_layer(i);
  3903. ggml_context * ctx_split = ctx_for_layer_split(i);
  3904. auto & layer = model.layers[i];
  3905. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3906. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3907. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3908. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3909. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3910. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3911. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3912. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3913. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3914. }
  3915. } break;
  3916. case LLM_ARCH_FALCON:
  3917. {
  3918. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3919. // output
  3920. {
  3921. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3922. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3923. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  3924. if (!model.output) {
  3925. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}); // needs to be on GPU
  3926. ml.n_created--; // artificial tensor
  3927. ml.size_data += ggml_nbytes(model.output);
  3928. }
  3929. }
  3930. for (int i = 0; i < n_layer; ++i) {
  3931. ggml_context * ctx_layer = ctx_for_layer(i);
  3932. ggml_context * ctx_split = ctx_for_layer_split(i);
  3933. auto & layer = model.layers[i];
  3934. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3935. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3936. layer.attn_norm_2 = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i), {n_embd}, false);
  3937. layer.attn_norm_2_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "bias", i), {n_embd}, false);
  3938. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3939. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3940. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3941. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3942. }
  3943. } break;
  3944. case LLM_ARCH_STARCODER:
  3945. {
  3946. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3947. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3948. // output
  3949. {
  3950. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3951. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3952. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3953. }
  3954. for (int i = 0; i < n_layer; ++i) {
  3955. ggml_context * ctx_layer = ctx_for_layer(i);
  3956. ggml_context * ctx_split = ctx_for_layer_split(i);
  3957. auto & layer = model.layers[i];
  3958. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3959. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3960. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3961. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3962. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3963. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3964. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3965. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3966. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3967. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3968. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3969. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3970. }
  3971. } break;
  3972. case LLM_ARCH_PERSIMMON:
  3973. {
  3974. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3975. {
  3976. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3977. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3978. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3979. }
  3980. for (int i = 0; i < n_layer; ++i) {
  3981. ggml_context * ctx_layer = ctx_for_layer(i);
  3982. ggml_context * ctx_split = ctx_for_layer_split(i);
  3983. auto & layer = model.layers[i];
  3984. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3985. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3986. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3987. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3988. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3989. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3990. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3991. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3992. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3993. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3994. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3995. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3996. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {64});
  3997. layer.attn_q_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "bias", i), {64});
  3998. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {64});
  3999. layer.attn_k_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "bias", i), {64});
  4000. }
  4001. } break;
  4002. case LLM_ARCH_BERT:
  4003. case LLM_ARCH_NOMIC_BERT:
  4004. {
  4005. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4006. model.type_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_TYPES, "weight"), {n_embd, n_vocab_type});
  4007. if (model.arch == LLM_ARCH_BERT) {
  4008. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  4009. }
  4010. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  4011. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  4012. for (int i = 0; i < n_layer; ++i) {
  4013. ggml_context * ctx_layer = ctx_for_layer(i);
  4014. ggml_context * ctx_split = ctx_for_layer_split(i);
  4015. auto & layer = model.layers[i];
  4016. if (model.arch == LLM_ARCH_BERT) {
  4017. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4018. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  4019. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4020. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  4021. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4022. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  4023. } else {
  4024. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4025. }
  4026. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4027. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  4028. layer.attn_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "bias", i), {n_embd});
  4029. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4030. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4031. if (model.arch == LLM_ARCH_BERT) {
  4032. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4033. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4034. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4035. } else {
  4036. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4037. }
  4038. layer.layer_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd});
  4039. layer.layer_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "bias", i), {n_embd});
  4040. }
  4041. } break;
  4042. case LLM_ARCH_BLOOM:
  4043. {
  4044. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4045. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  4046. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  4047. // output
  4048. {
  4049. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4050. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4051. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4052. }
  4053. for (int i = 0; i < n_layer; ++i) {
  4054. ggml_context * ctx_layer = ctx_for_layer(i);
  4055. ggml_context * ctx_split = ctx_for_layer_split(i);
  4056. auto & layer = model.layers[i];
  4057. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4058. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4059. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4060. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  4061. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4062. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4063. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4064. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4065. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4066. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4067. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4068. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4069. }
  4070. } break;
  4071. case LLM_ARCH_MPT:
  4072. {
  4073. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4074. // output
  4075. {
  4076. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4077. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, false);
  4078. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  4079. if (!model.output) {
  4080. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}); // needs to be on GPU
  4081. ml.n_created--; // artificial tensor
  4082. ml.size_data += ggml_nbytes(model.output);
  4083. }
  4084. }
  4085. for (int i = 0; i < n_layer; ++i) {
  4086. ggml_context * ctx_layer = ctx_for_layer(i);
  4087. ggml_context * ctx_split = ctx_for_layer_split(i);
  4088. auto & layer = model.layers[i];
  4089. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4090. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, false);
  4091. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4092. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, false);
  4093. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4094. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, false);
  4095. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4096. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, false);
  4097. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4098. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, false);
  4099. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4100. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, false);
  4101. // AWQ ScaleActivation layer
  4102. layer.ffn_act = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_ACT, "scales", i), {n_ff}, false);
  4103. }
  4104. } break;
  4105. case LLM_ARCH_STABLELM:
  4106. {
  4107. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4108. // output
  4109. {
  4110. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4111. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4112. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4113. }
  4114. for (int i = 0; i < n_layer; ++i) {
  4115. ggml_context * ctx_layer = ctx_for_layer(i);
  4116. ggml_context * ctx_split = ctx_for_layer_split(i);
  4117. auto & layer = model.layers[i];
  4118. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4119. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4120. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4121. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4122. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4123. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4124. // optional bias tensors, present in Stable LM 2 1.6B
  4125. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, false);
  4126. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, false);
  4127. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, false);
  4128. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4129. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4130. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4131. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4132. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4133. }
  4134. } break;
  4135. case LLM_ARCH_QWEN:
  4136. {
  4137. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4138. // output
  4139. {
  4140. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4141. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4142. }
  4143. for (int i = 0; i < n_layer; ++i) {
  4144. ggml_context * ctx_layer = ctx_for_layer(i);
  4145. ggml_context * ctx_split = ctx_for_layer_split(i);
  4146. auto & layer = model.layers[i];
  4147. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4148. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd*3});
  4149. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd*3});
  4150. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4151. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4152. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff/2});
  4153. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff/2, n_embd});
  4154. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff/2});
  4155. }
  4156. } break;
  4157. case LLM_ARCH_QWEN2:
  4158. {
  4159. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4160. // output
  4161. {
  4162. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4163. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4164. }
  4165. for (int i = 0; i < n_layer; ++i) {
  4166. ggml_context * ctx_layer = ctx_for_layer(i);
  4167. ggml_context * ctx_split = ctx_for_layer_split(i);
  4168. auto & layer = model.layers[i];
  4169. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4170. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4171. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4172. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4173. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4174. // optional bias tensors
  4175. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  4176. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  4177. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  4178. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4179. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4180. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4181. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4182. }
  4183. } break;
  4184. case LLM_ARCH_PHI2:
  4185. {
  4186. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4187. // output
  4188. {
  4189. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4190. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4191. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4192. model.output_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT, "bias"), {n_vocab});
  4193. }
  4194. for (int i = 0; i < n_layer; ++i) {
  4195. ggml_context * ctx_layer = ctx_for_layer(i);
  4196. ggml_context * ctx_split = ctx_for_layer_split(i);
  4197. auto & layer = model.layers[i];
  4198. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4199. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4200. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, false);
  4201. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, false);
  4202. if (layer.wqkv == nullptr) {
  4203. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4204. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  4205. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4206. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  4207. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4208. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  4209. }
  4210. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4211. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4212. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4213. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4214. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4215. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4216. }
  4217. } break;
  4218. case LLM_ARCH_PLAMO:
  4219. {
  4220. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4221. // output
  4222. {
  4223. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4224. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4225. }
  4226. for (int i = 0; i < n_layer; ++i) {
  4227. ggml_context * ctx_layer = ctx_for_layer(i);
  4228. ggml_context * ctx_split = ctx_for_layer_split(i);
  4229. auto & layer = model.layers[i];
  4230. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4231. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4232. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4233. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4234. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4235. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4236. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4237. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4238. }
  4239. } break;
  4240. case LLM_ARCH_GPT2:
  4241. {
  4242. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4243. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  4244. // output
  4245. {
  4246. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4247. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4248. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4249. }
  4250. for (int i = 0; i < n_layer; ++i) {
  4251. ggml_context * ctx_layer = ctx_for_layer(i);
  4252. ggml_context * ctx_split = ctx_for_layer_split(i);
  4253. auto & layer = model.layers[i];
  4254. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4255. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4256. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4257. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  4258. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4259. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4260. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4261. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4262. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4263. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4264. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4265. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4266. }
  4267. } break;
  4268. case LLM_ARCH_CODESHELL:
  4269. {
  4270. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4271. // output
  4272. {
  4273. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4274. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4275. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4276. }
  4277. for (int i = 0; i < n_layer; ++i) {
  4278. ggml_context * ctx_layer = ctx_for_layer(i);
  4279. ggml_context * ctx_split = ctx_for_layer_split(i);
  4280. auto & layer = model.layers[i];
  4281. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4282. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4283. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4284. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  4285. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4286. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4287. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4288. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4289. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4290. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4291. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4292. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4293. }
  4294. } break;
  4295. case LLM_ARCH_ORION:
  4296. {
  4297. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4298. {
  4299. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4300. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4301. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4302. }
  4303. for (int i = 0; i < n_layer; ++i) {
  4304. ggml_context * ctx_layer = ctx_for_layer(i);
  4305. ggml_context * ctx_split = ctx_for_layer_split(i);
  4306. auto & layer = model.layers[i];
  4307. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4308. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4309. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4310. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4311. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4312. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4313. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4314. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4315. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4316. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4317. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4318. }
  4319. } break;
  4320. case LLM_ARCH_INTERNLM2:
  4321. {
  4322. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4323. // output
  4324. {
  4325. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4326. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4327. }
  4328. for (int i = 0; i < n_layer; ++i) {
  4329. ggml_context * ctx_layer = ctx_for_layer(i);
  4330. ggml_context * ctx_split = ctx_for_layer_split(i);
  4331. auto & layer = model.layers[i];
  4332. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4333. // layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4334. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4335. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4336. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4337. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4338. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4339. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4340. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4341. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4342. }
  4343. } break;
  4344. case LLM_ARCH_GEMMA:
  4345. {
  4346. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4347. // output
  4348. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4349. 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
  4350. ml.n_created--; // artificial tensor
  4351. ml.size_data += ggml_nbytes(model.output);
  4352. const int64_t n_ff = hparams.n_ff;
  4353. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  4354. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  4355. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  4356. for (uint32_t i = 0; i < n_layer; ++i) {
  4357. ggml_context * ctx_layer = ctx_for_layer(i);
  4358. ggml_context * ctx_split = ctx_for_layer_split(i);
  4359. auto & layer = model.layers[i];
  4360. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4361. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * hparams.n_head});
  4362. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  4363. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  4364. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * hparams.n_head, n_embd});
  4365. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4366. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4367. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4368. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4369. }
  4370. } break;
  4371. case LLM_ARCH_STARCODER2:
  4372. {
  4373. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4374. // output
  4375. {
  4376. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4377. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4378. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  4379. // if output is NULL, init from the input tok embed
  4380. if (model.output == NULL) {
  4381. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4382. ml.n_created--; // artificial tensor
  4383. ml.size_data += ggml_nbytes(model.output);
  4384. }
  4385. }
  4386. for (int i = 0; i < n_layer; ++i) {
  4387. ggml_context * ctx_layer = ctx_for_layer(i);
  4388. ggml_context * ctx_split = ctx_for_layer_split(i);
  4389. auto & layer = model.layers[i];
  4390. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4391. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4392. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4393. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4394. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4395. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4396. // optional bias tensors
  4397. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  4398. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  4399. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  4400. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4401. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4402. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4403. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4404. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4405. // optional bias tensors
  4406. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4407. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP , "bias", i), { n_ff});
  4408. }
  4409. } break;
  4410. case LLM_ARCH_MAMBA:
  4411. {
  4412. const int64_t d_conv = hparams.ssm_d_conv;
  4413. const int64_t d_inner = hparams.ssm_d_inner;
  4414. const int64_t d_state = hparams.ssm_d_state;
  4415. const int64_t dt_rank = hparams.ssm_dt_rank;
  4416. // only an expansion factor of 2 is supported for now
  4417. GGML_ASSERT(2 * n_embd == d_inner);
  4418. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4419. // output
  4420. {
  4421. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4422. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  4423. // if output is NULL, init from the input tok embed, duplicated to allow offloading
  4424. if (model.output == NULL) {
  4425. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4426. ml.n_created--; // artificial tensor
  4427. ml.size_data += ggml_nbytes(model.output);
  4428. }
  4429. }
  4430. for (int i = 0; i < n_layer; ++i) {
  4431. ggml_context * ctx_layer = ctx_for_layer(i);
  4432. ggml_context * ctx_split = ctx_for_layer_split(i);
  4433. auto & layer = model.layers[i];
  4434. // norm
  4435. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4436. layer.ssm_in = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_IN, "weight", i), {n_embd, 2*d_inner});
  4437. layer.ssm_conv1d = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_CONV1D, "weight", i), {d_conv, d_inner});
  4438. layer.ssm_conv1d_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_CONV1D, "bias", i), {d_inner});
  4439. layer.ssm_x = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_X, "weight", i), {d_inner, dt_rank + 2*d_state});
  4440. layer.ssm_dt = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_DT, "weight", i), {dt_rank, d_inner});
  4441. layer.ssm_dt_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_DT, "bias", i), {d_inner});
  4442. // no "weight" suffix for these
  4443. layer.ssm_a = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_A, i), {d_state, d_inner});
  4444. layer.ssm_d = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_D, i), {d_inner});
  4445. // out_proj
  4446. layer.ssm_out = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_OUT, "weight", i), {d_inner, n_embd});
  4447. }
  4448. } break;
  4449. case LLM_ARCH_COMMAND_R:
  4450. {
  4451. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4452. // output
  4453. {
  4454. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4455. // init output from the input tok embed
  4456. model.output = ml.create_tensor(ctx_output, 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. for (int i = 0; i < n_layer; ++i) {
  4461. ggml_context * ctx_layer = ctx_for_layer(i);
  4462. ggml_context * ctx_split = ctx_for_layer_split(i);
  4463. auto & layer = model.layers[i];
  4464. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4465. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4466. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4467. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4468. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4469. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4470. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4471. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4472. }
  4473. } break;
  4474. default:
  4475. throw std::runtime_error("unknown architecture");
  4476. }
  4477. }
  4478. ml.done_getting_tensors();
  4479. ml.init_mappings(true, &model.mlock_mmaps);
  4480. model.mappings.reserve(ml.mappings.size());
  4481. // create the backend buffers
  4482. std::vector<std::pair<ggml_context *, llama_buf_map>> ctx_bufs;
  4483. ctx_bufs.reserve(ctx_map.size());
  4484. // Ensure we have enough capacity for the maximum backend buffer we will potentially create
  4485. size_t n_max_backend_buffer = ctx_map.size() * ml.files.size();
  4486. model.bufs.reserve(n_max_backend_buffer);
  4487. for (auto & it : ctx_map) {
  4488. ggml_backend_buffer_type_t buft = it.first;
  4489. ggml_context * ctx = it.second;
  4490. llama_buf_map bufs;
  4491. bufs.reserve(n_max_backend_buffer);
  4492. // only the mmap region containing the tensors in the model is mapped to the backend buffer
  4493. // 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
  4494. // this allows using partial offloading when the model size exceeds the metal buffer size, but not the RAM size
  4495. if (ml.use_mmap && buft == llama_default_buffer_type_cpu(true)) {
  4496. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  4497. void * addr = nullptr;
  4498. size_t first, last;
  4499. ml.get_mapping_range(&first, &last, &addr, idx, ctx);
  4500. if (first >= last) {
  4501. continue;
  4502. }
  4503. ggml_backend_buffer_t buf = ggml_backend_cpu_buffer_from_ptr((char *) addr + first, last - first);
  4504. if (buf == nullptr) {
  4505. throw std::runtime_error("unable to allocate backend CPU buffer");
  4506. }
  4507. model.bufs.push_back(buf);
  4508. bufs.emplace(idx, buf);
  4509. #ifdef GGML_USE_CUDA
  4510. if (n_layer >= n_gpu_layers) {
  4511. ggml_backend_cuda_register_host_buffer(
  4512. ggml_backend_buffer_get_base(buf),
  4513. ggml_backend_buffer_get_size(buf));
  4514. }
  4515. #endif
  4516. }
  4517. }
  4518. #ifdef GGML_USE_METAL
  4519. else if (ml.use_mmap && buft == ggml_backend_metal_buffer_type()) {
  4520. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  4521. const size_t max_size = ggml_get_max_tensor_size(ctx);
  4522. void * addr = nullptr;
  4523. size_t first, last;
  4524. ml.get_mapping_range(&first, &last, &addr, idx, ctx);
  4525. if (first >= last) {
  4526. continue;
  4527. }
  4528. ggml_backend_buffer_t buf = ggml_backend_metal_buffer_from_ptr((char *) addr + first, last - first, max_size);
  4529. if (buf == nullptr) {
  4530. throw std::runtime_error("unable to allocate backend metal buffer");
  4531. }
  4532. model.bufs.push_back(buf);
  4533. bufs.emplace(idx, buf);
  4534. }
  4535. }
  4536. #endif
  4537. else {
  4538. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  4539. if (buf == nullptr) {
  4540. throw std::runtime_error("unable to allocate backend buffer");
  4541. }
  4542. model.bufs.push_back(buf);
  4543. if (use_mlock && ggml_backend_buffer_is_host(buf)) {
  4544. model.mlock_bufs.emplace_back(new llama_mlock);
  4545. auto & mlock_buf = model.mlock_bufs.back();
  4546. mlock_buf->init (ggml_backend_buffer_get_base(buf));
  4547. mlock_buf->grow_to(ggml_backend_buffer_get_size(buf));
  4548. }
  4549. for (uint32_t idx = 0; idx < ml.files.size(); idx++) {
  4550. bufs.emplace(idx, buf);
  4551. }
  4552. }
  4553. if (bufs.empty()) {
  4554. throw std::runtime_error("failed to allocate buffer");
  4555. }
  4556. for (auto & buf : bufs) {
  4557. // indicate that this buffer contains weights
  4558. // 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
  4559. ggml_backend_buffer_set_usage(buf.second, GGML_BACKEND_BUFFER_USAGE_WEIGHTS);
  4560. }
  4561. ctx_bufs.emplace_back(ctx, bufs);
  4562. }
  4563. if (llama_supports_gpu_offload()) {
  4564. const int n_gpu = std::min(n_gpu_layers, int(hparams.n_layer));
  4565. LLAMA_LOG_INFO("%s: offloading %d repeating layers to GPU\n", __func__, n_gpu);
  4566. if (n_gpu_layers > (int) hparams.n_layer) {
  4567. LLAMA_LOG_INFO("%s: offloading non-repeating layers to GPU\n", __func__);
  4568. }
  4569. const int max_backend_supported_layers = hparams.n_layer + 1;
  4570. const int max_offloadable_layers = hparams.n_layer + 1;
  4571. LLAMA_LOG_INFO("%s: offloaded %d/%d layers to GPU\n", __func__, std::min(n_gpu_layers, max_offloadable_layers), max_backend_supported_layers);
  4572. }
  4573. // print memory requirements
  4574. for (ggml_backend_buffer_t buf : model.bufs) {
  4575. 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);
  4576. }
  4577. // populate tensors_by_name
  4578. for (ggml_context * ctx : model.ctxs) {
  4579. for (auto * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  4580. model.tensors_by_name.emplace_back(ggml_get_name(cur), cur);
  4581. }
  4582. }
  4583. // load tensor data
  4584. for (auto & it : ctx_bufs) {
  4585. ggml_context * ctx = it.first;
  4586. auto & bufs = it.second;
  4587. if (!ml.load_all_data(ctx, bufs, use_mlock ? &model.mlock_mmaps : NULL, progress_callback, progress_callback_user_data)) {
  4588. return false;
  4589. }
  4590. }
  4591. for (auto & mapping : ml.mappings) {
  4592. model.mappings.emplace_back(std::move(mapping));
  4593. }
  4594. // loading time will be recalculate after the first eval, so
  4595. // we take page faults deferred by mmap() into consideration
  4596. model.t_load_us = ggml_time_us() - model.t_start_us;
  4597. return true;
  4598. }
  4599. // Returns 0 on success, -1 on error, and -2 on cancellation via llama_progress_callback
  4600. static int llama_model_load(const std::string & fname, llama_model & model, llama_model_params & params) {
  4601. try {
  4602. llama_model_loader ml(fname, params.use_mmap, params.kv_overrides);
  4603. model.hparams.vocab_only = params.vocab_only;
  4604. try {
  4605. llm_load_arch(ml, model);
  4606. } catch(const std::exception & e) {
  4607. throw std::runtime_error("error loading model architecture: " + std::string(e.what()));
  4608. }
  4609. try {
  4610. llm_load_hparams(ml, model);
  4611. } catch(const std::exception & e) {
  4612. throw std::runtime_error("error loading model hyperparameters: " + std::string(e.what()));
  4613. }
  4614. try {
  4615. llm_load_vocab(ml, model);
  4616. } catch(const std::exception & e) {
  4617. throw std::runtime_error("error loading model vocabulary: " + std::string(e.what()));
  4618. }
  4619. llm_load_print_meta(ml, model);
  4620. if (model.vocab.type != LLAMA_VOCAB_TYPE_NONE &&
  4621. model.hparams.n_vocab != model.vocab.id_to_token.size()) {
  4622. throw std::runtime_error("vocab size mismatch");
  4623. }
  4624. if (params.vocab_only) {
  4625. LLAMA_LOG_INFO("%s: vocab only - skipping tensors\n", __func__);
  4626. return 0;
  4627. }
  4628. #ifdef GGML_USE_KOMPUTE
  4629. if (params.n_gpu_layers > 0 && (
  4630. !(model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON)
  4631. || !(
  4632. model.ftype == LLAMA_FTYPE_ALL_F32 ||
  4633. model.ftype == LLAMA_FTYPE_MOSTLY_F16 ||
  4634. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ||
  4635. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_1
  4636. )
  4637. )) {
  4638. // TODO(cebtenzzre): propagate this error outside of llama_load_model_from_file
  4639. LLAMA_LOG_WARN("%s: disabling Kompute due to unsupported model arch or quantization\n", __func__);
  4640. params.n_gpu_layers = 0;
  4641. }
  4642. #endif
  4643. #ifdef GGML_USE_SYCL
  4644. if (params.split_mode == LLAMA_SPLIT_MODE_NONE) {
  4645. ggml_backend_sycl_set_single_device_mode(params.main_gpu);
  4646. //SYCL use device index (0, 1, 2) directly, uer input device id, then convert to device index.
  4647. params.main_gpu = ggml_backend_sycl_get_device_index(params.main_gpu);
  4648. } else {
  4649. ggml_backend_sycl_set_mul_device_mode();
  4650. }
  4651. #endif
  4652. if (!llm_load_tensors(
  4653. ml, model, params.n_gpu_layers, params.split_mode, params.main_gpu, params.tensor_split, params.use_mlock,
  4654. params.progress_callback, params.progress_callback_user_data
  4655. )) {
  4656. return -2;
  4657. }
  4658. } catch (const std::exception & err) {
  4659. LLAMA_LOG_ERROR("%s: error loading model: %s\n", __func__, err.what());
  4660. return -1;
  4661. }
  4662. return 0;
  4663. }
  4664. //
  4665. // llm_build
  4666. //
  4667. using llm_build_cb = std::function<void(struct ggml_tensor * cur, const char * name, int nl)>;
  4668. enum llm_ffn_op_type {
  4669. LLM_FFN_SILU,
  4670. LLM_FFN_GELU,
  4671. LLM_FFN_RELU,
  4672. LLM_FFN_RELU_SQR,
  4673. };
  4674. enum llm_ffn_gate_type {
  4675. LLM_FFN_SEQ,
  4676. LLM_FFN_PAR, // ffn_gate is parallel to ffn_up
  4677. };
  4678. enum llm_norm_type {
  4679. LLM_NORM,
  4680. LLM_NORM_RMS,
  4681. };
  4682. static struct ggml_tensor * llm_build_inp_embd(
  4683. struct ggml_context * ctx,
  4684. struct llama_context & lctx,
  4685. const llama_hparams & hparams,
  4686. const llama_batch & batch,
  4687. struct ggml_tensor * tok_embd,
  4688. const llm_build_cb & cb) {
  4689. const int64_t n_embd = hparams.n_embd;
  4690. struct ggml_tensor * inpL;
  4691. if (batch.token) {
  4692. lctx.inp_tokens = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, batch.n_tokens);
  4693. cb(lctx.inp_tokens, "inp_tokens", -1);
  4694. ggml_set_input(lctx.inp_tokens);
  4695. inpL = ggml_get_rows(ctx, tok_embd, lctx.inp_tokens);
  4696. } else {
  4697. #ifdef GGML_USE_MPI
  4698. GGML_ASSERT(false && "not implemented");
  4699. #endif
  4700. lctx.inp_embd = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, batch.n_tokens);
  4701. inpL = lctx.inp_embd;
  4702. ggml_set_input(lctx.inp_embd);
  4703. }
  4704. cb(inpL, "inp_embd", -1);
  4705. return inpL;
  4706. }
  4707. static void llm_build_kv_store(
  4708. struct ggml_context * ctx,
  4709. const llama_hparams & hparams,
  4710. const llama_kv_cache & kv,
  4711. struct ggml_cgraph * graph,
  4712. struct ggml_tensor * k_cur,
  4713. struct ggml_tensor * v_cur,
  4714. int64_t n_ctx,
  4715. int32_t n_tokens,
  4716. int32_t kv_head,
  4717. const llm_build_cb & cb,
  4718. int64_t il) {
  4719. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  4720. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  4721. GGML_ASSERT(kv.size == n_ctx);
  4722. // compute the transposed [n_tokens, n_embd] V matrix
  4723. struct ggml_tensor * v_cur_t = ggml_transpose(ctx, ggml_reshape_2d(ctx, v_cur, n_embd_v_gqa, n_tokens));
  4724. //struct ggml_tensor * v_cur_t = ggml_transpose(ctx, v_cur); // TODO: reshape above is likely not needed
  4725. cb(v_cur_t, "v_cur_t", il);
  4726. struct ggml_tensor * k_cache_view = ggml_view_1d(ctx, kv.k_l[il], n_tokens*n_embd_k_gqa,
  4727. (ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa))*kv_head);
  4728. cb(k_cache_view, "k_cache_view", il);
  4729. struct ggml_tensor * v_cache_view = ggml_view_2d(ctx, kv.v_l[il], n_tokens, n_embd_v_gqa,
  4730. ( n_ctx)*ggml_element_size(kv.v_l[il]),
  4731. (kv_head)*ggml_element_size(kv.v_l[il]));
  4732. cb(v_cache_view, "v_cache_view", il);
  4733. // important: storing RoPE-ed version of K in the KV cache!
  4734. ggml_build_forward_expand(graph, ggml_cpy(ctx, k_cur, k_cache_view));
  4735. ggml_build_forward_expand(graph, ggml_cpy(ctx, v_cur_t, v_cache_view));
  4736. }
  4737. static struct ggml_tensor * llm_build_norm(
  4738. struct ggml_context * ctx,
  4739. struct ggml_tensor * cur,
  4740. const llama_hparams & hparams,
  4741. struct ggml_tensor * mw,
  4742. struct ggml_tensor * mb,
  4743. llm_norm_type type,
  4744. const llm_build_cb & cb,
  4745. int il) {
  4746. switch (type) {
  4747. case LLM_NORM: cur = ggml_norm (ctx, cur, hparams.f_norm_eps); break;
  4748. case LLM_NORM_RMS: cur = ggml_rms_norm(ctx, cur, hparams.f_norm_rms_eps); break;
  4749. }
  4750. if (mw || mb) {
  4751. cb(cur, "norm", il);
  4752. }
  4753. if (mw) {
  4754. cur = ggml_mul(ctx, cur, mw);
  4755. if (mb) {
  4756. cb(cur, "norm_w", il);
  4757. }
  4758. }
  4759. if (mb) {
  4760. cur = ggml_add(ctx, cur, mb);
  4761. }
  4762. return cur;
  4763. }
  4764. static struct ggml_tensor * llm_build_ffn(
  4765. struct ggml_context * ctx,
  4766. struct ggml_tensor * cur,
  4767. struct ggml_tensor * up,
  4768. struct ggml_tensor * up_b,
  4769. struct ggml_tensor * gate,
  4770. struct ggml_tensor * gate_b,
  4771. struct ggml_tensor * down,
  4772. struct ggml_tensor * down_b,
  4773. struct ggml_tensor * act_scales,
  4774. llm_ffn_op_type type_op,
  4775. llm_ffn_gate_type type_gate,
  4776. const llm_build_cb & cb,
  4777. int il) {
  4778. struct ggml_tensor * tmp = ggml_mul_mat(ctx, up, cur);
  4779. cb(tmp, "ffn_up", il);
  4780. if (up_b) {
  4781. tmp = ggml_add(ctx, tmp, up_b);
  4782. cb(tmp, "ffn_up_b", il);
  4783. }
  4784. if (gate) {
  4785. switch (type_gate) {
  4786. case LLM_FFN_SEQ:
  4787. {
  4788. cur = ggml_mul_mat(ctx, gate, tmp);
  4789. cb(cur, "ffn_gate", il);
  4790. } break;
  4791. case LLM_FFN_PAR:
  4792. {
  4793. cur = ggml_mul_mat(ctx, gate, cur);
  4794. cb(cur, "ffn_gate", il);
  4795. } break;
  4796. }
  4797. if (gate_b) {
  4798. cur = ggml_add(ctx, cur, gate_b);
  4799. cb(cur, "ffn_gate_b", il);
  4800. }
  4801. } else {
  4802. cur = tmp;
  4803. }
  4804. switch (type_op) {
  4805. case LLM_FFN_SILU:
  4806. {
  4807. cur = ggml_silu(ctx, cur);
  4808. cb(cur, "ffn_silu", il);
  4809. } break;
  4810. case LLM_FFN_GELU:
  4811. {
  4812. cur = ggml_gelu(ctx, cur);
  4813. cb(cur, "ffn_gelu", il);
  4814. if (act_scales != NULL) {
  4815. cur = ggml_div(ctx, cur, act_scales);
  4816. cb(cur, "ffn_act", il);
  4817. }
  4818. } break;
  4819. case LLM_FFN_RELU:
  4820. {
  4821. cur = ggml_relu(ctx, cur);
  4822. cb(cur, "ffn_relu", il);
  4823. } break;
  4824. case LLM_FFN_RELU_SQR:
  4825. {
  4826. cur = ggml_relu(ctx, cur);
  4827. cb(cur, "ffn_relu", il);
  4828. cur = ggml_sqr(ctx, cur);
  4829. cb(cur, "ffn_sqr(relu)", il);
  4830. } break;
  4831. }
  4832. if (type_gate == LLM_FFN_PAR) {
  4833. cur = ggml_mul(ctx, cur, tmp);
  4834. cb(cur, "ffn_gate_par", il);
  4835. }
  4836. cur = ggml_mul_mat(ctx, down, cur);
  4837. if (down_b) {
  4838. cb(cur, "ffn_down", il);
  4839. }
  4840. if (down_b) {
  4841. cur = ggml_add(ctx, cur, down_b);
  4842. }
  4843. return cur;
  4844. }
  4845. // if max_alibi_bias > 0 then apply ALiBi
  4846. static struct ggml_tensor * llm_build_kqv(
  4847. struct ggml_context * ctx,
  4848. const llama_model & model,
  4849. const llama_hparams & hparams,
  4850. const llama_kv_cache & kv,
  4851. struct ggml_cgraph * graph,
  4852. struct ggml_tensor * wo,
  4853. struct ggml_tensor * wo_b,
  4854. struct ggml_tensor * q_cur,
  4855. struct ggml_tensor * kq_mask,
  4856. struct ggml_tensor * kq_pos,
  4857. int64_t n_ctx,
  4858. int32_t n_tokens,
  4859. int32_t n_kv,
  4860. float kq_scale,
  4861. const llm_build_cb & cb,
  4862. int il) {
  4863. const int64_t n_head = hparams.n_head;
  4864. const int64_t n_head_kv = hparams.n_head_kv;
  4865. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  4866. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  4867. const int64_t n_embd_head_v = hparams.n_embd_head_v;
  4868. struct ggml_tensor * q = ggml_permute(ctx, q_cur, 0, 2, 1, 3);
  4869. cb(q, "q", il);
  4870. struct ggml_tensor * k =
  4871. ggml_view_3d(ctx, kv.k_l[il],
  4872. n_embd_head_k, n_kv, n_head_kv,
  4873. ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa),
  4874. ggml_row_size(kv.k_l[il]->type, n_embd_head_k),
  4875. 0);
  4876. cb(k, "k", il);
  4877. struct ggml_tensor * kq = ggml_mul_mat(ctx, k, q);
  4878. cb(kq, "kq", il);
  4879. if (model.arch == LLM_ARCH_PHI2) {
  4880. // for this arch, we need to perform the KQ multiplication with F32 precision, otherwise we get NaNs
  4881. // ref: https://github.com/ggerganov/llama.cpp/pull/4490#issuecomment-1859055847
  4882. ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  4883. }
  4884. if (model.arch == LLM_ARCH_GROK) {
  4885. // need to do the following:
  4886. // multiply by attn_output_multiplyer of 0.08838834764831845
  4887. // and then :
  4888. // kq = 30 * tanh(kq / 30)
  4889. // before the softmax below
  4890. //try from phi2
  4891. //ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  4892. kq = ggml_tanh(ctx, ggml_scale(ctx, kq, 0.08838834764831845f/30.0f));
  4893. kq = ggml_scale(ctx, kq, 30);
  4894. }
  4895. #if defined(GGML_USE_KOMPUTE)
  4896. #pragma message("TODO: ALiBi support in ggml_soft_max_ext is not implemented for Kompute")
  4897. #pragma message(" Falling back to ggml_alibi(). Will become an error in Mar 2024")
  4898. #pragma message("ref: https://github.com/ggerganov/llama.cpp/pull/5488")
  4899. if (hparams.f_max_alibi_bias > 0.0f) {
  4900. kq = ggml_scale(ctx, kq, kq_scale);
  4901. cb(kq, "kq_scaled", il);
  4902. kq = ggml_alibi(ctx, kq, /*n_past*/ 0, n_head, hparams.f_max_alibi_bias);
  4903. cb(kq, "kq_scaled_alibi", il);
  4904. kq = ggml_add(ctx, kq, kq_mask);
  4905. cb(kq, "kq_masked", il);
  4906. kq = ggml_soft_max(ctx, kq);
  4907. cb(kq, "kq_soft_max", il);
  4908. } else
  4909. #endif
  4910. {
  4911. kq = ggml_soft_max_ext(ctx, kq, kq_mask, kq_pos, kq_scale, hparams.f_max_alibi_bias);
  4912. cb(kq, "kq_soft_max_ext", il);
  4913. }
  4914. GGML_ASSERT(kv.size == n_ctx);
  4915. // split cached v into n_head heads
  4916. struct ggml_tensor * v =
  4917. ggml_view_3d(ctx, kv.v_l[il],
  4918. n_kv, n_embd_head_v, n_head_kv,
  4919. ggml_element_size(kv.v_l[il])*n_ctx,
  4920. ggml_element_size(kv.v_l[il])*n_ctx*n_embd_head_v,
  4921. 0);
  4922. cb(v, "v", il);
  4923. struct ggml_tensor * kqv = ggml_mul_mat(ctx, v, kq);
  4924. cb(kqv, "kqv", il);
  4925. struct ggml_tensor * kqv_merged = ggml_permute(ctx, kqv, 0, 2, 1, 3);
  4926. cb(kqv_merged, "kqv_merged", il);
  4927. struct ggml_tensor * cur = ggml_cont_2d(ctx, kqv_merged, n_embd_head_k*n_head, n_tokens);
  4928. cb(cur, "kqv_merged_cont", il);
  4929. ggml_build_forward_expand(graph, cur);
  4930. cur = ggml_mul_mat(ctx, wo, cur);
  4931. if (wo_b) {
  4932. cb(cur, "kqv_wo", il);
  4933. }
  4934. if (wo_b) {
  4935. cur = ggml_add(ctx, cur, wo_b);
  4936. }
  4937. return cur;
  4938. }
  4939. static struct ggml_tensor * llm_build_kv(
  4940. struct ggml_context * ctx,
  4941. const llama_model & model,
  4942. const llama_hparams & hparams,
  4943. const llama_kv_cache & kv,
  4944. struct ggml_cgraph * graph,
  4945. struct ggml_tensor * wo,
  4946. struct ggml_tensor * wo_b,
  4947. struct ggml_tensor * k_cur,
  4948. struct ggml_tensor * v_cur,
  4949. struct ggml_tensor * q_cur,
  4950. struct ggml_tensor * kq_mask,
  4951. struct ggml_tensor * kq_pos,
  4952. int64_t n_ctx,
  4953. int32_t n_tokens,
  4954. int32_t kv_head,
  4955. int32_t n_kv,
  4956. float kq_scale,
  4957. const llm_build_cb & cb,
  4958. int il) {
  4959. // these nodes are added to the graph together so that they are not reordered
  4960. // by doing so, the number of splits in the graph is reduced
  4961. ggml_build_forward_expand(graph, q_cur);
  4962. ggml_build_forward_expand(graph, k_cur);
  4963. ggml_build_forward_expand(graph, v_cur);
  4964. llm_build_kv_store(ctx, hparams, kv, graph, k_cur, v_cur, n_ctx, n_tokens, kv_head, cb, il);
  4965. struct ggml_tensor * cur;
  4966. cur = llm_build_kqv(ctx, model, hparams, kv, graph, wo, wo_b,
  4967. q_cur, kq_mask, kq_pos, n_ctx, n_tokens, n_kv, kq_scale, cb, il);
  4968. cb(cur, "kqv_out", il);
  4969. return cur;
  4970. }
  4971. struct llm_build_context {
  4972. const llama_model & model;
  4973. llama_context & lctx;
  4974. const llama_hparams & hparams;
  4975. const llama_cparams & cparams;
  4976. const llama_batch & batch;
  4977. const llama_kv_cache & kv_self;
  4978. const int64_t n_embd;
  4979. const int64_t n_layer;
  4980. const int64_t n_rot;
  4981. const int64_t n_ctx; // user-specified context size (can be different from n_ctx_train)
  4982. const int64_t n_head;
  4983. const int64_t n_head_kv;
  4984. const int64_t n_embd_head_k;
  4985. const int64_t n_embd_k_gqa;
  4986. const int64_t n_embd_head_v;
  4987. const int64_t n_embd_v_gqa;
  4988. const int64_t n_expert;
  4989. const int64_t n_expert_used;
  4990. const float freq_base;
  4991. const float freq_scale;
  4992. const float ext_factor;
  4993. const float attn_factor;
  4994. const float beta_fast;
  4995. const float beta_slow;
  4996. const float norm_eps;
  4997. const float norm_rms_eps;
  4998. const int32_t n_tokens;
  4999. const int32_t n_kv; // size of KV cache to consider (n_kv <= kv_self.size)
  5000. const int32_t n_outputs;
  5001. const int32_t kv_head; // index of where we store new KV data in the cache
  5002. const int32_t n_orig_ctx;
  5003. const enum llama_pooling_type pooling_type;
  5004. const enum llama_rope_type rope_type;
  5005. const llm_build_cb & cb;
  5006. std::vector<uint8_t> & buf_compute_meta;
  5007. struct ggml_context * ctx0 = nullptr;
  5008. // TODO: consider making the entire interface noexcept
  5009. llm_build_context(
  5010. llama_context & lctx,
  5011. const llama_batch & batch,
  5012. const llm_build_cb & cb,
  5013. bool worst_case) :
  5014. model (lctx.model),
  5015. lctx (lctx),
  5016. hparams (model.hparams),
  5017. cparams (lctx.cparams),
  5018. batch (batch),
  5019. kv_self (lctx.kv_self),
  5020. n_embd (hparams.n_embd),
  5021. n_layer (hparams.n_layer),
  5022. n_rot (hparams.n_rot),
  5023. n_ctx (cparams.n_ctx),
  5024. n_head (hparams.n_head),
  5025. n_head_kv (hparams.n_head_kv),
  5026. n_embd_head_k (hparams.n_embd_head_k),
  5027. n_embd_k_gqa (hparams.n_embd_k_gqa()),
  5028. n_embd_head_v (hparams.n_embd_head_v),
  5029. n_embd_v_gqa (hparams.n_embd_v_gqa()),
  5030. n_expert (hparams.n_expert),
  5031. n_expert_used (hparams.n_expert_used),
  5032. freq_base (cparams.rope_freq_base),
  5033. freq_scale (cparams.rope_freq_scale),
  5034. ext_factor (cparams.yarn_ext_factor),
  5035. attn_factor (cparams.yarn_attn_factor),
  5036. beta_fast (cparams.yarn_beta_fast),
  5037. beta_slow (cparams.yarn_beta_slow),
  5038. norm_eps (hparams.f_norm_eps),
  5039. norm_rms_eps (hparams.f_norm_rms_eps),
  5040. n_tokens (batch.n_tokens),
  5041. n_kv (worst_case ? kv_self.size : kv_self.n),
  5042. n_outputs (worst_case ? n_tokens : lctx.n_outputs),
  5043. kv_head (worst_case ? (kv_self.recurrent ? 0 : kv_self.size - n_tokens) : kv_self.head),
  5044. n_orig_ctx (cparams.n_yarn_orig_ctx),
  5045. pooling_type (cparams.pooling_type),
  5046. rope_type (hparams.rope_type),
  5047. cb (cb),
  5048. buf_compute_meta (lctx.buf_compute_meta) {
  5049. // all initializations should be done in init()
  5050. }
  5051. void init() {
  5052. struct ggml_init_params params = {
  5053. /*.mem_size =*/ buf_compute_meta.size(),
  5054. /*.mem_buffer =*/ buf_compute_meta.data(),
  5055. /*.no_alloc =*/ true,
  5056. };
  5057. ctx0 = ggml_init(params);
  5058. lctx.inp_tokens = nullptr;
  5059. lctx.inp_embd = nullptr;
  5060. lctx.inp_pos = nullptr;
  5061. lctx.inp_out_ids = nullptr;
  5062. lctx.inp_KQ_mask = nullptr;
  5063. lctx.inp_KQ_pos = nullptr;
  5064. lctx.inp_K_shift = nullptr;
  5065. lctx.inp_mean = nullptr;
  5066. lctx.inp_cls = nullptr;
  5067. lctx.inp_s_copy = nullptr;
  5068. lctx.inp_s_mask = nullptr;
  5069. lctx.inp_s_seq = nullptr;
  5070. }
  5071. void free() {
  5072. if (ctx0) {
  5073. ggml_free(ctx0);
  5074. ctx0 = nullptr;
  5075. }
  5076. }
  5077. struct ggml_cgraph * build_k_shift() {
  5078. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5079. GGML_ASSERT(kv_self.size == n_ctx);
  5080. lctx.inp_K_shift = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_ctx);
  5081. cb(lctx.inp_K_shift, "K_shift", -1);
  5082. ggml_set_input(lctx.inp_K_shift);
  5083. for (int il = 0; il < n_layer; ++il) {
  5084. struct ggml_tensor * tmp =
  5085. // we rotate only the first n_rot dimensions
  5086. ggml_rope_custom_inplace(ctx0,
  5087. ggml_view_3d(ctx0, kv_self.k_l[il],
  5088. n_embd_head_k, n_head_kv, n_ctx,
  5089. ggml_row_size(kv_self.k_l[il]->type, n_embd_head_k),
  5090. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  5091. 0),
  5092. lctx.inp_K_shift, n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5093. ext_factor, attn_factor, beta_fast, beta_slow);
  5094. cb(tmp, "K_shifted", il);
  5095. ggml_build_forward_expand(gf, tmp);
  5096. }
  5097. return gf;
  5098. }
  5099. struct ggml_cgraph * build_s_copy() {
  5100. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5101. GGML_ASSERT(kv_self.recurrent);
  5102. struct ggml_tensor * state_copy = build_inp_s_copy();
  5103. for (int il = 0; il < n_layer; ++il) {
  5104. struct ggml_tensor * conv_states = ggml_reshape_2d(ctx0, kv_self.k_l[il], hparams.n_embd_k_s(), kv_self.size);
  5105. struct ggml_tensor * ssm_states = ggml_reshape_2d(ctx0, kv_self.v_l[il], hparams.n_embd_v_s(), kv_self.size);
  5106. conv_states = ggml_get_rows(ctx0, conv_states, state_copy);
  5107. ssm_states = ggml_get_rows(ctx0, ssm_states, state_copy);
  5108. // TODO: name the intermediate tensors with cb()
  5109. ggml_build_forward_expand(gf, ggml_cpy(ctx0, conv_states, kv_self.k_l[il]));
  5110. ggml_build_forward_expand(gf, ggml_cpy(ctx0, ssm_states, kv_self.v_l[il]));
  5111. }
  5112. return gf;
  5113. }
  5114. struct ggml_cgraph * build_defrag(const std::vector<uint32_t> & ids) {
  5115. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5116. for (uint32_t i = 0; i < ids.size(); ++i) {
  5117. const uint32_t id = ids[i];
  5118. if (i == id || id == ids.size()) {
  5119. continue;
  5120. }
  5121. uint32_t nm = 1;
  5122. while (i + nm < ids.size() && ids[i + nm] == id + nm) {
  5123. nm++;
  5124. }
  5125. for (int il = 0; il < n_layer; ++il) {
  5126. ggml_tensor * view_k_src = ggml_view_2d(ctx0, kv_self.k_l[il],
  5127. n_embd_k_gqa, nm,
  5128. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  5129. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*i));
  5130. ggml_tensor * view_k_dst = ggml_view_2d(ctx0, kv_self.k_l[il],
  5131. n_embd_k_gqa, nm,
  5132. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  5133. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*id));
  5134. ggml_tensor * view_v_src = ggml_view_2d(ctx0, kv_self.v_l[il],
  5135. nm, n_embd_v_gqa,
  5136. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  5137. ggml_row_size(kv_self.v_l[il]->type, i));
  5138. ggml_tensor * view_v_dst = ggml_view_2d(ctx0, kv_self.v_l[il],
  5139. nm, n_embd_v_gqa,
  5140. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  5141. ggml_row_size(kv_self.v_l[il]->type, id));
  5142. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_k_src, view_k_dst));
  5143. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_v_src, view_v_dst));
  5144. }
  5145. i += nm - 1;
  5146. }
  5147. //LLAMA_LOG_INFO("gf->n_nodes = %d\n", gf->n_nodes);
  5148. return gf;
  5149. }
  5150. struct ggml_tensor * build_inp_pos() {
  5151. lctx.inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  5152. cb(lctx.inp_pos, "inp_pos", -1);
  5153. ggml_set_input(lctx.inp_pos);
  5154. return lctx.inp_pos;
  5155. }
  5156. struct ggml_tensor * build_inp_out_ids() {
  5157. lctx.inp_out_ids = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_outputs);
  5158. cb(lctx.inp_out_ids, "inp_out_ids", -1);
  5159. ggml_set_input(lctx.inp_out_ids);
  5160. return lctx.inp_out_ids;
  5161. }
  5162. struct ggml_tensor * build_inp_KQ_mask(bool causal = true) {
  5163. if (causal) {
  5164. lctx.inp_KQ_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_kv, n_tokens);
  5165. } else {
  5166. lctx.inp_KQ_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, n_tokens);
  5167. }
  5168. cb(lctx.inp_KQ_mask, "KQ_mask", -1);
  5169. ggml_set_input(lctx.inp_KQ_mask);
  5170. return lctx.inp_KQ_mask;
  5171. }
  5172. struct ggml_tensor * build_inp_KQ_pos() {
  5173. lctx.inp_KQ_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, n_kv);
  5174. cb(lctx.inp_KQ_pos, "KQ_pos", -1);
  5175. ggml_set_input(lctx.inp_KQ_pos);
  5176. return lctx.inp_KQ_pos;
  5177. }
  5178. struct ggml_tensor * build_inp_mean() {
  5179. lctx.inp_mean = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, n_tokens);
  5180. cb(lctx.inp_mean, "inp_mean", -1);
  5181. ggml_set_input(lctx.inp_mean);
  5182. return lctx.inp_mean;
  5183. }
  5184. struct ggml_tensor * build_inp_cls() {
  5185. lctx.inp_cls = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  5186. cb(lctx.inp_cls, "inp_cls", -1);
  5187. ggml_set_input(lctx.inp_cls);
  5188. return lctx.inp_cls;
  5189. }
  5190. struct ggml_tensor * build_inp_s_copy() {
  5191. lctx.inp_s_copy = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, kv_self.size);
  5192. cb(lctx.inp_s_copy, "inp_s_copy", -1);
  5193. ggml_set_input(lctx.inp_s_copy);
  5194. return lctx.inp_s_copy;
  5195. }
  5196. struct ggml_tensor * build_inp_s_mask() {
  5197. lctx.inp_s_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, 1, n_kv);
  5198. cb(lctx.inp_s_mask, "inp_s_mask", -1);
  5199. ggml_set_input(lctx.inp_s_mask);
  5200. return lctx.inp_s_mask;
  5201. }
  5202. struct ggml_tensor * build_inp_s_seq() {
  5203. lctx.inp_s_seq = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_kv, n_tokens);
  5204. cb(lctx.inp_s_seq, "inp_s_seq", -1);
  5205. ggml_set_input(lctx.inp_s_seq);
  5206. return lctx.inp_s_seq;
  5207. }
  5208. struct ggml_cgraph * build_llama() {
  5209. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5210. // mutable variable, needed during the last layer of the computation to skip unused tokens
  5211. int32_t n_tokens = this->n_tokens;
  5212. const int64_t n_embd_head = hparams.n_embd_head_v;
  5213. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5214. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5215. struct ggml_tensor * cur;
  5216. struct ggml_tensor * inpL;
  5217. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5218. // inp_pos - contains the positions
  5219. struct ggml_tensor * inp_pos = build_inp_pos();
  5220. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5221. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5222. for (int il = 0; il < n_layer; ++il) {
  5223. struct ggml_tensor * inpSA = inpL;
  5224. // norm
  5225. cur = llm_build_norm(ctx0, inpL, hparams,
  5226. model.layers[il].attn_norm, NULL,
  5227. LLM_NORM_RMS, cb, il);
  5228. cb(cur, "attn_norm", il);
  5229. // self-attention
  5230. {
  5231. // compute Q and K and RoPE them
  5232. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5233. cb(Qcur, "Qcur", il);
  5234. if (model.layers[il].bq) {
  5235. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5236. cb(Qcur, "Qcur", il);
  5237. }
  5238. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5239. cb(Kcur, "Kcur", il);
  5240. if (model.layers[il].bk) {
  5241. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5242. cb(Kcur, "Kcur", il);
  5243. }
  5244. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5245. cb(Vcur, "Vcur", il);
  5246. if (model.layers[il].bv) {
  5247. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  5248. cb(Vcur, "Vcur", il);
  5249. }
  5250. Qcur = ggml_rope_custom(
  5251. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5252. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5253. ext_factor, attn_factor, beta_fast, beta_slow
  5254. );
  5255. cb(Qcur, "Qcur", il);
  5256. Kcur = ggml_rope_custom(
  5257. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5258. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5259. ext_factor, attn_factor, beta_fast, beta_slow
  5260. );
  5261. cb(Kcur, "Kcur", il);
  5262. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5263. model.layers[il].wo, model.layers[il].bo,
  5264. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5265. }
  5266. if (il == n_layer - 1) {
  5267. // skip computing output for unused tokens
  5268. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  5269. n_tokens = n_outputs;
  5270. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  5271. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  5272. }
  5273. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5274. cb(ffn_inp, "ffn_inp", il);
  5275. // feed-forward network
  5276. if (model.layers[il].ffn_gate_inp == nullptr) {
  5277. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5278. model.layers[il].ffn_norm, NULL,
  5279. LLM_NORM_RMS, cb, il);
  5280. cb(cur, "ffn_norm", il);
  5281. cur = llm_build_ffn(ctx0, cur,
  5282. model.layers[il].ffn_up, NULL,
  5283. model.layers[il].ffn_gate, NULL,
  5284. model.layers[il].ffn_down, NULL,
  5285. NULL,
  5286. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5287. cb(cur, "ffn_out", il);
  5288. } else {
  5289. // MoE branch
  5290. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5291. model.layers[il].ffn_norm, NULL,
  5292. LLM_NORM_RMS, cb, il);
  5293. cb(cur, "ffn_norm", il);
  5294. ggml_tensor * logits = ggml_mul_mat(ctx0, model.layers[il].ffn_gate_inp, cur); // [n_tokens, num_experts]
  5295. cb(logits, "ffn_moe_logits", il);
  5296. ggml_tensor * probs = ggml_soft_max(ctx0, logits); // [n_tokens, num_experts]
  5297. cb(probs, "ffn_moe_probs", il);
  5298. // select experts
  5299. ggml_tensor * selected_experts = ggml_top_k(ctx0, probs, n_expert_used); // [n_tokens, num_experts_per_tok]
  5300. cb(selected_experts->src[0], "ffn_moe_argsort", il);
  5301. ggml_tensor * weights = ggml_get_rows(ctx0,
  5302. ggml_reshape_3d(ctx0, probs, 1, n_expert, n_tokens), selected_experts);
  5303. cb(weights, "ffn_moe_weights", il);
  5304. weights = ggml_reshape_2d(ctx0, weights, n_expert_used, n_tokens); // [n_tokens, num_experts_per_tok]
  5305. ggml_tensor * weights_sum = ggml_sum_rows(ctx0, weights);
  5306. cb(weights_sum, "ffn_moe_weights_sum", il);
  5307. weights = ggml_div(ctx0, weights, weights_sum); // [n_tokens, num_experts_per_tok]
  5308. cb(weights, "ffn_moe_weights_norm", il);
  5309. // compute expert outputs
  5310. ggml_tensor * moe_out = nullptr;
  5311. for (int i = 0; i < n_expert_used; ++i) {
  5312. ggml_tensor * cur_expert;
  5313. ggml_tensor * cur_up = ggml_mul_mat_id(ctx0, model.layers[il].ffn_up_exp, n_expert, selected_experts, i, cur);
  5314. cb(cur_up, "ffn_moe_up", il);
  5315. ggml_tensor * cur_gate = ggml_mul_mat_id(ctx0, model.layers[il].ffn_gate_exp, n_expert, selected_experts, i, cur);
  5316. cb(cur_gate, "ffn_moe_gate", il);
  5317. cur_gate = ggml_silu(ctx0, cur_gate);
  5318. cb(cur_gate, "ffn_moe_silu", il);
  5319. cur_expert = ggml_mul(ctx0, cur_up, cur_gate); // [n_tokens, n_embd]
  5320. cb(cur_expert, "ffn_moe_gate_par", il);
  5321. cur_expert = ggml_mul_mat_id(ctx0, model.layers[il].ffn_down_exp, n_expert, selected_experts, i, cur_expert); // [n_tokens, n_embd]
  5322. cb(cur_expert, "ffn_moe_down", il);
  5323. cur_expert = ggml_mul(ctx0, cur_expert,
  5324. ggml_view_2d(ctx0, weights, 1, n_tokens, weights->nb[1], i*weights->nb[0]));
  5325. cb(cur_expert, "ffn_moe_weighted", il);
  5326. if (i == 0) {
  5327. moe_out = cur_expert;
  5328. } else {
  5329. moe_out = ggml_add(ctx0, moe_out, cur_expert);
  5330. cb(moe_out, "ffn_moe_out", il);
  5331. }
  5332. }
  5333. cur = moe_out;
  5334. }
  5335. cur = ggml_add(ctx0, cur, ffn_inp);
  5336. cb(cur, "ffn_out", il);
  5337. ggml_tensor * layer_dir = lctx.cvec.tensor_for(il);
  5338. if (layer_dir != nullptr) {
  5339. cur = ggml_add(ctx0, cur, layer_dir);
  5340. }
  5341. cb(cur, "l_out", il);
  5342. // input for next layer
  5343. inpL = cur;
  5344. }
  5345. cur = inpL;
  5346. cur = llm_build_norm(ctx0, cur, hparams,
  5347. model.output_norm, NULL,
  5348. LLM_NORM_RMS, cb, -1);
  5349. cb(cur, "result_norm", -1);
  5350. // lm_head
  5351. cur = ggml_mul_mat(ctx0, model.output, cur);
  5352. cb(cur, "result_output", -1);
  5353. ggml_build_forward_expand(gf, cur);
  5354. return gf;
  5355. }
  5356. struct ggml_cgraph * build_baichuan() {
  5357. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5358. const int64_t n_embd_head = hparams.n_embd_head_v;
  5359. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5360. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5361. struct ggml_tensor * cur;
  5362. struct ggml_tensor * inpL;
  5363. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5364. // inp_pos - contains the positions
  5365. struct ggml_tensor * inp_pos = model.type == MODEL_7B ? build_inp_pos() : nullptr;
  5366. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5367. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5368. // positions of the tokens in the KV cache
  5369. struct ggml_tensor * KQ_pos = build_inp_KQ_pos();
  5370. for (int il = 0; il < n_layer; ++il) {
  5371. struct ggml_tensor * inpSA = inpL;
  5372. cur = llm_build_norm(ctx0, inpL, hparams,
  5373. model.layers[il].attn_norm, NULL,
  5374. LLM_NORM_RMS, cb, il);
  5375. cb(cur, "attn_norm", il);
  5376. // self-attention
  5377. {
  5378. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5379. cb(Qcur, "Qcur", il);
  5380. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5381. cb(Kcur, "Kcur", il);
  5382. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5383. cb(Vcur, "Vcur", il);
  5384. switch (model.type) {
  5385. case MODEL_7B:
  5386. Qcur = ggml_rope_custom(
  5387. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5388. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5389. ext_factor, attn_factor, beta_fast, beta_slow
  5390. );
  5391. Kcur = ggml_rope_custom(
  5392. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5393. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5394. ext_factor, attn_factor, beta_fast, beta_slow
  5395. );
  5396. break;
  5397. case MODEL_13B:
  5398. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd/n_head, n_head, n_tokens);
  5399. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd/n_head, n_head, n_tokens);
  5400. break;
  5401. default:
  5402. GGML_ASSERT(false);
  5403. }
  5404. cb(Qcur, "Qcur", il);
  5405. cb(Kcur, "Kcur", il);
  5406. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5407. model.layers[il].wo, NULL,
  5408. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5409. }
  5410. if (il == n_layer - 1) {
  5411. // skip computing output for unused tokens
  5412. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  5413. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  5414. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  5415. }
  5416. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5417. cb(ffn_inp, "ffn_inp", il);
  5418. // feed-forward network
  5419. {
  5420. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5421. model.layers[il].ffn_norm, NULL,
  5422. LLM_NORM_RMS, cb, il);
  5423. cb(cur, "ffn_norm", il);
  5424. cur = llm_build_ffn(ctx0, cur,
  5425. model.layers[il].ffn_up, NULL,
  5426. model.layers[il].ffn_gate, NULL,
  5427. model.layers[il].ffn_down, NULL,
  5428. NULL,
  5429. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5430. cb(cur, "ffn_out", il);
  5431. }
  5432. cur = ggml_add(ctx0, cur, ffn_inp);
  5433. cb(cur, "l_out", il);
  5434. // input for next layer
  5435. inpL = cur;
  5436. }
  5437. cur = inpL;
  5438. cur = llm_build_norm(ctx0, cur, hparams,
  5439. model.output_norm, NULL,
  5440. LLM_NORM_RMS, cb, -1);
  5441. cb(cur, "result_norm", -1);
  5442. // lm_head
  5443. cur = ggml_mul_mat(ctx0, model.output, cur);
  5444. cb(cur, "result_output", -1);
  5445. ggml_build_forward_expand(gf, cur);
  5446. return gf;
  5447. }
  5448. struct ggml_cgraph * build_falcon() {
  5449. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5450. const int64_t n_embd_head = hparams.n_embd_head_v;
  5451. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5452. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5453. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5454. struct ggml_tensor * cur;
  5455. struct ggml_tensor * inpL;
  5456. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5457. // inp_pos - contains the positions
  5458. struct ggml_tensor * inp_pos = build_inp_pos();
  5459. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5460. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5461. for (int il = 0; il < n_layer; ++il) {
  5462. struct ggml_tensor * attn_norm;
  5463. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  5464. model.layers[il].attn_norm,
  5465. model.layers[il].attn_norm_b,
  5466. LLM_NORM, cb, il);
  5467. cb(attn_norm, "attn_norm", il);
  5468. // self-attention
  5469. {
  5470. if (model.layers[il].attn_norm_2) {
  5471. // Falcon-40B
  5472. cur = llm_build_norm(ctx0, inpL, hparams,
  5473. model.layers[il].attn_norm_2,
  5474. model.layers[il].attn_norm_2_b,
  5475. LLM_NORM, cb, il);
  5476. cb(cur, "attn_norm_2", il);
  5477. } else {
  5478. cur = attn_norm;
  5479. }
  5480. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5481. cb(cur, "wqkv", il);
  5482. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5483. 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)));
  5484. 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)));
  5485. cb(Qcur, "Qcur", il);
  5486. cb(Kcur, "Kcur", il);
  5487. cb(Vcur, "Vcur", il);
  5488. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5489. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  5490. // using mode = 2 for neox mode
  5491. Qcur = ggml_rope_custom(
  5492. ctx0, Qcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5493. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5494. );
  5495. cb(Qcur, "Qcur", il);
  5496. Kcur = ggml_rope_custom(
  5497. ctx0, Kcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5498. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5499. );
  5500. cb(Kcur, "Kcur", il);
  5501. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5502. model.layers[il].wo, NULL,
  5503. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5504. }
  5505. if (il == n_layer - 1) {
  5506. // skip computing output for unused tokens
  5507. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  5508. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  5509. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  5510. attn_norm = ggml_get_rows(ctx0, attn_norm, inp_out_ids);
  5511. }
  5512. struct ggml_tensor * ffn_inp = cur;
  5513. // feed forward
  5514. {
  5515. cur = llm_build_ffn(ctx0, attn_norm, // !! use the attn norm, not the result
  5516. model.layers[il].ffn_up, NULL,
  5517. NULL, NULL,
  5518. model.layers[il].ffn_down, NULL,
  5519. NULL,
  5520. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5521. cb(cur, "ffn_out", il);
  5522. }
  5523. cur = ggml_add(ctx0, cur, ffn_inp);
  5524. cb(cur, "l_out", il);
  5525. cur = ggml_add(ctx0, cur, inpL);
  5526. cb(cur, "l_out", il);
  5527. // input for next layer
  5528. inpL = cur;
  5529. }
  5530. cur = inpL;
  5531. // norm
  5532. cur = llm_build_norm(ctx0, cur, hparams,
  5533. model.output_norm,
  5534. model.output_norm_b,
  5535. LLM_NORM, cb, -1);
  5536. cb(cur, "result_norm", -1);
  5537. cur = ggml_mul_mat(ctx0, model.output, cur);
  5538. cb(cur, "result_output", -1);
  5539. ggml_build_forward_expand(gf, cur);
  5540. return gf;
  5541. }
  5542. struct ggml_cgraph * build_grok() {
  5543. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5544. // mutable variable, needed during the last layer of the computation to skip unused tokens
  5545. int32_t n_tokens = this->n_tokens;
  5546. const int64_t n_embd_head = hparams.n_embd_head_v;
  5547. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5548. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5549. struct ggml_tensor * cur;
  5550. struct ggml_tensor * inpL;
  5551. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5552. // multiply by embedding_multiplier_scale of 78.38367176906169
  5553. inpL = ggml_scale(ctx0, inpL, 78.38367176906169f);
  5554. // inp_pos - contains the positions
  5555. struct ggml_tensor * inp_pos = build_inp_pos();
  5556. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5557. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5558. for (int il = 0; il < n_layer; ++il) {
  5559. struct ggml_tensor * inpSA = inpL;
  5560. // norm
  5561. cur = llm_build_norm(ctx0, inpL, hparams,
  5562. model.layers[il].attn_norm, NULL,
  5563. LLM_NORM_RMS, cb, il);
  5564. cb(cur, "attn_norm", il);
  5565. // self-attention
  5566. {
  5567. // compute Q and K and RoPE them
  5568. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5569. cb(Qcur, "Qcur", il);
  5570. if (model.layers[il].bq) {
  5571. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5572. cb(Qcur, "Qcur", il);
  5573. }
  5574. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5575. cb(Kcur, "Kcur", il);
  5576. if (model.layers[il].bk) {
  5577. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5578. cb(Kcur, "Kcur", il);
  5579. }
  5580. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5581. cb(Vcur, "Vcur", il);
  5582. if (model.layers[il].bv) {
  5583. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  5584. cb(Vcur, "Vcur", il);
  5585. }
  5586. Qcur = ggml_rope_custom(
  5587. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5588. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5589. ext_factor, attn_factor, beta_fast, beta_slow
  5590. );
  5591. cb(Qcur, "Qcur", il);
  5592. Kcur = ggml_rope_custom(
  5593. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5594. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5595. ext_factor, attn_factor, beta_fast, beta_slow
  5596. );
  5597. cb(Kcur, "Kcur", il);
  5598. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5599. model.layers[il].wo, model.layers[il].bo,
  5600. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  5601. }
  5602. if (il == n_layer - 1) {
  5603. // skip computing output for unused tokens
  5604. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  5605. n_tokens = n_outputs;
  5606. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  5607. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  5608. }
  5609. // Grok
  5610. // if attn_out_norm is present then apply it before adding the input
  5611. if (model.layers[il].attn_out_norm) {
  5612. cur = llm_build_norm(ctx0, cur, hparams,
  5613. model.layers[il].attn_out_norm, NULL,
  5614. LLM_NORM_RMS, cb, il);
  5615. cb(cur, "attn_out_norm", il);
  5616. }
  5617. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5618. cb(ffn_inp, "ffn_inp", il);
  5619. // feed-forward network
  5620. // MoE branch
  5621. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5622. model.layers[il].ffn_norm, NULL,
  5623. LLM_NORM_RMS, cb, il);
  5624. cb(cur, "ffn_norm", il);
  5625. ggml_tensor * logits = ggml_mul_mat(ctx0, model.layers[il].ffn_gate_inp, cur); // [n_tokens, num_experts]
  5626. cb(logits, "ffn_moe_logits", il);
  5627. ggml_tensor * probs = ggml_soft_max(ctx0, logits); // [n_tokens, num_experts]
  5628. cb(probs, "ffn_moe_probs", il);
  5629. // select experts
  5630. ggml_tensor * selected_experts = ggml_top_k(ctx0, probs, n_expert_used); // [n_tokens, num_experts_per_tok]
  5631. cb(selected_experts->src[0], "ffn_moe_argsort", il);
  5632. ggml_tensor * weights = ggml_get_rows(ctx0,
  5633. ggml_reshape_3d(ctx0, probs, 1, n_expert, n_tokens), selected_experts);
  5634. cb(weights, "ffn_moe_weights", il);
  5635. weights = ggml_reshape_2d(ctx0, weights, n_expert_used, n_tokens); // [n_tokens, num_experts_per_tok]
  5636. ggml_tensor * weights_sum = ggml_sum_rows(ctx0, weights);
  5637. cb(weights_sum, "ffn_moe_weights_sum", il);
  5638. weights = ggml_div(ctx0, weights, weights_sum); // [n_tokens, num_experts_per_tok]
  5639. cb(weights, "ffn_moe_weights_norm", il);
  5640. // compute expert outputs
  5641. ggml_tensor * moe_out = nullptr;
  5642. for (int i = 0; i < n_expert_used; ++i) {
  5643. ggml_tensor * cur_expert;
  5644. ggml_tensor * cur_up = ggml_mul_mat_id(ctx0, model.layers[il].ffn_up_exp, n_expert, selected_experts, i, cur);
  5645. cb(cur_up, "ffn_moe_up", il);
  5646. ggml_tensor * cur_gate = ggml_mul_mat_id(ctx0, model.layers[il].ffn_gate_exp, n_expert, selected_experts, i, cur);
  5647. cb(cur_gate, "ffn_moe_gate", il);
  5648. //GeLU
  5649. cur_gate = ggml_gelu(ctx0, cur_gate);
  5650. cb(cur_gate, "ffn_moe_gelu", il);
  5651. cur_expert = ggml_mul(ctx0, cur_up, cur_gate); // [n_tokens, n_embd]
  5652. cb(cur_expert, "ffn_moe_gate_par", il);
  5653. cur_expert = ggml_mul_mat_id(ctx0, model.layers[il].ffn_down_exp, n_expert, selected_experts, i, cur_expert); // [n_tokens, n_embd]
  5654. cb(cur_expert, "ffn_moe_down", il);
  5655. cur_expert = ggml_mul(ctx0, cur_expert,
  5656. ggml_view_2d(ctx0, weights, 1, n_tokens, weights->nb[1], i*weights->nb[0]));
  5657. cb(cur_expert, "ffn_moe_weighted", il);
  5658. if (i == 0) {
  5659. moe_out = cur_expert;
  5660. } else {
  5661. moe_out = ggml_add(ctx0, moe_out, cur_expert);
  5662. cb(moe_out, "ffn_moe_out", il);
  5663. }
  5664. }
  5665. cur = moe_out;
  5666. // Grok
  5667. // if layer_out_norm is present then apply it before adding the input
  5668. // Idea: maybe ffn_out_norm is a better name
  5669. if (model.layers[il].layer_out_norm) {
  5670. cur = llm_build_norm(ctx0, cur, hparams,
  5671. model.layers[il].layer_out_norm, NULL,
  5672. LLM_NORM_RMS, cb, il);
  5673. cb(cur, "layer_out_norm", il);
  5674. }
  5675. cur = ggml_add(ctx0, cur, ffn_inp);
  5676. cb(cur, "ffn_out", il);
  5677. ggml_tensor * layer_dir = lctx.cvec.tensor_for(il);
  5678. if (layer_dir != nullptr) {
  5679. cur = ggml_add(ctx0, cur, layer_dir);
  5680. }
  5681. cb(cur, "l_out", il);
  5682. // input for next layer
  5683. inpL = cur;
  5684. }
  5685. cur = inpL;
  5686. cur = llm_build_norm(ctx0, cur, hparams,
  5687. model.output_norm, NULL,
  5688. LLM_NORM_RMS, cb, -1);
  5689. cb(cur, "result_norm", -1);
  5690. // lm_head
  5691. cur = ggml_mul_mat(ctx0, model.output, cur);
  5692. // Grok
  5693. // multiply logits by output_multiplier_scale of 0.5773502691896257
  5694. cur = ggml_scale(ctx0, cur, 0.5773502691896257f);
  5695. cb(cur, "result_output", -1);
  5696. ggml_build_forward_expand(gf, cur);
  5697. return gf;
  5698. }
  5699. struct ggml_cgraph * build_starcoder() {
  5700. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5701. const int64_t n_embd_head = hparams.n_embd_head_v;
  5702. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5703. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5704. struct ggml_tensor * cur;
  5705. struct ggml_tensor * inpL;
  5706. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5707. // inp_pos - contains the positions
  5708. struct ggml_tensor * inp_pos = build_inp_pos();
  5709. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5710. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5711. struct ggml_tensor * pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  5712. cb(pos, "pos_embd", -1);
  5713. inpL = ggml_add(ctx0, inpL, pos);
  5714. cb(inpL, "inpL", -1);
  5715. for (int il = 0; il < n_layer; ++il) {
  5716. cur = llm_build_norm(ctx0, inpL, hparams,
  5717. model.layers[il].attn_norm,
  5718. model.layers[il].attn_norm_b,
  5719. LLM_NORM, cb, il);
  5720. cb(cur, "attn_norm", il);
  5721. // self-attention
  5722. {
  5723. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5724. cb(cur, "wqkv", il);
  5725. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5726. cb(cur, "bqkv", il);
  5727. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5728. 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)));
  5729. 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)));
  5730. cb(Qcur, "Qcur", il);
  5731. cb(Kcur, "Kcur", il);
  5732. cb(Vcur, "Vcur", il);
  5733. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5734. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5735. model.layers[il].wo, model.layers[il].bo,
  5736. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5737. }
  5738. if (il == n_layer - 1) {
  5739. // skip computing output for unused tokens
  5740. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  5741. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  5742. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  5743. }
  5744. // add the input
  5745. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5746. cb(ffn_inp, "ffn_inp", il);
  5747. // FF
  5748. {
  5749. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5750. model.layers[il].ffn_norm,
  5751. model.layers[il].ffn_norm_b,
  5752. LLM_NORM, cb, il);
  5753. cb(cur, "ffn_norm", il);
  5754. cur = llm_build_ffn(ctx0, cur,
  5755. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5756. NULL, NULL,
  5757. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5758. NULL,
  5759. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5760. cb(cur, "ffn_out", il);
  5761. }
  5762. inpL = ggml_add(ctx0, cur, ffn_inp);
  5763. cb(inpL, "l_out", il);
  5764. }
  5765. cur = llm_build_norm(ctx0, inpL, hparams,
  5766. model.output_norm,
  5767. model.output_norm_b,
  5768. LLM_NORM, cb, -1);
  5769. cb(cur, "result_norm", -1);
  5770. cur = ggml_mul_mat(ctx0, model.output, cur);
  5771. cb(cur, "result_output", -1);
  5772. ggml_build_forward_expand(gf, cur);
  5773. return gf;
  5774. }
  5775. struct ggml_cgraph * build_persimmon() {
  5776. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5777. const int64_t n_embd_head = hparams.n_embd_head_v;
  5778. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5779. GGML_ASSERT(n_embd_head/2 == hparams.n_rot);
  5780. struct ggml_tensor * cur;
  5781. struct ggml_tensor * inpL;
  5782. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5783. // inp_pos - contains the positions
  5784. struct ggml_tensor * inp_pos = build_inp_pos();
  5785. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5786. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5787. for (int il = 0; il < n_layer; ++il) {
  5788. struct ggml_tensor * residual = inpL;
  5789. cur = llm_build_norm(ctx0, inpL, hparams,
  5790. model.layers[il].attn_norm,
  5791. model.layers[il].attn_norm_b,
  5792. LLM_NORM, cb, il);
  5793. cb(cur, "attn_norm", il);
  5794. // self attention
  5795. {
  5796. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5797. cb(cur, "wqkv", il);
  5798. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5799. cb(cur, "bqkv", il);
  5800. // split qkv
  5801. GGML_ASSERT(n_head_kv == n_head);
  5802. struct ggml_tensor * tmpqkv = ggml_reshape_4d(ctx0, cur, n_embd_head, 3, n_head, n_tokens);
  5803. cb(tmpqkv, "tmpqkv", il);
  5804. struct ggml_tensor * tmpqkv_perm = ggml_cont(ctx0, ggml_permute(ctx0, tmpqkv, 0, 3, 1, 2));
  5805. cb(tmpqkv_perm, "tmpqkv", il);
  5806. struct ggml_tensor * tmpq = ggml_view_3d(
  5807. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  5808. ggml_element_size(tmpqkv_perm) * n_embd_head,
  5809. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  5810. 0
  5811. );
  5812. cb(tmpq, "tmpq", il);
  5813. struct ggml_tensor * tmpk = ggml_view_3d(
  5814. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  5815. ggml_element_size(tmpqkv_perm) * n_embd_head,
  5816. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  5817. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens
  5818. );
  5819. cb(tmpk, "tmpk", il);
  5820. // Q/K Layernorm
  5821. tmpq = llm_build_norm(ctx0, tmpq, hparams,
  5822. model.layers[il].attn_q_norm,
  5823. model.layers[il].attn_q_norm_b,
  5824. LLM_NORM, cb, il);
  5825. cb(tmpq, "tmpq", il);
  5826. tmpk = llm_build_norm(ctx0, tmpk, hparams,
  5827. model.layers[il].attn_k_norm,
  5828. model.layers[il].attn_k_norm_b,
  5829. LLM_NORM, cb, il);
  5830. cb(tmpk, "tmpk", il);
  5831. // RoPE the first n_rot of q/k, pass the other half, and concat.
  5832. struct ggml_tensor * qrot = ggml_view_3d(
  5833. ctx0, tmpq, n_rot, n_head, n_tokens,
  5834. ggml_element_size(tmpq) * n_embd_head,
  5835. ggml_element_size(tmpq) * n_embd_head * n_head,
  5836. 0
  5837. );
  5838. cb(qrot, "qrot", il);
  5839. struct ggml_tensor * krot = ggml_view_3d(
  5840. ctx0, tmpk, n_rot, n_head, n_tokens,
  5841. ggml_element_size(tmpk) * n_embd_head,
  5842. ggml_element_size(tmpk) * n_embd_head * n_head,
  5843. 0
  5844. );
  5845. cb(krot, "krot", il);
  5846. // get the second half of tmpq, e.g tmpq[n_rot:, :, :]
  5847. struct ggml_tensor * qpass = ggml_view_3d(
  5848. ctx0, tmpq, n_rot, n_head, n_tokens,
  5849. ggml_element_size(tmpq) * n_embd_head,
  5850. ggml_element_size(tmpq) * n_embd_head * n_head,
  5851. ggml_element_size(tmpq) * n_rot
  5852. );
  5853. cb(qpass, "qpass", il);
  5854. struct ggml_tensor * kpass = ggml_view_3d(
  5855. ctx0, tmpk, n_rot, n_head, n_tokens,
  5856. ggml_element_size(tmpk) * n_embd_head,
  5857. ggml_element_size(tmpk) * n_embd_head * n_head,
  5858. ggml_element_size(tmpk) * n_rot
  5859. );
  5860. cb(kpass, "kpass", il);
  5861. struct ggml_tensor * qrotated = ggml_rope_custom(
  5862. ctx0, qrot, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5863. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5864. );
  5865. cb(qrotated, "qrotated", il);
  5866. struct ggml_tensor * krotated = ggml_rope_custom(
  5867. ctx0, krot, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5868. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5869. );
  5870. cb(krotated, "krotated", il);
  5871. // ggml currently only supports concatenation on dim=2
  5872. // so we need to permute qrot, qpass, concat, then permute back.
  5873. qrotated = ggml_cont(ctx0, ggml_permute(ctx0, qrotated, 2, 1, 0, 3));
  5874. cb(qrotated, "qrotated", il);
  5875. krotated = ggml_cont(ctx0, ggml_permute(ctx0, krotated, 2, 1, 0, 3));
  5876. cb(krotated, "krotated", il);
  5877. qpass = ggml_cont(ctx0, ggml_permute(ctx0, qpass, 2, 1, 0, 3));
  5878. cb(qpass, "qpass", il);
  5879. kpass = ggml_cont(ctx0, ggml_permute(ctx0, kpass, 2, 1, 0, 3));
  5880. cb(kpass, "kpass", il);
  5881. struct ggml_tensor * Qcur = ggml_concat(ctx0, qrotated, qpass);
  5882. cb(Qcur, "Qcur", il);
  5883. struct ggml_tensor * Kcur = ggml_concat(ctx0, krotated, kpass);
  5884. cb(Kcur, "Kcur", il);
  5885. struct ggml_tensor * Q = ggml_cont(ctx0, ggml_permute(ctx0, Qcur, 2, 1, 0, 3));
  5886. cb(Q, "Q", il);
  5887. Kcur = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 2, 1, 0, 3));
  5888. cb(Kcur, "Kcur", il);
  5889. struct ggml_tensor * Vcur = ggml_view_3d(
  5890. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  5891. ggml_element_size(tmpqkv_perm) * n_embd_head,
  5892. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  5893. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens * 2
  5894. );
  5895. cb(Vcur, "Vcur", il);
  5896. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5897. model.layers[il].wo, model.layers[il].bo,
  5898. Kcur, Vcur, Q, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5899. }
  5900. if (il == n_layer - 1) {
  5901. // skip computing output for unused tokens
  5902. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  5903. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  5904. residual = ggml_get_rows(ctx0, residual, inp_out_ids);
  5905. }
  5906. struct ggml_tensor * ffn_inp = ggml_add(ctx0, residual, cur);
  5907. cb(ffn_inp, "ffn_inp", il);
  5908. // feed-forward network
  5909. {
  5910. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5911. model.layers[il].ffn_norm,
  5912. model.layers[il].ffn_norm_b,
  5913. LLM_NORM, cb, il);
  5914. cb(cur, "ffn_norm", il);
  5915. cur = llm_build_ffn(ctx0, cur,
  5916. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5917. NULL, NULL,
  5918. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5919. NULL,
  5920. LLM_FFN_RELU_SQR, LLM_FFN_SEQ, cb, il);
  5921. cb(cur, "ffn_out", il);
  5922. }
  5923. cur = ggml_add(ctx0, cur, ffn_inp);
  5924. cb(cur, "l_out", il);
  5925. inpL = cur;
  5926. }
  5927. cur = inpL;
  5928. cur = llm_build_norm(ctx0, cur, hparams,
  5929. model.output_norm,
  5930. model.output_norm_b,
  5931. LLM_NORM, cb, -1);
  5932. cb(cur, "result_norm", -1);
  5933. cur = ggml_mul_mat(ctx0, model.output, cur);
  5934. cb(cur, "result_output", -1);
  5935. ggml_build_forward_expand(gf, cur);
  5936. return gf;
  5937. }
  5938. struct ggml_cgraph * build_refact() {
  5939. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5940. const int64_t n_embd_head = hparams.n_embd_head_v;
  5941. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5942. struct ggml_tensor * cur;
  5943. struct ggml_tensor * inpL;
  5944. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5945. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5946. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5947. // positions of the tokens in the KV cache
  5948. struct ggml_tensor * KQ_pos = build_inp_KQ_pos();
  5949. for (int il = 0; il < n_layer; ++il) {
  5950. struct ggml_tensor * inpSA = inpL;
  5951. cur = llm_build_norm(ctx0, inpL, hparams,
  5952. model.layers[il].attn_norm, NULL,
  5953. LLM_NORM_RMS, cb, il);
  5954. cb(cur, "attn_norm", il);
  5955. // self-attention
  5956. {
  5957. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5958. cb(Qcur, "Qcur", il);
  5959. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5960. cb(Kcur, "Kcur", il);
  5961. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5962. cb(Vcur, "Vcur", il);
  5963. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  5964. cb(Kcur, "Kcur", il);
  5965. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5966. cb(Qcur, "Qcur", il);
  5967. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5968. model.layers[il].wo, NULL,
  5969. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5970. }
  5971. if (il == n_layer - 1) {
  5972. // skip computing output for unused tokens
  5973. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  5974. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  5975. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  5976. }
  5977. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5978. cb(ffn_inp, "ffn_inp", il);
  5979. // feed-forward network
  5980. {
  5981. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5982. model.layers[il].ffn_norm, NULL,
  5983. LLM_NORM_RMS, cb, il);
  5984. cb(cur, "ffn_norm", il);
  5985. cur = llm_build_ffn(ctx0, cur,
  5986. model.layers[il].ffn_up, NULL,
  5987. model.layers[il].ffn_gate, NULL,
  5988. model.layers[il].ffn_down, NULL,
  5989. NULL,
  5990. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5991. cb(cur, "ffn_out", il);
  5992. }
  5993. cur = ggml_add(ctx0, cur, ffn_inp);
  5994. cb(cur, "l_out", il);
  5995. // input for next layer
  5996. inpL = cur;
  5997. }
  5998. cur = inpL;
  5999. cur = llm_build_norm(ctx0, cur, hparams,
  6000. model.output_norm, NULL,
  6001. LLM_NORM_RMS, cb, -1);
  6002. cb(cur, "result_norm", -1);
  6003. // lm_head
  6004. cur = ggml_mul_mat(ctx0, model.output, cur);
  6005. cb(cur, "result_output", -1);
  6006. ggml_build_forward_expand(gf, cur);
  6007. return gf;
  6008. }
  6009. struct ggml_cgraph * build_bert() {
  6010. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6011. const int64_t n_embd_head = hparams.n_embd_head_v;
  6012. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  6013. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6014. struct ggml_tensor * cur;
  6015. struct ggml_tensor * inpL;
  6016. struct ggml_tensor * inp_pos = build_inp_pos();
  6017. struct ggml_tensor * inp_mean = build_inp_mean();
  6018. struct ggml_tensor * inp_cls = build_inp_cls();
  6019. // construct input embeddings (token, type, position)
  6020. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6021. // token types are hardcoded to zero ("Sentence A")
  6022. struct ggml_tensor * type_row0 = ggml_view_1d(ctx0, model.type_embd, n_embd, 0);
  6023. inpL = ggml_add(ctx0, inpL, type_row0);
  6024. if (model.arch == LLM_ARCH_BERT) {
  6025. inpL = ggml_add(ctx0, ggml_get_rows(ctx0, model.pos_embd, inp_pos), inpL);
  6026. }
  6027. cb(inpL, "inp_embd", -1);
  6028. // embed layer norm
  6029. inpL = llm_build_norm(ctx0, inpL, hparams, model.tok_norm, model.tok_norm_b, LLM_NORM, cb, -1);
  6030. cb(inpL, "inp_norm", -1);
  6031. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6032. struct ggml_tensor * KQ_mask = build_inp_KQ_mask(false);
  6033. // iterate layers
  6034. for (int il = 0; il < n_layer; ++il) {
  6035. struct ggml_tensor * cur = inpL;
  6036. struct ggml_tensor * Qcur;
  6037. struct ggml_tensor * Kcur;
  6038. struct ggml_tensor * Vcur;
  6039. // self-attention
  6040. if (model.arch == LLM_ARCH_BERT) {
  6041. Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, cur), model.layers[il].bq);
  6042. cb(Qcur, "Qcur", il);
  6043. Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, cur), model.layers[il].bk);
  6044. cb(Kcur, "Kcur", il);
  6045. Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, cur), model.layers[il].bv);
  6046. cb(Vcur, "Vcur", il);
  6047. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6048. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  6049. } else {
  6050. // compute Q and K and RoPE them
  6051. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6052. cb(cur, "wqkv", il);
  6053. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6054. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  6055. 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)));
  6056. cb(Qcur, "Qcur", il);
  6057. cb(Kcur, "Kcur", il);
  6058. cb(Vcur, "Vcur", il);
  6059. Qcur = ggml_rope_custom(
  6060. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6061. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6062. ext_factor, attn_factor, beta_fast, beta_slow
  6063. );
  6064. cb(Qcur, "Qcur", il);
  6065. Kcur = ggml_rope_custom(
  6066. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6067. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6068. ext_factor, attn_factor, beta_fast, beta_slow
  6069. );
  6070. cb(Kcur, "Kcur", il);
  6071. }
  6072. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  6073. struct ggml_tensor * k = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 0, 2, 1, 3));
  6074. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  6075. cb(kq, "kq", il);
  6076. kq = ggml_soft_max_ext(ctx0, kq, KQ_mask, nullptr, 1.0f/sqrtf(float(n_embd_head)), hparams.f_max_alibi_bias);
  6077. cb(kq, "kq_soft_max_ext", il);
  6078. struct ggml_tensor * v = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_reshape_2d(ctx0, Vcur, n_embd_gqa, n_tokens)));
  6079. cb(v, "v", il);
  6080. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, ggml_reshape_3d(ctx0, v, n_tokens, n_embd_head, n_head_kv), kq);
  6081. cb(kqv, "kqv", il);
  6082. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  6083. cb(kqv_merged, "kqv_merged", il);
  6084. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  6085. cb(cur, "kqv_merged_cont", il);
  6086. ggml_build_forward_expand(gf, cur);
  6087. cur = ggml_mul_mat(ctx0, model.layers[il].wo, cur);
  6088. if (model.layers[il].bo) {
  6089. cb(cur, "kqv_wo", il);
  6090. }
  6091. if (model.layers[il].bo) {
  6092. cur = ggml_add(ctx0, cur, model.layers[il].bo);
  6093. }
  6094. cb(cur, "kqv_out", il);
  6095. if (il == n_layer - 1 && pooling_type == LLAMA_POOLING_TYPE_NONE) {
  6096. // skip computing output for unused tokens
  6097. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6098. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6099. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  6100. }
  6101. // re-add the layer input
  6102. cur = ggml_add(ctx0, cur, inpL);
  6103. // attention layer norm
  6104. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].attn_out_norm, model.layers[il].attn_out_norm_b, LLM_NORM, cb, il);
  6105. struct ggml_tensor * ffn_inp = cur;
  6106. cb(ffn_inp, "ffn_inp", il);
  6107. // feed-forward network
  6108. if (model.arch == LLM_ARCH_BERT) {
  6109. cur = llm_build_ffn(ctx0, cur,
  6110. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6111. NULL, NULL,
  6112. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6113. NULL,
  6114. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6115. } else {
  6116. cur = llm_build_ffn(ctx0, cur,
  6117. model.layers[il].ffn_up, NULL,
  6118. model.layers[il].ffn_gate, NULL,
  6119. model.layers[il].ffn_down, NULL,
  6120. NULL,
  6121. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6122. }
  6123. cb(cur, "ffn_out", il);
  6124. // attentions bypass the intermediate layer
  6125. cur = ggml_add(ctx0, cur, ffn_inp);
  6126. // output layer norm
  6127. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].layer_out_norm, model.layers[il].layer_out_norm_b, LLM_NORM, cb, il);
  6128. // input for next layer
  6129. inpL = cur;
  6130. }
  6131. // final output
  6132. cur = inpL;
  6133. cb(cur, "result_embd", -1);
  6134. // pooling layer
  6135. switch (pooling_type) {
  6136. case LLAMA_POOLING_TYPE_NONE:
  6137. {
  6138. // nop
  6139. } break;
  6140. case LLAMA_POOLING_TYPE_MEAN:
  6141. {
  6142. cur = ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, cur)), inp_mean);
  6143. cb(cur, "result_embd_pooled", -1);
  6144. } break;
  6145. case LLAMA_POOLING_TYPE_CLS:
  6146. {
  6147. cur = ggml_get_rows(ctx0, cur, inp_cls);
  6148. cb(cur, "result_embd_pooled", -1);
  6149. } break;
  6150. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  6151. {
  6152. GGML_ASSERT(false && "Invalid pooling type");
  6153. } break;
  6154. }
  6155. ggml_build_forward_expand(gf, cur);
  6156. return gf;
  6157. }
  6158. struct ggml_cgraph * build_bloom() {
  6159. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6160. const int64_t n_embd_head = hparams.n_embd_head_v;
  6161. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  6162. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6163. struct ggml_tensor * cur;
  6164. struct ggml_tensor * inpL;
  6165. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6166. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6167. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6168. // positions of the tokens in the KV cache
  6169. struct ggml_tensor * KQ_pos = build_inp_KQ_pos();
  6170. inpL = llm_build_norm(ctx0, inpL, hparams,
  6171. model.tok_norm,
  6172. model.tok_norm_b,
  6173. LLM_NORM, cb, -1);
  6174. cb(inpL, "inp_norm", -1);
  6175. for (int il = 0; il < n_layer; ++il) {
  6176. cur = llm_build_norm(ctx0, inpL, hparams,
  6177. model.layers[il].attn_norm,
  6178. model.layers[il].attn_norm_b,
  6179. LLM_NORM, cb, il);
  6180. cb(cur, "attn_norm", il);
  6181. // self-attention
  6182. {
  6183. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6184. cb(cur, "wqkv", il);
  6185. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6186. cb(cur, "bqkv", il);
  6187. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6188. 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)));
  6189. 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)));
  6190. cb(Qcur, "Qcur", il);
  6191. cb(Kcur, "Kcur", il);
  6192. cb(Vcur, "Vcur", il);
  6193. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6194. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6195. model.layers[il].wo, model.layers[il].bo,
  6196. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6197. }
  6198. if (il == n_layer - 1) {
  6199. // skip computing output for unused tokens
  6200. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6201. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6202. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  6203. }
  6204. // Add the input
  6205. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  6206. cb(ffn_inp, "ffn_inp", il);
  6207. // FF
  6208. {
  6209. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6210. model.layers[il].ffn_norm,
  6211. model.layers[il].ffn_norm_b,
  6212. LLM_NORM, cb, il);
  6213. cb(cur, "ffn_norm", il);
  6214. cur = llm_build_ffn(ctx0, cur,
  6215. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6216. NULL, NULL,
  6217. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6218. NULL,
  6219. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6220. cb(cur, "ffn_out", il);
  6221. }
  6222. inpL = ggml_add(ctx0, cur, ffn_inp);
  6223. cb(inpL, "l_out", il);
  6224. }
  6225. cur = llm_build_norm(ctx0, inpL, hparams,
  6226. model.output_norm,
  6227. model.output_norm_b,
  6228. LLM_NORM, cb, -1);
  6229. cb(cur, "result_norm", -1);
  6230. cur = ggml_mul_mat(ctx0, model.output, cur);
  6231. cb(cur, "result_output", -1);
  6232. ggml_build_forward_expand(gf, cur);
  6233. return gf;
  6234. }
  6235. struct ggml_cgraph * build_mpt() {
  6236. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6237. const int64_t n_embd_head = hparams.n_embd_head_v;
  6238. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  6239. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6240. struct ggml_tensor * cur;
  6241. struct ggml_tensor * inpL;
  6242. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6243. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6244. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6245. // positions of the tokens in the KV cache
  6246. struct ggml_tensor * KQ_pos = build_inp_KQ_pos();
  6247. for (int il = 0; il < n_layer; ++il) {
  6248. struct ggml_tensor * attn_norm;
  6249. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  6250. model.layers[il].attn_norm,
  6251. model.layers[il].attn_norm_b,
  6252. LLM_NORM, cb, il);
  6253. cb(attn_norm, "attn_norm", il);
  6254. // self-attention
  6255. {
  6256. cur = attn_norm;
  6257. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6258. cb(cur, "wqkv", il);
  6259. if (model.layers[il].bqkv){
  6260. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6261. cb(cur, "bqkv", il);
  6262. }
  6263. if (hparams.f_clamp_kqv > 0.0f) {
  6264. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  6265. cb(cur, "wqkv_clamped", il);
  6266. }
  6267. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6268. 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)));
  6269. 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)));
  6270. cb(Qcur, "Qcur", il);
  6271. cb(Kcur, "Kcur", il);
  6272. cb(Vcur, "Vcur", il);
  6273. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6274. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6275. model.layers[il].wo, model.layers[il].bo,
  6276. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6277. }
  6278. if (il == n_layer - 1) {
  6279. // skip computing output for unused tokens
  6280. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6281. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6282. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  6283. }
  6284. // Add the input
  6285. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  6286. cb(ffn_inp, "ffn_inp", il);
  6287. // feed forward
  6288. {
  6289. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6290. model.layers[il].ffn_norm,
  6291. model.layers[il].ffn_norm_b,
  6292. LLM_NORM, cb, il);
  6293. cb(cur, "ffn_norm", il);
  6294. cur = llm_build_ffn(ctx0, cur,
  6295. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6296. NULL, NULL,
  6297. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6298. model.layers[il].ffn_act,
  6299. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6300. cb(cur, "ffn_out", il);
  6301. }
  6302. cur = ggml_add(ctx0, cur, ffn_inp);
  6303. cb(cur, "l_out", il);
  6304. // input for next layer
  6305. inpL = cur;
  6306. }
  6307. cur = inpL;
  6308. cur = llm_build_norm(ctx0, cur, hparams,
  6309. model.output_norm,
  6310. model.output_norm_b,
  6311. LLM_NORM, cb, -1);
  6312. cb(cur, "result_norm", -1);
  6313. cur = ggml_mul_mat(ctx0, model.output, cur);
  6314. cb(cur, "result_output", -1);
  6315. ggml_build_forward_expand(gf, cur);
  6316. return gf;
  6317. }
  6318. struct ggml_cgraph * build_stablelm() {
  6319. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  6320. const int64_t n_embd_head = hparams.n_embd_head_v;
  6321. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6322. struct ggml_tensor * cur;
  6323. struct ggml_tensor * inpL;
  6324. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6325. // inp_pos - contains the positions
  6326. struct ggml_tensor * inp_pos = build_inp_pos();
  6327. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6328. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6329. for (int il = 0; il < n_layer; ++il) {
  6330. struct ggml_tensor * inpSA = inpL;
  6331. // norm
  6332. cur = llm_build_norm(ctx0, inpL, hparams,
  6333. model.layers[il].attn_norm,
  6334. model.layers[il].attn_norm_b,
  6335. LLM_NORM, cb, il);
  6336. cb(cur, "attn_norm", il);
  6337. // self-attention
  6338. {
  6339. // compute Q and K and RoPE them
  6340. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6341. cb(Qcur, "Qcur", il);
  6342. if (model.layers[il].bq) {
  6343. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6344. cb(Qcur, "Qcur", il);
  6345. }
  6346. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6347. cb(Kcur, "Kcur", il);
  6348. if (model.layers[il].bk) {
  6349. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6350. cb(Kcur, "Kcur", il);
  6351. }
  6352. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6353. cb(Vcur, "Vcur", il);
  6354. if (model.layers[il].bv) {
  6355. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6356. cb(Vcur, "Vcur", il);
  6357. }
  6358. Qcur = ggml_rope_custom(
  6359. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6360. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6361. ext_factor, attn_factor, beta_fast, beta_slow
  6362. );
  6363. cb(Qcur, "Qcur", il);
  6364. Kcur = ggml_rope_custom(
  6365. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6366. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6367. ext_factor, attn_factor, beta_fast, beta_slow
  6368. );
  6369. cb(Kcur, "Kcur", il);
  6370. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6371. model.layers[il].wo, NULL,
  6372. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6373. }
  6374. if (il == n_layer - 1) {
  6375. // skip computing output for unused tokens
  6376. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6377. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6378. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  6379. }
  6380. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6381. cb(ffn_inp, "ffn_inp", il);
  6382. // feed-forward network
  6383. {
  6384. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6385. model.layers[il].ffn_norm,
  6386. model.layers[il].ffn_norm_b,
  6387. LLM_NORM, cb, il);
  6388. cb(cur, "ffn_norm", il);
  6389. cur = llm_build_ffn(ctx0, cur,
  6390. model.layers[il].ffn_up, NULL,
  6391. model.layers[il].ffn_gate, NULL,
  6392. model.layers[il].ffn_down, NULL,
  6393. NULL,
  6394. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6395. cb(cur, "ffn_out", il);
  6396. }
  6397. cur = ggml_add(ctx0, cur, ffn_inp);
  6398. cb(cur, "l_out", il);
  6399. // input for next layer
  6400. inpL = cur;
  6401. }
  6402. cur = inpL;
  6403. cur = llm_build_norm(ctx0, cur, hparams,
  6404. model.output_norm,
  6405. model.output_norm_b,
  6406. LLM_NORM, cb, -1);
  6407. cb(cur, "result_norm", -1);
  6408. // lm_head
  6409. cur = ggml_mul_mat(ctx0, model.output, cur);
  6410. cb(cur, "result_output", -1);
  6411. ggml_build_forward_expand(gf, cur);
  6412. return gf;
  6413. }
  6414. struct ggml_cgraph * build_qwen() {
  6415. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6416. const int64_t n_embd_head = hparams.n_embd_head_v;
  6417. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6418. struct ggml_tensor * cur;
  6419. struct ggml_tensor * inpL;
  6420. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6421. // inp_pos - contains the positions
  6422. struct ggml_tensor * inp_pos = build_inp_pos();
  6423. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6424. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6425. for (int il = 0; il < n_layer; ++il) {
  6426. struct ggml_tensor * inpSA = inpL;
  6427. cur = llm_build_norm(ctx0, inpL, hparams,
  6428. model.layers[il].attn_norm, NULL,
  6429. LLM_NORM_RMS, cb, il);
  6430. cb(cur, "attn_norm", il);
  6431. // self-attention
  6432. {
  6433. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6434. cb(cur, "wqkv", il);
  6435. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6436. cb(cur, "bqkv", il);
  6437. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6438. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  6439. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 2*sizeof(float)*(n_embd)));
  6440. cb(Qcur, "Qcur", il);
  6441. cb(Kcur, "Kcur", il);
  6442. cb(Vcur, "Vcur", il);
  6443. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6444. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  6445. // using mode = 2 for neox mode
  6446. Qcur = ggml_rope_custom(
  6447. ctx0, Qcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  6448. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  6449. );
  6450. cb(Qcur, "Qcur", il);
  6451. Kcur = ggml_rope_custom(
  6452. ctx0, Kcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  6453. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  6454. );
  6455. cb(Kcur, "Kcur", il);
  6456. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6457. model.layers[il].wo, NULL,
  6458. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6459. }
  6460. if (il == n_layer - 1) {
  6461. // skip computing output for unused tokens
  6462. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6463. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6464. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  6465. }
  6466. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6467. cb(ffn_inp, "ffn_inp", il);
  6468. // feed-forward forward
  6469. {
  6470. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6471. model.layers[il].ffn_norm, NULL,
  6472. LLM_NORM_RMS, cb, il);
  6473. cb(cur, "ffn_norm", il);
  6474. cur = llm_build_ffn(ctx0, cur,
  6475. model.layers[il].ffn_up, NULL,
  6476. model.layers[il].ffn_gate, NULL,
  6477. model.layers[il].ffn_down, NULL,
  6478. NULL,
  6479. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6480. cb(cur, "ffn_out", il);
  6481. }
  6482. cur = ggml_add(ctx0, cur, ffn_inp);
  6483. cb(cur, "l_out", il);
  6484. // input for next layer
  6485. inpL = cur;
  6486. }
  6487. cur = inpL;
  6488. cur = llm_build_norm(ctx0, cur, hparams,
  6489. model.output_norm, NULL,
  6490. LLM_NORM_RMS, cb, -1);
  6491. cb(cur, "result_norm", -1);
  6492. // lm_head
  6493. cur = ggml_mul_mat(ctx0, model.output, cur);
  6494. cb(cur, "result_output", -1);
  6495. ggml_build_forward_expand(gf, cur);
  6496. return gf;
  6497. }
  6498. struct ggml_cgraph * build_qwen2() {
  6499. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6500. const int64_t n_embd_head = hparams.n_embd_head_v;
  6501. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6502. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6503. struct ggml_tensor * cur;
  6504. struct ggml_tensor * inpL;
  6505. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6506. // inp_pos - contains the positions
  6507. struct ggml_tensor * inp_pos = build_inp_pos();
  6508. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6509. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6510. for (int il = 0; il < n_layer; ++il) {
  6511. struct ggml_tensor * inpSA = inpL;
  6512. // norm
  6513. cur = llm_build_norm(ctx0, inpL, hparams,
  6514. model.layers[il].attn_norm, NULL,
  6515. LLM_NORM_RMS, cb, il);
  6516. cb(cur, "attn_norm", il);
  6517. // self-attention
  6518. {
  6519. // compute Q and K and RoPE them
  6520. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6521. cb(Qcur, "Qcur", il);
  6522. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6523. cb(Qcur, "Qcur", il);
  6524. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6525. cb(Kcur, "Kcur", il);
  6526. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6527. cb(Kcur, "Kcur", il);
  6528. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6529. cb(Vcur, "Vcur", il);
  6530. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6531. cb(Vcur, "Vcur", il);
  6532. // these nodes are added to the graph together so that they are not reordered
  6533. // by doing so, the number of splits in the graph is reduced
  6534. ggml_build_forward_expand(gf, Qcur);
  6535. ggml_build_forward_expand(gf, Kcur);
  6536. ggml_build_forward_expand(gf, Vcur);
  6537. Qcur = ggml_rope_custom(
  6538. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6539. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6540. ext_factor, attn_factor, beta_fast, beta_slow
  6541. );
  6542. cb(Qcur, "Qcur", il);
  6543. Kcur = ggml_rope_custom(
  6544. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6545. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6546. ext_factor, attn_factor, beta_fast, beta_slow
  6547. );
  6548. cb(Kcur, "Kcur", il);
  6549. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6550. model.layers[il].wo, model.layers[il].bo,
  6551. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6552. }
  6553. if (il == n_layer - 1) {
  6554. // skip computing output for unused tokens
  6555. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6556. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6557. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  6558. }
  6559. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6560. cb(ffn_inp, "ffn_inp", il);
  6561. // feed-forward network
  6562. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6563. model.layers[il].ffn_norm, NULL,
  6564. LLM_NORM_RMS, cb, il);
  6565. cb(cur, "ffn_norm", il);
  6566. cur = llm_build_ffn(ctx0, cur,
  6567. model.layers[il].ffn_up, NULL,
  6568. model.layers[il].ffn_gate, NULL,
  6569. model.layers[il].ffn_down, NULL,
  6570. NULL,
  6571. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6572. cb(cur, "ffn_out", il);
  6573. cur = ggml_add(ctx0, cur, ffn_inp);
  6574. cb(cur, "l_out", il);
  6575. // input for next layer
  6576. inpL = cur;
  6577. }
  6578. cur = inpL;
  6579. cur = llm_build_norm(ctx0, cur, hparams,
  6580. model.output_norm, NULL,
  6581. LLM_NORM_RMS, cb, -1);
  6582. cb(cur, "result_norm", -1);
  6583. // lm_head
  6584. cur = ggml_mul_mat(ctx0, model.output, cur);
  6585. cb(cur, "result_output", -1);
  6586. ggml_build_forward_expand(gf, cur);
  6587. return gf;
  6588. }
  6589. struct ggml_cgraph * build_phi2() {
  6590. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6591. const int64_t n_embd_head = hparams.n_embd_head_v;
  6592. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  6593. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6594. struct ggml_tensor * cur;
  6595. struct ggml_tensor * attn_norm_output;
  6596. struct ggml_tensor * ffn_output;
  6597. struct ggml_tensor * inpL;
  6598. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6599. // inp_pos - contains the positions
  6600. struct ggml_tensor * inp_pos = build_inp_pos();
  6601. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6602. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6603. for (int il = 0; il < n_layer; ++il) {
  6604. attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  6605. model.layers[il].attn_norm,
  6606. model.layers[il].attn_norm_b,
  6607. LLM_NORM, cb, il);
  6608. cb(attn_norm_output, "attn_norm", il);
  6609. // self-attention
  6610. {
  6611. struct ggml_tensor * Qcur = nullptr;
  6612. struct ggml_tensor * Kcur = nullptr;
  6613. struct ggml_tensor * Vcur = nullptr;
  6614. if (model.layers[il].wqkv) {
  6615. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, attn_norm_output);
  6616. cb(cur, "wqkv", il);
  6617. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6618. cb(cur, "bqkv", il);
  6619. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6620. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  6621. 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)));
  6622. } else {
  6623. Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  6624. Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  6625. Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  6626. }
  6627. cb(Qcur, "Qcur", il);
  6628. cb(Kcur, "Kcur", il);
  6629. cb(Vcur, "Vcur", il);
  6630. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6631. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  6632. Qcur = ggml_rope_custom(
  6633. ctx0, Qcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  6634. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  6635. );
  6636. cb(Qcur, "Qcur", il);
  6637. // with phi2, we scale the Q to avoid precision issues
  6638. // ref: https://github.com/ml-explore/mlx-examples/blob/08e862336ade809bc37d1035f94b359e7d1a5152/phi2/phi2.py#L64-L66
  6639. Qcur = ggml_scale(ctx0, Qcur, 1.0f/sqrtf(float(n_embd_head)));
  6640. cb(Qcur, "Qcur", il);
  6641. Kcur = ggml_rope_custom(
  6642. ctx0, Kcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  6643. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  6644. );
  6645. cb(Kcur, "Kcur", il);
  6646. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6647. model.layers[il].wo, model.layers[il].bo,
  6648. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  6649. }
  6650. if (il == n_layer - 1) {
  6651. // skip computing output for unused tokens
  6652. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6653. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6654. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  6655. attn_norm_output = ggml_get_rows(ctx0, attn_norm_output, inp_out_ids);
  6656. }
  6657. // FF
  6658. {
  6659. ffn_output = llm_build_ffn(ctx0, attn_norm_output,
  6660. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6661. NULL, NULL,
  6662. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6663. NULL,
  6664. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6665. cb(ffn_output, "ffn_out", il);
  6666. }
  6667. cur = ggml_add(ctx0, cur, ffn_output);
  6668. cb(cur, "l_out", il);
  6669. cur = ggml_add(ctx0, cur, inpL);
  6670. cb(cur, "l_out", il);
  6671. inpL = cur;
  6672. }
  6673. cur = llm_build_norm(ctx0, inpL, hparams,
  6674. model.output_norm,
  6675. model.output_norm_b,
  6676. LLM_NORM, cb, -1);
  6677. cb(cur, "result_norm", -1);
  6678. cur = ggml_mul_mat(ctx0, model.output, cur);
  6679. cb(cur, "result_output_no_bias", -1);
  6680. cur = ggml_add(ctx0, cur, model.output_b);
  6681. cb(cur, "result_output", -1);
  6682. ggml_build_forward_expand(gf, cur);
  6683. return gf;
  6684. }
  6685. struct ggml_cgraph * build_plamo() {
  6686. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  6687. const int64_t n_embd_head = hparams.n_embd_head_v;
  6688. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6689. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6690. struct ggml_tensor * cur;
  6691. struct ggml_tensor * inpL;
  6692. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6693. // inp_pos - contains the positions
  6694. struct ggml_tensor * inp_pos = build_inp_pos();
  6695. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6696. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6697. for (int il = 0; il < n_layer; ++il) {
  6698. // norm
  6699. cur = llm_build_norm(ctx0, inpL, hparams,
  6700. model.layers[il].attn_norm, NULL,
  6701. LLM_NORM_RMS, cb, il);
  6702. cb(cur, "attn_norm", il);
  6703. struct ggml_tensor * attention_norm = cur;
  6704. // self-attention
  6705. {
  6706. // compute Q and K and RoPE them
  6707. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6708. cb(Qcur, "Qcur", il);
  6709. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6710. cb(Kcur, "Kcur", il);
  6711. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6712. cb(Vcur, "Vcur", il);
  6713. Qcur = ggml_rope_custom(
  6714. ctx0, ggml_reshape_3d(ctx0, Qcur, n_rot, n_head, n_tokens), inp_pos,
  6715. n_embd_head, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6716. ext_factor, attn_factor, beta_fast, beta_slow);
  6717. cb(Qcur, "Qcur", il);
  6718. Kcur = ggml_rope_custom(
  6719. ctx0, ggml_reshape_3d(ctx0, Kcur, n_rot, n_head_kv, n_tokens), inp_pos,
  6720. n_embd_head, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6721. ext_factor, attn_factor, beta_fast, beta_slow);
  6722. cb(Kcur, "Kcur", il);
  6723. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6724. model.layers[il].wo, NULL,
  6725. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6726. }
  6727. struct ggml_tensor * sa_out = cur;
  6728. cur = attention_norm;
  6729. if (il == n_layer - 1) {
  6730. // skip computing output for unused tokens
  6731. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6732. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6733. sa_out = ggml_get_rows(ctx0, sa_out, inp_out_ids);
  6734. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  6735. }
  6736. // feed-forward network
  6737. {
  6738. cur = llm_build_ffn(ctx0, cur,
  6739. model.layers[il].ffn_up, NULL,
  6740. model.layers[il].ffn_gate, NULL,
  6741. model.layers[il].ffn_down, NULL,
  6742. NULL,
  6743. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6744. cb(cur, "ffn_out", il);
  6745. }
  6746. cur = ggml_add(ctx0, cur, sa_out);
  6747. cb(cur, "l_out", il);
  6748. cur = ggml_add(ctx0, cur, inpL);
  6749. cb(cur, "l_out", il);
  6750. // input for next layer
  6751. inpL = cur;
  6752. }
  6753. cur = inpL;
  6754. cur = llm_build_norm(ctx0, cur, hparams,
  6755. model.output_norm, NULL,
  6756. LLM_NORM_RMS, cb, -1);
  6757. cb(cur, "result_norm", -1);
  6758. // lm_head
  6759. cur = ggml_mul_mat(ctx0, model.output, cur);
  6760. cb(cur, "result_output", -1);
  6761. ggml_build_forward_expand(gf, cur);
  6762. return gf;
  6763. }
  6764. struct ggml_cgraph * build_gpt2() {
  6765. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6766. const int64_t n_embd_head = hparams.n_embd_head_v;
  6767. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  6768. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6769. struct ggml_tensor * cur;
  6770. struct ggml_tensor * pos;
  6771. struct ggml_tensor * inpL;
  6772. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6773. // inp_pos - contains the positions
  6774. struct ggml_tensor * inp_pos = build_inp_pos();
  6775. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6776. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6777. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  6778. cb(pos, "pos_embd", -1);
  6779. inpL = ggml_add(ctx0, inpL, pos);
  6780. cb(inpL, "inpL", -1);
  6781. for (int il = 0; il < n_layer; ++il) {
  6782. cur = llm_build_norm(ctx0, inpL, hparams,
  6783. model.layers[il].attn_norm,
  6784. model.layers[il].attn_norm_b,
  6785. LLM_NORM, cb, il);
  6786. cb(cur, "attn_norm", il);
  6787. // self-attention
  6788. {
  6789. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6790. cb(cur, "wqkv", il);
  6791. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6792. cb(cur, "bqkv", il);
  6793. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6794. 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)));
  6795. 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)));
  6796. cb(Qcur, "Qcur", il);
  6797. cb(Kcur, "Kcur", il);
  6798. cb(Vcur, "Vcur", il);
  6799. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6800. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6801. model.layers[il].wo, model.layers[il].bo,
  6802. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6803. }
  6804. if (il == n_layer - 1) {
  6805. // skip computing output for unused tokens
  6806. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6807. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6808. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  6809. }
  6810. // add the input
  6811. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  6812. cb(ffn_inp, "ffn_inp", il);
  6813. // FF
  6814. {
  6815. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6816. model.layers[il].ffn_norm,
  6817. model.layers[il].ffn_norm_b,
  6818. LLM_NORM, cb, il);
  6819. cb(cur, "ffn_norm", il);
  6820. cur = llm_build_ffn(ctx0, cur,
  6821. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6822. NULL, NULL,
  6823. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6824. NULL,
  6825. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6826. cb(cur, "ffn_out", il);
  6827. }
  6828. inpL = ggml_add(ctx0, cur, ffn_inp);
  6829. cb(inpL, "l_out", il);
  6830. }
  6831. cur = llm_build_norm(ctx0, inpL, hparams,
  6832. model.output_norm,
  6833. model.output_norm_b,
  6834. LLM_NORM, cb, -1);
  6835. cb(cur, "result_norm", -1);
  6836. cur = ggml_mul_mat(ctx0, model.output, cur);
  6837. cb(cur, "result_output", -1);
  6838. ggml_build_forward_expand(gf, cur);
  6839. return gf;
  6840. }
  6841. struct ggml_cgraph * build_codeshell() {
  6842. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6843. const int64_t n_embd_head = hparams.n_embd_head_v;
  6844. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  6845. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6846. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6847. struct ggml_tensor * cur;
  6848. struct ggml_tensor * inpL;
  6849. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6850. // inp_pos - contains the positions
  6851. struct ggml_tensor * inp_pos = build_inp_pos();
  6852. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6853. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6854. for (int il = 0; il < n_layer; ++il) {
  6855. cur = llm_build_norm(ctx0, inpL, hparams,
  6856. model.layers[il].attn_norm,
  6857. model.layers[il].attn_norm_b,
  6858. LLM_NORM, cb, il);
  6859. cb(cur, "attn_norm", il);
  6860. // self-attention
  6861. {
  6862. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6863. cb(cur, "wqkv", il);
  6864. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6865. cb(cur, "bqkv", il);
  6866. struct ggml_tensor * tmpq = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6867. 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)));
  6868. 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)));
  6869. cb(tmpq, "tmpq", il);
  6870. cb(tmpk, "tmpk", il);
  6871. cb(Vcur, "Vcur", il);
  6872. struct ggml_tensor * Qcur = ggml_rope_custom(
  6873. ctx0, ggml_reshape_3d(ctx0, tmpq, n_embd_head, n_head, n_tokens), inp_pos,
  6874. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6875. ext_factor, attn_factor, beta_fast, beta_slow
  6876. );
  6877. cb(Qcur, "Qcur", il);
  6878. struct ggml_tensor * Kcur = ggml_rope_custom(
  6879. ctx0, ggml_reshape_3d(ctx0, tmpk, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6880. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6881. ext_factor, attn_factor, beta_fast, beta_slow
  6882. );
  6883. cb(Kcur, "Kcur", il);
  6884. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6885. model.layers[il].wo, model.layers[il].bo,
  6886. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6887. }
  6888. if (il == n_layer - 1) {
  6889. // skip computing output for unused tokens
  6890. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6891. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6892. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  6893. }
  6894. // add the input
  6895. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  6896. cb(ffn_inp, "ffn_inp", il);
  6897. // FF
  6898. {
  6899. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6900. model.layers[il].ffn_norm,
  6901. model.layers[il].ffn_norm_b,
  6902. LLM_NORM, cb, il);
  6903. cb(cur, "ffn_norm", il);
  6904. cur = llm_build_ffn(ctx0, cur,
  6905. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6906. NULL, NULL,
  6907. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6908. NULL,
  6909. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6910. cb(cur, "ffn_out", il);
  6911. }
  6912. inpL = ggml_add(ctx0, cur, ffn_inp);
  6913. cb(inpL, "l_out", il);
  6914. }
  6915. cur = llm_build_norm(ctx0, inpL, hparams,
  6916. model.output_norm,
  6917. model.output_norm_b,
  6918. LLM_NORM, cb, -1);
  6919. cb(cur, "result_norm", -1);
  6920. cur = ggml_mul_mat(ctx0, model.output, cur);
  6921. cb(cur, "result_output", -1);
  6922. ggml_build_forward_expand(gf, cur);
  6923. return gf;
  6924. }
  6925. struct ggml_cgraph * build_orion() {
  6926. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6927. const int64_t n_embd_head = hparams.n_embd_head_v;
  6928. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6929. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6930. struct ggml_tensor * cur;
  6931. struct ggml_tensor * inpL;
  6932. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6933. // inp_pos - contains the positions
  6934. struct ggml_tensor * inp_pos = build_inp_pos();
  6935. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6936. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6937. for (int il = 0; il < n_layer; ++il) {
  6938. struct ggml_tensor * inpSA = inpL;
  6939. // norm
  6940. cur = llm_build_norm(ctx0, inpL, hparams,
  6941. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  6942. LLM_NORM, cb, il);
  6943. cb(cur, "attn_norm", il);
  6944. // self-attention
  6945. {
  6946. // compute Q and K and RoPE them
  6947. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6948. cb(Qcur, "Qcur", il);
  6949. // if (model.layers[il].bq) {
  6950. // Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6951. // cb(Qcur, "Qcur", il);
  6952. // }
  6953. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6954. cb(Kcur, "Kcur", il);
  6955. // if (model.layers[il].bk) {
  6956. // Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6957. // cb(Kcur, "Kcur", il);
  6958. // }
  6959. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6960. cb(Vcur, "Vcur", il);
  6961. // if (model.layers[il].bv) {
  6962. // Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6963. // cb(Vcur, "Vcur", il);
  6964. // }
  6965. Qcur = ggml_rope_custom(
  6966. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6967. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6968. ext_factor, attn_factor, beta_fast, beta_slow
  6969. );
  6970. cb(Qcur, "Qcur", il);
  6971. Kcur = ggml_rope_custom(
  6972. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6973. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6974. ext_factor, attn_factor, beta_fast, beta_slow
  6975. );
  6976. cb(Kcur, "Kcur", il);
  6977. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6978. model.layers[il].wo, NULL,
  6979. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6980. }
  6981. if (il == n_layer - 1) {
  6982. // skip computing output for unused tokens
  6983. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  6984. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  6985. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  6986. }
  6987. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6988. cb(ffn_inp, "ffn_inp", il);
  6989. // feed-forward network
  6990. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6991. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  6992. LLM_NORM, cb, il);
  6993. cb(cur, "ffn_norm", il);
  6994. cur = llm_build_ffn(ctx0, cur,
  6995. model.layers[il].ffn_up, NULL,
  6996. model.layers[il].ffn_gate, NULL,
  6997. model.layers[il].ffn_down, NULL,
  6998. NULL,
  6999. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  7000. cb(cur, "ffn_out", il);
  7001. cur = ggml_add(ctx0, cur, ffn_inp);
  7002. cb(cur, "l_out", il);
  7003. // input for next layer
  7004. inpL = cur;
  7005. }
  7006. cur = inpL;
  7007. cur = llm_build_norm(ctx0, cur, hparams,
  7008. model.output_norm, model.output_norm_b,
  7009. LLM_NORM, cb, -1);
  7010. cb(cur, "result_norm", -1);
  7011. // lm_head
  7012. cur = ggml_mul_mat(ctx0, model.output, cur);
  7013. cb(cur, "result_output", -1);
  7014. ggml_build_forward_expand(gf, cur);
  7015. return gf;
  7016. }
  7017. struct ggml_cgraph * build_internlm2() {
  7018. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7019. const int64_t n_embd_head = hparams.n_embd_head_v;
  7020. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7021. GGML_ASSERT(n_embd_head == hparams.n_rot);
  7022. struct ggml_tensor * cur;
  7023. struct ggml_tensor * inpL;
  7024. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7025. // inp_pos - contains the positions
  7026. struct ggml_tensor * inp_pos = build_inp_pos();
  7027. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7028. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7029. for (int il = 0; il < n_layer; ++il) {
  7030. struct ggml_tensor * inpSA = inpL;
  7031. // norm
  7032. cur = llm_build_norm(ctx0, inpL, hparams,
  7033. model.layers[il].attn_norm, NULL,
  7034. LLM_NORM_RMS, cb, il);
  7035. cb(cur, "attn_norm", il);
  7036. // self-attention
  7037. {
  7038. // compute Q and K and RoPE them
  7039. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  7040. cb(Qcur, "Qcur", il);
  7041. if (model.layers[il].bq) {
  7042. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  7043. cb(Qcur, "Qcur", il);
  7044. }
  7045. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  7046. cb(Kcur, "Kcur", il);
  7047. if (model.layers[il].bk) {
  7048. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  7049. cb(Kcur, "Kcur", il);
  7050. }
  7051. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  7052. cb(Vcur, "Vcur", il);
  7053. if (model.layers[il].bv) {
  7054. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  7055. cb(Vcur, "Vcur", il);
  7056. }
  7057. Qcur = ggml_rope_custom(
  7058. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  7059. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7060. ext_factor, attn_factor, beta_fast, beta_slow
  7061. );
  7062. cb(Qcur, "Qcur", il);
  7063. Kcur = ggml_rope_custom(
  7064. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  7065. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7066. ext_factor, attn_factor, beta_fast, beta_slow
  7067. );
  7068. cb(Kcur, "Kcur", il);
  7069. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  7070. model.layers[il].wo, model.layers[il].bo,
  7071. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7072. }
  7073. if (il == n_layer - 1) {
  7074. // skip computing output for unused tokens
  7075. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7076. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7077. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  7078. }
  7079. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  7080. cb(ffn_inp, "ffn_inp", il);
  7081. // feed-forward network
  7082. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7083. model.layers[il].ffn_norm, NULL,
  7084. LLM_NORM_RMS, cb, il);
  7085. cb(cur, "ffn_norm", il);
  7086. cur = llm_build_ffn(ctx0, cur,
  7087. model.layers[il].ffn_up, NULL,
  7088. model.layers[il].ffn_gate, NULL,
  7089. model.layers[il].ffn_down, NULL,
  7090. NULL,
  7091. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  7092. cb(cur, "ffn_out", il);
  7093. cur = ggml_add(ctx0, cur, ffn_inp);
  7094. cb(cur, "l_out", il);
  7095. // input for next layer
  7096. inpL = cur;
  7097. }
  7098. cur = inpL;
  7099. cur = llm_build_norm(ctx0, cur, hparams,
  7100. model.output_norm, NULL,
  7101. LLM_NORM_RMS, cb, -1);
  7102. cb(cur, "result_norm", -1);
  7103. // lm_head
  7104. cur = ggml_mul_mat(ctx0, model.output, cur);
  7105. cb(cur, "result_output", -1);
  7106. ggml_build_forward_expand(gf, cur);
  7107. return gf;
  7108. }
  7109. // ref: https://arxiv.org/abs/2203.03466
  7110. // https://github.com/ggerganov/llama.cpp/issues/5276#issuecomment-1925774738
  7111. // based on the original build_llama() function
  7112. struct ggml_cgraph * build_minicpm() {
  7113. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7114. const int64_t n_embd_head = hparams.n_embd_head_v;
  7115. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7116. GGML_ASSERT(n_embd_head == hparams.n_rot);
  7117. const int64_t n_embd = hparams.n_embd;
  7118. //TODO: if the model varies, these parameters need to be read from the model
  7119. const int64_t n_embd_base = 256;
  7120. const float scale_embd = 12.0f;
  7121. const float scale_depth = 1.4f;
  7122. struct ggml_tensor * cur;
  7123. struct ggml_tensor * inpL;
  7124. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7125. // scale the input embeddings
  7126. inpL = ggml_scale(ctx0, inpL, scale_embd);
  7127. cb(inpL, "inp_scaled", -1);
  7128. // inp_pos - contains the positions
  7129. struct ggml_tensor * inp_pos = build_inp_pos();
  7130. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7131. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7132. for (int il = 0; il < n_layer; ++il) {
  7133. struct ggml_tensor * inpSA = inpL;
  7134. // norm
  7135. cur = llm_build_norm(ctx0, inpL, hparams,
  7136. model.layers[il].attn_norm, NULL,
  7137. LLM_NORM_RMS, cb, il);
  7138. cb(cur, "attn_norm", il);
  7139. // self-attention
  7140. {
  7141. // compute Q and K and RoPE them
  7142. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  7143. cb(Qcur, "Qcur", il);
  7144. if (model.layers[il].bq) {
  7145. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  7146. cb(Qcur, "Qcur", il);
  7147. }
  7148. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  7149. cb(Kcur, "Kcur", il);
  7150. if (model.layers[il].bk) {
  7151. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  7152. cb(Kcur, "Kcur", il);
  7153. }
  7154. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  7155. cb(Vcur, "Vcur", il);
  7156. if (model.layers[il].bv) {
  7157. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  7158. cb(Vcur, "Vcur", il);
  7159. }
  7160. Qcur = ggml_rope_custom(
  7161. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  7162. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7163. ext_factor, attn_factor, beta_fast, beta_slow
  7164. );
  7165. cb(Qcur, "Qcur", il);
  7166. Kcur = ggml_rope_custom(
  7167. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  7168. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7169. ext_factor, attn_factor, beta_fast, beta_slow
  7170. );
  7171. cb(Kcur, "Kcur", il);
  7172. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  7173. model.layers[il].wo, model.layers[il].bo,
  7174. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7175. }
  7176. if (il == n_layer - 1) {
  7177. // skip computing output for unused tokens
  7178. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7179. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7180. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  7181. }
  7182. // scale_res - scale the hidden states for residual connection
  7183. const float scale_res = scale_depth/sqrtf(float(n_layer));
  7184. cur = ggml_scale(ctx0, cur, scale_res);
  7185. cb(cur, "hidden_scaled", -1);
  7186. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  7187. cb(ffn_inp, "ffn_inp", il);
  7188. // feed-forward network
  7189. {
  7190. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7191. model.layers[il].ffn_norm, NULL,
  7192. LLM_NORM_RMS, cb, il);
  7193. cb(cur, "ffn_norm", il);
  7194. cur = llm_build_ffn(ctx0, cur,
  7195. model.layers[il].ffn_up, NULL,
  7196. model.layers[il].ffn_gate, NULL,
  7197. model.layers[il].ffn_down, NULL,
  7198. NULL,
  7199. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  7200. cb(cur, "ffn_out", il);
  7201. }
  7202. // scale the hidden states for residual connection
  7203. cur = ggml_scale(ctx0, cur, scale_res);
  7204. cb(cur, "hidden_scaled_ffn", -1);
  7205. cur = ggml_add(ctx0, cur, ffn_inp);
  7206. cb(cur, "l_out", il);
  7207. // input for next layer
  7208. inpL = cur;
  7209. }
  7210. cur = inpL;
  7211. cur = llm_build_norm(ctx0, cur, hparams,
  7212. model.output_norm, NULL,
  7213. LLM_NORM_RMS, cb, -1);
  7214. cb(cur, "result_norm", -1);
  7215. // lm_head scaling
  7216. const float scale_lmhead = float(n_embd_base)/float(n_embd);
  7217. cur = ggml_scale(ctx0, cur, scale_lmhead);
  7218. cb(cur, "lmhead_scaling", -1);
  7219. // lm_head
  7220. cur = ggml_mul_mat(ctx0, model.tok_embd, cur);
  7221. cb(cur, "result_output", -1);
  7222. ggml_build_forward_expand(gf, cur);
  7223. return gf;
  7224. }
  7225. struct ggml_cgraph * build_gemma() {
  7226. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7227. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  7228. struct ggml_tensor * cur;
  7229. struct ggml_tensor * inpL;
  7230. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7231. inpL = ggml_scale(ctx0, inpL, sqrtf(n_embd));
  7232. cb(inpL, "inp_scaled", -1);
  7233. // inp_pos - contains the positions
  7234. struct ggml_tensor * inp_pos = build_inp_pos();
  7235. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7236. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7237. for (int il = 0; il < n_layer; ++il) {
  7238. // norm
  7239. cur = llm_build_norm(ctx0, inpL, hparams,
  7240. model.layers[il].attn_norm, NULL,
  7241. LLM_NORM_RMS, cb, il);
  7242. cb(cur, "attn_norm", il);
  7243. // self-attention
  7244. {
  7245. // compute Q and K and RoPE them
  7246. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  7247. cb(Qcur, "Qcur", il);
  7248. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  7249. cb(Kcur, "Kcur", il);
  7250. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  7251. cb(Vcur, "Vcur", il);
  7252. Qcur = ggml_rope_custom(
  7253. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head_k, n_head, n_tokens), inp_pos,
  7254. n_embd_head_k, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7255. ext_factor, attn_factor, beta_fast, beta_slow);
  7256. cb(Qcur, "Qcur", il);
  7257. Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head_k)));
  7258. cb(Qcur, "Qcur_scaled", il);
  7259. Kcur = ggml_rope_custom(
  7260. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head_k, n_head_kv, n_tokens), inp_pos,
  7261. n_embd_head_k, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7262. ext_factor, attn_factor, beta_fast, beta_slow);
  7263. cb(Kcur, "Kcur", il);
  7264. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  7265. model.layers[il].wo, NULL,
  7266. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  7267. }
  7268. if (il == n_layer - 1) {
  7269. // skip computing output for unused tokens
  7270. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7271. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7272. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  7273. }
  7274. struct ggml_tensor * sa_out = ggml_add(ctx0, cur, inpL);
  7275. cb(sa_out, "sa_out", il);
  7276. cur = llm_build_norm(ctx0, sa_out, hparams,
  7277. model.layers[il].ffn_norm, NULL,
  7278. LLM_NORM_RMS, cb, il);
  7279. cb(cur, "ffn_norm", il);
  7280. // feed-forward network
  7281. {
  7282. cur = llm_build_ffn(ctx0, cur,
  7283. model.layers[il].ffn_up, NULL,
  7284. model.layers[il].ffn_gate, NULL,
  7285. model.layers[il].ffn_down, NULL,
  7286. NULL,
  7287. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  7288. cb(cur, "ffn_out", il);
  7289. }
  7290. cur = ggml_add(ctx0, cur, sa_out);
  7291. cb(cur, "l_out", il);
  7292. // input for next layer
  7293. inpL = cur;
  7294. }
  7295. cur = inpL;
  7296. cur = llm_build_norm(ctx0, cur, hparams,
  7297. model.output_norm, NULL,
  7298. LLM_NORM_RMS, cb, -1);
  7299. cb(cur, "result_norm", -1);
  7300. // lm_head
  7301. cur = ggml_mul_mat(ctx0, model.output, cur);
  7302. cb(cur, "result_output", -1);
  7303. ggml_build_forward_expand(gf, cur);
  7304. return gf;
  7305. }
  7306. struct ggml_cgraph * build_starcoder2() {
  7307. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7308. const int64_t n_embd_head = hparams.n_embd_head_v;
  7309. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7310. GGML_ASSERT(n_embd_head == hparams.n_rot);
  7311. struct ggml_tensor * cur;
  7312. struct ggml_tensor * inpL;
  7313. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7314. // inp_pos - contains the positions
  7315. struct ggml_tensor * inp_pos = build_inp_pos();
  7316. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7317. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7318. for (int il = 0; il < n_layer; ++il) {
  7319. struct ggml_tensor * inpSA = inpL;
  7320. // norm
  7321. cur = llm_build_norm(ctx0, inpL, hparams,
  7322. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  7323. LLM_NORM, cb, il);
  7324. cb(cur, "attn_norm", il);
  7325. // self-attention
  7326. {
  7327. // compute Q and K and RoPE them
  7328. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  7329. cb(Qcur, "Qcur", il);
  7330. if (model.layers[il].bq) {
  7331. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  7332. cb(Qcur, "Qcur", il);
  7333. }
  7334. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  7335. cb(Kcur, "Kcur", il);
  7336. if (model.layers[il].bk) {
  7337. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  7338. cb(Kcur, "Kcur", il);
  7339. }
  7340. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  7341. cb(Vcur, "Vcur", il);
  7342. if (model.layers[il].bv) {
  7343. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  7344. cb(Vcur, "Vcur", il);
  7345. }
  7346. Qcur = ggml_rope_custom(
  7347. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  7348. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7349. ext_factor, attn_factor, beta_fast, beta_slow
  7350. );
  7351. cb(Qcur, "Qcur", il);
  7352. Kcur = ggml_rope_custom(
  7353. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  7354. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7355. ext_factor, attn_factor, beta_fast, beta_slow
  7356. );
  7357. cb(Kcur, "Kcur", il);
  7358. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  7359. model.layers[il].wo, model.layers[il].bo,
  7360. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7361. }
  7362. if (il == n_layer - 1) {
  7363. // skip computing output for unused tokens
  7364. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7365. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7366. inpSA = ggml_get_rows(ctx0, inpSA, inp_out_ids);
  7367. }
  7368. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  7369. cb(ffn_inp, "ffn_inp", il);
  7370. // feed-forward network
  7371. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  7372. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  7373. LLM_NORM, cb, il);
  7374. cb(cur, "ffn_norm", il);
  7375. cur = llm_build_ffn(ctx0, cur,
  7376. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  7377. NULL, NULL,
  7378. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  7379. NULL,
  7380. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  7381. cb(cur, "ffn_out", il);
  7382. cur = ggml_add(ctx0, cur, ffn_inp);
  7383. cb(cur, "l_out", il);
  7384. // input for next layer
  7385. inpL = cur;
  7386. }
  7387. cur = inpL;
  7388. cur = llm_build_norm(ctx0, cur, hparams,
  7389. model.output_norm, model.output_norm_b,
  7390. LLM_NORM, cb, -1);
  7391. cb(cur, "result_norm", -1);
  7392. // lm_head
  7393. cur = ggml_mul_mat(ctx0, model.output, cur);
  7394. cb(cur, "result_output", -1);
  7395. ggml_build_forward_expand(gf, cur);
  7396. return gf;
  7397. }
  7398. struct ggml_cgraph * build_mamba() {
  7399. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7400. const int64_t d_model = n_embd;
  7401. const int64_t d_conv = hparams.ssm_d_conv;
  7402. const int64_t d_inner = hparams.ssm_d_inner;
  7403. GGML_ASSERT(2 * d_model == d_inner);
  7404. const int64_t d_state = hparams.ssm_d_state;
  7405. const int64_t dt_rank = hparams.ssm_dt_rank;
  7406. struct ggml_tensor * cur;
  7407. struct ggml_tensor * inpL;
  7408. // {n_embd, n_tokens}
  7409. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7410. struct ggml_tensor * state_mask = build_inp_s_mask();
  7411. struct ggml_tensor * state_seq = build_inp_s_seq();
  7412. for (int il = 0; il < n_layer; ++il) {
  7413. // (ab)using the KV cache to store the states
  7414. struct ggml_tensor * conv_states = ggml_reshape_2d(ctx0, kv_self.k_l[il], hparams.n_embd_k_s(), kv_self.size);
  7415. struct ggml_tensor * ssm_states = ggml_reshape_2d(ctx0, kv_self.v_l[il], hparams.n_embd_v_s(), kv_self.size);
  7416. // clear states of sequences which are starting at the beginning of this batch
  7417. {
  7418. conv_states = ggml_mul(ctx0,
  7419. ggml_view_2d(ctx0, conv_states, conv_states->ne[0], n_kv, conv_states->nb[1], kv_head*conv_states->nb[1]),
  7420. state_mask);
  7421. ssm_states = ggml_mul(ctx0,
  7422. ggml_view_2d(ctx0, ssm_states, ssm_states->ne[0], n_kv, ssm_states->nb[1], kv_head*ssm_states->nb[1]),
  7423. state_mask);
  7424. }
  7425. conv_states = ggml_reshape_3d(ctx0, conv_states, d_conv - 1, d_inner, n_kv);
  7426. ssm_states = ggml_reshape_3d(ctx0, ssm_states, d_state, d_inner, n_kv);
  7427. // norm
  7428. cur = llm_build_norm(ctx0, inpL, hparams,
  7429. model.layers[il].attn_norm, NULL,
  7430. LLM_NORM_RMS, cb, il);
  7431. cb(cur, "attn_norm", il);
  7432. // {n_embd, 2*d_inner} * {n_embd, n_tokens} => {2*d_inner, n_tokens}
  7433. struct ggml_tensor * xz = ggml_mul_mat(ctx0, model.layers[il].ssm_in, cur);
  7434. // split the above in two
  7435. // => {d_inner, n_tokens}
  7436. struct ggml_tensor * x = ggml_view_2d(ctx0, xz, d_inner, xz->ne[1], xz->nb[1], 0);
  7437. struct ggml_tensor * z = ggml_view_2d(ctx0, xz, d_inner, xz->ne[1], xz->nb[1], ggml_element_size(xz)*d_inner);
  7438. // conv
  7439. {
  7440. // Custom operator which is needed only to ease simultaneous sequence processing.
  7441. // For a single sequence, the equivalent is to concatenate the columns of conv_states and x,
  7442. // then make a self-overlapping view of that over d_conv columns at each stride in the 3rd dimension,
  7443. // then element-wise multiply that with the conv1d weigth,
  7444. // then sum the elements of each row,
  7445. // (the last two steps are a dot product over rows (also doable with mul_mat))
  7446. // then permute away the ne[0] dimension,
  7447. // and then you're left with the resulting x tensor.
  7448. // The new conv_states is the last (d_conv - 1) columns
  7449. // of the last 3rd dimensional "layer" of the self-overlapping view.
  7450. // For simultaneous sequences, it's more complicated.
  7451. struct ggml_tensor * x_conv = ggml_ssm_conv(ctx0, conv_states, x, model.layers[il].ssm_conv1d, state_seq);
  7452. // store last (d_conv - 1) columns of the conv_state part of x_conv back into the KV cache
  7453. ggml_build_forward_expand(gf,
  7454. ggml_cpy(ctx0,
  7455. 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)),
  7456. 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))));
  7457. // extract x from x_conv
  7458. x = ggml_view_2d(ctx0, x_conv, d_inner, n_tokens, d_inner*ggml_element_size(x_conv), 0);
  7459. // bias
  7460. x = ggml_add(ctx0, x, model.layers[il].ssm_conv1d_b);
  7461. x = ggml_silu(ctx0, x);
  7462. }
  7463. // ssm
  7464. {
  7465. // {d_inner, dt_rank + 2*d_state} * {d_inner, n_tokens} => {dt_rank + 2*d_state, n_tokens}
  7466. struct ggml_tensor * x_db = ggml_mul_mat(ctx0, model.layers[il].ssm_x, x);
  7467. // split
  7468. struct ggml_tensor * dt = ggml_view_2d(ctx0, x_db, dt_rank, n_tokens, x_db->nb[1], 0);
  7469. 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);
  7470. 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));
  7471. // {dt_rank, d_inner} * {dt_rank, n_tokens} => {d_inner, n_tokens}
  7472. dt = ggml_mul_mat(ctx0, model.layers[il].ssm_dt, dt);
  7473. dt = ggml_add(ctx0, dt, model.layers[il].ssm_dt_b);
  7474. // Custom operator to optimize the parallel associative scan
  7475. // as described in the Annex D of the Mamba paper.
  7476. // => {d_inner, n_tokens} and {d_state, d_inner, n_kv} combined,
  7477. // because only a single tensor can be returned.
  7478. struct ggml_tensor * y_ssm_states = ggml_ssm_scan(ctx0, ssm_states, x, dt, model.layers[il].ssm_a, B, C, state_seq);
  7479. // store last states (the second part of y_ssm_states)
  7480. ggml_build_forward_expand(gf,
  7481. ggml_cpy(ctx0,
  7482. ggml_view_1d(ctx0, y_ssm_states, d_state*d_inner*n_kv, d_inner*n_tokens*ggml_element_size(y_ssm_states)),
  7483. 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))));
  7484. struct ggml_tensor * y = ggml_view_2d(ctx0, y_ssm_states, d_inner, n_tokens, d_inner*ggml_element_size(y_ssm_states), 0);
  7485. if (il == n_layer - 1) {
  7486. // skip computing output for unused tokens
  7487. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7488. x = ggml_get_rows(ctx0, x, inp_out_ids);
  7489. y = ggml_get_rows(ctx0, y, inp_out_ids);
  7490. z = ggml_get_rows(ctx0, z, inp_out_ids);
  7491. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  7492. }
  7493. // {d_inner, n_tokens} * {d_inner} => {d_inner, n_tokens}
  7494. y = ggml_add(ctx0, y, ggml_mul(ctx0, x, model.layers[il].ssm_d));
  7495. y = ggml_mul(ctx0, y, ggml_silu(ctx0, z));
  7496. // {d_inner, n_embd} * {d_inner, n_tokens} => {n_embd, n_tokens}
  7497. cur = ggml_mul_mat(ctx0, model.layers[il].ssm_out, y);
  7498. }
  7499. // residual
  7500. cur = ggml_add(ctx0, cur, inpL);
  7501. cb(cur, "l_out", il);
  7502. // input for next layer
  7503. inpL = cur;
  7504. }
  7505. // final rmsnorm
  7506. cur = llm_build_norm(ctx0, inpL, hparams,
  7507. model.output_norm, NULL,
  7508. LLM_NORM_RMS, cb, -1);
  7509. cb(cur, "result_norm", -1);
  7510. // lm_head
  7511. cur = ggml_mul_mat(ctx0, model.output, cur);
  7512. cb(cur, "result_output", -1);
  7513. ggml_build_forward_expand(gf, cur);
  7514. return gf;
  7515. }
  7516. struct ggml_cgraph * build_command_r() {
  7517. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  7518. const int64_t n_embd_head = hparams.n_embd_head_v;
  7519. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  7520. const float f_logit_scale = hparams.f_logit_scale;
  7521. struct ggml_tensor * cur;
  7522. struct ggml_tensor * inpL;
  7523. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  7524. // inp_pos - contains the positions
  7525. struct ggml_tensor * inp_pos = build_inp_pos();
  7526. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  7527. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  7528. for (int il = 0; il < n_layer; ++il) {
  7529. // norm
  7530. cur = llm_build_norm(ctx0, inpL, hparams,
  7531. model.layers[il].attn_norm, NULL,
  7532. LLM_NORM, cb, il);
  7533. cb(cur, "attn_norm", il);
  7534. struct ggml_tensor * ffn_inp = cur;
  7535. // self-attention
  7536. {
  7537. // compute Q and K and RoPE them
  7538. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  7539. cb(Qcur, "Qcur", il);
  7540. if (model.layers[il].bq) {
  7541. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  7542. cb(Qcur, "Qcur", il);
  7543. }
  7544. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  7545. cb(Kcur, "Kcur", il);
  7546. if (model.layers[il].bk) {
  7547. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  7548. cb(Kcur, "Kcur", il);
  7549. }
  7550. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  7551. cb(Vcur, "Vcur", il);
  7552. if (model.layers[il].bv) {
  7553. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  7554. cb(Vcur, "Vcur", il);
  7555. }
  7556. Qcur = ggml_rope_custom(
  7557. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  7558. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7559. ext_factor, attn_factor, beta_fast, beta_slow
  7560. );
  7561. cb(Qcur, "Qcur", il);
  7562. Kcur = ggml_rope_custom(
  7563. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  7564. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7565. ext_factor, attn_factor, beta_fast, beta_slow
  7566. );
  7567. cb(Kcur, "Kcur", il);
  7568. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  7569. model.layers[il].wo, model.layers[il].bo,
  7570. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7571. }
  7572. if (il == n_layer - 1) {
  7573. // skip computing output for unused tokens
  7574. struct ggml_tensor * inp_out_ids = build_inp_out_ids();
  7575. cur = ggml_get_rows(ctx0, cur, inp_out_ids);
  7576. inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);
  7577. }
  7578. struct ggml_tensor * attn_out = cur;
  7579. // feed-forward network
  7580. {
  7581. cur = llm_build_ffn(ctx0, ffn_inp,
  7582. model.layers[il].ffn_up, NULL,
  7583. model.layers[il].ffn_gate, NULL,
  7584. model.layers[il].ffn_down, NULL,
  7585. NULL,
  7586. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  7587. cb(cur, "ffn_out", il);
  7588. }
  7589. // add together residual + FFN + self-attention
  7590. cur = ggml_add(ctx0, cur, inpL);
  7591. cur = ggml_add(ctx0, cur, attn_out);
  7592. cb(cur, "l_out", il);
  7593. // input for next layer
  7594. inpL = cur;
  7595. }
  7596. cur = inpL;
  7597. cur = llm_build_norm(ctx0, cur, hparams,
  7598. model.output_norm, NULL,
  7599. LLM_NORM, cb, -1);
  7600. cb(cur, "result_norm", -1);
  7601. // lm_head
  7602. cur = ggml_mul_mat(ctx0, model.output, cur);
  7603. if (f_logit_scale) {
  7604. cur = ggml_scale(ctx0, cur, f_logit_scale);
  7605. }
  7606. cb(cur, "result_output", -1);
  7607. ggml_build_forward_expand(gf, cur);
  7608. return gf;
  7609. }
  7610. };
  7611. static struct ggml_cgraph * llama_build_graph_defrag(llama_context & lctx, const std::vector<uint32_t> & ids) {
  7612. llama_batch dummy;
  7613. dummy.n_tokens = 0;
  7614. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  7615. struct llm_build_context llm(lctx, dummy, cb, false);
  7616. llm.init();
  7617. struct ggml_cgraph * result = llm.build_defrag(ids);
  7618. llm.free();
  7619. return result;
  7620. }
  7621. static struct ggml_cgraph * llama_build_graph_k_shift(llama_context & lctx) {
  7622. llama_batch dummy;
  7623. dummy.n_tokens = 0;
  7624. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  7625. struct llm_build_context llm(lctx, dummy, cb, false);
  7626. llm.init();
  7627. struct ggml_cgraph * result = llm.build_k_shift();
  7628. llm.free();
  7629. return result;
  7630. }
  7631. static struct ggml_cgraph * llama_build_graph_s_copy(llama_context & lctx) {
  7632. llama_batch dummy;
  7633. dummy.n_tokens = 0;
  7634. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  7635. struct llm_build_context llm(lctx, dummy, cb, false);
  7636. llm.init();
  7637. struct ggml_cgraph * result = llm.build_s_copy();
  7638. llm.free();
  7639. return result;
  7640. }
  7641. static struct ggml_cgraph * llama_build_graph(
  7642. llama_context & lctx,
  7643. const llama_batch & batch,
  7644. bool worst_case) {
  7645. const auto & model = lctx.model;
  7646. // this callback allows us to apply custom logic to each tensor (e.g. ggml-alloc, offloading, etc.)
  7647. llm_build_cb cb = [&](struct ggml_tensor * cur, const char * name, int il) {
  7648. if (il >= 0) {
  7649. ggml_format_name(cur, "%s-%d", name, il);
  7650. } else {
  7651. ggml_set_name(cur, name);
  7652. }
  7653. if (!lctx.cparams.offload_kqv) {
  7654. if (strcmp(name, "kqv_merged_cont") == 0) {
  7655. // all nodes between the KV store and the attention output are run on the CPU
  7656. ggml_backend_sched_set_tensor_backend(lctx.sched, cur, lctx.backend_cpu);
  7657. }
  7658. }
  7659. // norm may be automatically assigned to the backend of the previous layer, increasing data transfer between backends
  7660. // FIXME: fix in ggml_backend_sched
  7661. const bool full_offload = lctx.model.n_gpu_layers > (int)lctx.model.hparams.n_layer;
  7662. if (batch.n_tokens < 32 || full_offload) {
  7663. if (il != -1 && strcmp(name, "norm") == 0) {
  7664. for (auto * backend : lctx.backends) {
  7665. if (ggml_backend_buft_supports_backend(lctx.model.buft_layer[il].buft, backend)) {
  7666. ggml_backend_sched_set_tensor_backend(lctx.sched, cur, backend);
  7667. break;
  7668. }
  7669. }
  7670. }
  7671. }
  7672. };
  7673. struct ggml_cgraph * result = NULL;
  7674. struct llm_build_context llm(lctx, batch, cb, worst_case);
  7675. llm.init();
  7676. switch (model.arch) {
  7677. case LLM_ARCH_LLAMA:
  7678. {
  7679. result = llm.build_llama();
  7680. } break;
  7681. case LLM_ARCH_BAICHUAN:
  7682. {
  7683. result = llm.build_baichuan();
  7684. } break;
  7685. case LLM_ARCH_FALCON:
  7686. {
  7687. result = llm.build_falcon();
  7688. } break;
  7689. case LLM_ARCH_GROK:
  7690. {
  7691. result = llm.build_grok();
  7692. } break;
  7693. case LLM_ARCH_STARCODER:
  7694. {
  7695. result = llm.build_starcoder();
  7696. } break;
  7697. case LLM_ARCH_PERSIMMON:
  7698. {
  7699. result = llm.build_persimmon();
  7700. } break;
  7701. case LLM_ARCH_REFACT:
  7702. {
  7703. result = llm.build_refact();
  7704. } break;
  7705. case LLM_ARCH_BERT:
  7706. case LLM_ARCH_NOMIC_BERT:
  7707. {
  7708. result = llm.build_bert();
  7709. } break;
  7710. case LLM_ARCH_BLOOM:
  7711. {
  7712. result = llm.build_bloom();
  7713. } break;
  7714. case LLM_ARCH_MPT:
  7715. {
  7716. result = llm.build_mpt();
  7717. } break;
  7718. case LLM_ARCH_STABLELM:
  7719. {
  7720. result = llm.build_stablelm();
  7721. } break;
  7722. case LLM_ARCH_QWEN:
  7723. {
  7724. result = llm.build_qwen();
  7725. } break;
  7726. case LLM_ARCH_QWEN2:
  7727. {
  7728. result = llm.build_qwen2();
  7729. } break;
  7730. case LLM_ARCH_PHI2:
  7731. {
  7732. result = llm.build_phi2();
  7733. } break;
  7734. case LLM_ARCH_PLAMO:
  7735. {
  7736. result = llm.build_plamo();
  7737. } break;
  7738. case LLM_ARCH_GPT2:
  7739. {
  7740. result = llm.build_gpt2();
  7741. } break;
  7742. case LLM_ARCH_CODESHELL:
  7743. {
  7744. result = llm.build_codeshell();
  7745. } break;
  7746. case LLM_ARCH_ORION:
  7747. {
  7748. result = llm.build_orion();
  7749. } break;
  7750. case LLM_ARCH_INTERNLM2:
  7751. {
  7752. result = llm.build_internlm2();
  7753. } break;
  7754. case LLM_ARCH_MINICPM:
  7755. {
  7756. result = llm.build_minicpm();
  7757. } break;
  7758. case LLM_ARCH_GEMMA:
  7759. {
  7760. result = llm.build_gemma();
  7761. } break;
  7762. case LLM_ARCH_STARCODER2:
  7763. {
  7764. result = llm.build_starcoder2();
  7765. } break;
  7766. case LLM_ARCH_MAMBA:
  7767. {
  7768. result = llm.build_mamba();
  7769. } break;
  7770. case LLM_ARCH_COMMAND_R:
  7771. {
  7772. result = llm.build_command_r();
  7773. } break;
  7774. default:
  7775. GGML_ASSERT(false);
  7776. }
  7777. llm.free();
  7778. return result;
  7779. }
  7780. static void llama_set_k_shift(llama_context & lctx) {
  7781. const int64_t kv_size = lctx.kv_self.size;
  7782. assert(ggml_backend_buffer_is_host(lctx.inp_K_shift->buffer));
  7783. int32_t * data = (int32_t *) lctx.inp_K_shift->data;
  7784. for (int i = 0; i < kv_size; ++i) {
  7785. data[i] = lctx.kv_self.cells[i].delta;
  7786. }
  7787. }
  7788. static void llama_set_s_copy(llama_context & lctx) {
  7789. const int64_t kv_size = lctx.kv_self.size;
  7790. assert(ggml_backend_buffer_is_host(lctx.inp_s_copy->buffer));
  7791. int32_t * data = (int32_t *) lctx.inp_s_copy->data;
  7792. for (int i = 0; i < kv_size; ++i) {
  7793. data[i] = lctx.kv_self.cells[i].src;
  7794. }
  7795. }
  7796. static void llama_set_inputs(llama_context & lctx, const llama_batch & batch) {
  7797. //
  7798. // set input data
  7799. //
  7800. const auto & hparams = lctx.model.hparams;
  7801. const auto & cparams = lctx.cparams;
  7802. const auto & kv_self = lctx.kv_self;
  7803. if (batch.token) {
  7804. const int64_t n_tokens = batch.n_tokens;
  7805. ggml_backend_tensor_set(lctx.inp_tokens, batch.token, 0, n_tokens*ggml_element_size(lctx.inp_tokens));
  7806. }
  7807. if (batch.embd) {
  7808. const int64_t n_embd = hparams.n_embd;
  7809. const int64_t n_tokens = batch.n_tokens;
  7810. ggml_backend_tensor_set(lctx.inp_embd, batch.embd, 0, n_tokens*n_embd*ggml_element_size(lctx.inp_embd));
  7811. }
  7812. if (batch.pos && lctx.inp_pos) {
  7813. const int64_t n_tokens = batch.n_tokens;
  7814. ggml_backend_tensor_set(lctx.inp_pos, batch.pos, 0, n_tokens*ggml_element_size(lctx.inp_pos));
  7815. }
  7816. if (hparams.causal_attn || cparams.pooling_type == LLAMA_POOLING_TYPE_NONE) {
  7817. GGML_ASSERT(lctx.inp_out_ids && "every model that can must skip unused outputs");
  7818. const int64_t n_tokens = batch.n_tokens;
  7819. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_out_ids->buffer));
  7820. int32_t * data = (int32_t *) lctx.inp_out_ids->data;
  7821. if (lctx.n_outputs == n_tokens) {
  7822. for (int i = 0; i < n_tokens; ++i) {
  7823. data[i] = i;
  7824. }
  7825. } else if (batch.logits) {
  7826. int32_t n_outputs = 0;
  7827. for (int i = 0; i < n_tokens; ++i) {
  7828. if (batch.logits[i]) {
  7829. data[n_outputs++] = i;
  7830. }
  7831. }
  7832. // the graph needs to have been passed the correct number of outputs
  7833. GGML_ASSERT(lctx.n_outputs == n_outputs);
  7834. } else if (lctx.n_outputs == 1) {
  7835. // only keep last output
  7836. data[0] = n_tokens - 1;
  7837. } else {
  7838. GGML_ASSERT(lctx.n_outputs == 0);
  7839. }
  7840. }
  7841. GGML_ASSERT(
  7842. // (!a || b) is a logical implication (a -> b)
  7843. // !hparams.causal_attn -> !cparams.causal_attn
  7844. (hparams.causal_attn || !cparams.causal_attn) &&
  7845. "causal attention with embedding models is not supported"
  7846. );
  7847. if (lctx.inp_KQ_mask) {
  7848. // NOTE: hparams.causal_attn indicates the model is capable of generation and uses the kv cache.
  7849. if (cparams.causal_attn) {
  7850. const int64_t n_kv = kv_self.n;
  7851. const int64_t n_tokens = batch.n_tokens;
  7852. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  7853. float * data = (float *) lctx.inp_KQ_mask->data;
  7854. // For causal attention, use only the previous KV cells
  7855. // of the correct sequence for each token of the batch.
  7856. // It's assumed that if a token in the batch has multiple sequences, they are equivalent.
  7857. for (int h = 0; h < 1; ++h) {
  7858. for (int j = 0; j < n_tokens; ++j) {
  7859. const llama_pos pos = batch.pos[j];
  7860. const llama_seq_id seq_id = batch.seq_id[j][0];
  7861. for (int i = 0; i < n_kv; ++i) {
  7862. float f;
  7863. if (!lctx.kv_self.cells[i].has_seq_id(seq_id) || lctx.kv_self.cells[i].pos > pos) {
  7864. f = -INFINITY;
  7865. } else {
  7866. f = 0.0f;
  7867. }
  7868. data[h*(n_kv*n_tokens) + j*n_kv + i] = f;
  7869. }
  7870. }
  7871. }
  7872. } else {
  7873. // when using kv cache, the mask needs to match the kv cache size
  7874. const int64_t n_tokens = batch.n_tokens;
  7875. const int64_t n_stride = hparams.causal_attn ? kv_self.n : n_tokens;
  7876. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  7877. float * data = (float *) lctx.inp_KQ_mask->data;
  7878. for (int h = 0; h < 1; ++h) {
  7879. for (int j = 0; j < n_tokens; ++j) {
  7880. const llama_seq_id seq_id = batch.seq_id[j][0];
  7881. for (int i = 0; i < n_tokens; ++i) {
  7882. float f = -INFINITY;
  7883. for (int s = 0; s < batch.n_seq_id[i]; ++s) {
  7884. if (batch.seq_id[i][s] == seq_id) {
  7885. f = 0.0f;
  7886. break;
  7887. }
  7888. }
  7889. data[h*(n_tokens*n_tokens) + j*n_stride + i] = f;
  7890. }
  7891. for (int i = n_tokens; i < n_stride; ++i) {
  7892. data[h*(n_tokens*n_tokens) + j*n_stride + i] = -INFINITY;
  7893. }
  7894. }
  7895. }
  7896. }
  7897. }
  7898. if (hparams.need_kq_pos) {
  7899. const int64_t n_kv = kv_self.n;
  7900. GGML_ASSERT(lctx.inp_KQ_pos);
  7901. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_pos->buffer));
  7902. float * data = (float *) lctx.inp_KQ_pos->data;
  7903. for (int i = 0; i < n_kv; ++i) {
  7904. data[i] = float(lctx.kv_self.cells[i].pos);
  7905. }
  7906. }
  7907. if (cparams.pooling_type == LLAMA_POOLING_TYPE_MEAN) {
  7908. const int64_t n_tokens = batch.n_tokens;
  7909. GGML_ASSERT(lctx.inp_mean);
  7910. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_mean->buffer));
  7911. float * data = (float *) lctx.inp_mean->data;
  7912. memset(lctx.inp_mean->data, 0, n_tokens * n_tokens * ggml_element_size(lctx.inp_mean));
  7913. std::vector<uint64_t> sum(n_tokens, 0);
  7914. for (int i = 0; i < n_tokens; ++i) {
  7915. const llama_seq_id seq_id = batch.seq_id[i][0];
  7916. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == MEAN");
  7917. sum[seq_id] += 1;
  7918. }
  7919. std::vector<float> div(n_tokens, 0.0f);
  7920. for (int i = 0; i < n_tokens; ++i) {
  7921. const uint64_t s = sum[i];
  7922. if (s > 0) {
  7923. div[i] = 1.0f/float(s);
  7924. }
  7925. }
  7926. for (int i = 0; i < n_tokens; ++i) {
  7927. const llama_seq_id seq_id = batch.seq_id[i][0];
  7928. data[seq_id*n_tokens + i] = div[seq_id];
  7929. }
  7930. }
  7931. if (cparams.pooling_type == LLAMA_POOLING_TYPE_CLS) {
  7932. const int64_t n_tokens = batch.n_tokens;
  7933. GGML_ASSERT(lctx.inp_cls);
  7934. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_cls->buffer));
  7935. uint32_t * data = (uint32_t *) lctx.inp_cls->data;
  7936. memset(lctx.inp_cls->data, 0, n_tokens * ggml_element_size(lctx.inp_cls));
  7937. for (int i = 0; i < n_tokens; ++i) {
  7938. const llama_seq_id seq_id = batch.seq_id[i][0];
  7939. const llama_pos pos = batch.pos[i];
  7940. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == CLS");
  7941. if (pos == 0) {
  7942. data[seq_id] = i;
  7943. }
  7944. }
  7945. }
  7946. if (kv_self.recurrent) {
  7947. const int64_t n_kv = kv_self.n;
  7948. if (lctx.inp_s_mask) {
  7949. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_s_mask->buffer));
  7950. float * data = (float *) lctx.inp_s_mask->data;
  7951. // states which are not affected by the current batch are left untouched
  7952. for (int i = 0; i < n_kv; ++i) {
  7953. llama_seq_id seq_id = i + lctx.kv_self.head;
  7954. llama_kv_cell & kv_cell = lctx.kv_self.cells[seq_id];
  7955. bool has_self_seq = kv_cell.has_seq_id(seq_id);
  7956. data[i] = (float) has_self_seq;
  7957. // ensure current sequences will be kept
  7958. if (!has_self_seq && kv_cell.pos >= 0) {
  7959. kv_cell.seq_id.insert(seq_id);
  7960. }
  7961. }
  7962. }
  7963. // For Mamba (and other recurrent architectures),
  7964. // update the correct state(s)/sequence(s) for each token of the batch.
  7965. // Like with the KQ_mask, if a token in the batch has multiple sequences,
  7966. // they are assumed to be equivalent (not here, but in ggml_ssm_scan and ggml_ssm_conv).
  7967. if (lctx.inp_s_seq) {
  7968. const int64_t n_tokens = batch.n_tokens;
  7969. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_s_seq->buffer));
  7970. int32_t * data = (int32_t *) lctx.inp_s_seq->data;
  7971. for (int j = 0; j < n_tokens; ++j) {
  7972. const int32_t n_seq = batch.n_seq_id[j];
  7973. GGML_ASSERT(0 < n_seq); // a token should be part of at least 1 sequence
  7974. for (int i = 0; i < n_kv; ++i) {
  7975. if (i < n_seq) {
  7976. // for this type of model, the head is the minimum seq_id of the batch
  7977. data[j*n_kv + i] = batch.seq_id[j][i] - kv_self.head;
  7978. } else {
  7979. data[j*n_kv + i] = -1;
  7980. }
  7981. }
  7982. }
  7983. }
  7984. }
  7985. }
  7986. // Make sure enough space is available for outputs.
  7987. // Returns max number of outputs for which space was reserved.
  7988. static size_t llama_output_reserve(llama_context & lctx, size_t n_outputs) {
  7989. const auto & cparams = lctx.cparams;
  7990. const auto & hparams = lctx.model.hparams;
  7991. const size_t n_outputs_max = std::max(n_outputs, (size_t) cparams.n_seq_max);
  7992. const auto n_batch = cparams.n_batch;
  7993. const auto n_vocab = hparams.n_vocab;
  7994. const auto n_embd = hparams.n_embd;
  7995. // TODO: use a per-batch flag for logits presence instead
  7996. const bool has_logits = cparams.causal_attn;
  7997. const bool has_embd = cparams.embeddings && (hparams.causal_attn || cparams.pooling_type == LLAMA_POOLING_TYPE_NONE);
  7998. const size_t logits_size = has_logits ? n_vocab*n_outputs_max : 0;
  7999. const size_t embd_size = has_embd ? n_embd*n_outputs_max : 0;
  8000. if (lctx.output_ids.empty()) {
  8001. // init, never resized afterwards
  8002. lctx.output_ids.resize(n_batch);
  8003. }
  8004. const size_t prev_size = lctx.buf_output ? ggml_backend_buffer_get_size(lctx.buf_output) : 0;
  8005. const size_t new_size = (logits_size + embd_size) * sizeof(float);
  8006. // alloc only when more than the current capacity is required
  8007. // TODO: also consider shrinking the buffer
  8008. if (!lctx.buf_output || prev_size < new_size) {
  8009. if (lctx.buf_output) {
  8010. #ifndef NDEBUG
  8011. // This doesn't happen often, but may be annoying in some cases (like the HellaSwag benchmark)
  8012. 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);
  8013. #endif
  8014. ggml_backend_buffer_free(lctx.buf_output);
  8015. lctx.buf_output = nullptr;
  8016. lctx.logits = nullptr;
  8017. lctx.embd = nullptr;
  8018. }
  8019. lctx.buf_output = ggml_backend_buft_alloc_buffer(llama_default_buffer_type_cpu(true), new_size);
  8020. if (lctx.buf_output == nullptr) {
  8021. LLAMA_LOG_ERROR("%s: failed to allocate output buffer of size %.2f MiB\n", __func__, new_size / (1024.0 * 1024.0));
  8022. return 0;
  8023. }
  8024. }
  8025. float * output_base = (float *) ggml_backend_buffer_get_base(lctx.buf_output);
  8026. lctx.logits = has_logits ? output_base : nullptr;
  8027. lctx.embd = has_embd ? output_base + logits_size : nullptr;
  8028. lctx.output_size = n_outputs_max;
  8029. lctx.logits_size = logits_size;
  8030. lctx.embd_size = embd_size;
  8031. // set all ids as invalid (negative)
  8032. std::fill(lctx.output_ids.begin(), lctx.output_ids.end(), -1);
  8033. ggml_backend_buffer_clear(lctx.buf_output, 0);
  8034. lctx.n_outputs = 0;
  8035. return n_outputs_max;
  8036. }
  8037. static void llama_graph_compute(
  8038. llama_context & lctx,
  8039. ggml_cgraph * gf,
  8040. int n_threads) {
  8041. #ifdef GGML_USE_MPI
  8042. const int64_t n_layer = lctx.model.hparams.n_layer;
  8043. ggml_mpi_graph_compute_pre(lctx.ctx_mpi, gf, n_layer);
  8044. #endif
  8045. #ifdef GGML_USE_METAL
  8046. if (ggml_backend_is_metal(lctx.backend_metal)) {
  8047. ggml_backend_metal_set_n_cb(lctx.backend_metal, n_threads);
  8048. }
  8049. #endif
  8050. if (lctx.backend_cpu != nullptr) {
  8051. ggml_backend_cpu_set_n_threads(lctx.backend_cpu, n_threads);
  8052. ggml_backend_cpu_set_abort_callback(lctx.backend_cpu, lctx.abort_callback, lctx.abort_callback_data);
  8053. }
  8054. ggml_backend_sched_graph_compute_async(lctx.sched, gf);
  8055. // fprintf(stderr, "splits: %d\n", ggml_backend_sched_get_n_splits(lctx.sched));
  8056. #ifdef GGML_USE_MPI
  8057. ggml_mpi_graph_compute_post(lctx.ctx_mpi, gf, n_layer);
  8058. #endif
  8059. }
  8060. // decode a batch of tokens by evaluating the transformer
  8061. //
  8062. // - lctx: llama context
  8063. // - batch: batch to evaluate
  8064. //
  8065. // return 0 on success
  8066. // return positive int on warning
  8067. // return negative int on error
  8068. //
  8069. static int llama_decode_internal(
  8070. llama_context & lctx,
  8071. llama_batch batch_all) { // TODO: rename back to batch
  8072. const uint32_t n_tokens_all = batch_all.n_tokens;
  8073. if (n_tokens_all == 0) {
  8074. LLAMA_LOG_ERROR("%s: n_tokens == 0", __func__);
  8075. return -1;
  8076. }
  8077. const auto & model = lctx.model;
  8078. const auto & hparams = model.hparams;
  8079. const auto & cparams = lctx.cparams;
  8080. GGML_ASSERT((!batch_all.token && batch_all.embd) || (batch_all.token && !batch_all.embd)); // NOLINT
  8081. GGML_ASSERT(n_tokens_all <= cparams.n_batch);
  8082. GGML_ASSERT((cparams.causal_attn || cparams.n_ubatch >= n_tokens_all) && "non-causal attention requires n_ubatch >= n_tokens");
  8083. if (lctx.t_compute_start_us == 0) {
  8084. lctx.t_compute_start_us = ggml_time_us();
  8085. }
  8086. lctx.n_queued_tokens += n_tokens_all;
  8087. #ifdef GGML_USE_MPI
  8088. // TODO: needs fix after #3228
  8089. GGML_ASSERT(false && "not implemented");
  8090. //ggml_mpi_eval_init(lctx.ctx_mpi, &n_tokens, &n_past, &n_threads);
  8091. #endif
  8092. auto & kv_self = lctx.kv_self;
  8093. const int64_t n_embd = hparams.n_embd;
  8094. const int64_t n_vocab = hparams.n_vocab;
  8095. uint32_t n_outputs = 0;
  8096. uint32_t n_outputs_prev = 0;
  8097. const auto n_ubatch = cparams.n_ubatch;
  8098. std::vector<llama_pos> pos;
  8099. std::vector<int32_t> n_seq_id;
  8100. std::vector<llama_seq_id *> seq_id_arr;
  8101. std::vector<std::vector<llama_seq_id>> seq_id;
  8102. // count outputs
  8103. if (batch_all.logits) {
  8104. for (uint32_t i = 0; i < n_tokens_all; ++i) {
  8105. n_outputs += batch_all.logits[i] != 0;
  8106. }
  8107. } else if (lctx.logits_all || (cparams.embeddings && cparams.pooling_type != LLAMA_POOLING_TYPE_NONE)) {
  8108. n_outputs = n_tokens_all;
  8109. } else {
  8110. // keep last output only
  8111. n_outputs = 1;
  8112. }
  8113. // reserve output buffer
  8114. if (llama_output_reserve(lctx, n_outputs) < n_outputs) {
  8115. LLAMA_LOG_ERROR("%s: could not reserve space for batch with %u outputs\n", __func__, n_outputs);
  8116. return -2;
  8117. };
  8118. // set output mappings
  8119. if (batch_all.logits) {
  8120. int32_t i_logits = 0;
  8121. for (uint32_t i = 0; i < n_tokens_all; ++i) {
  8122. if (batch_all.logits[i]) {
  8123. lctx.output_ids[i] = i_logits++;
  8124. }
  8125. }
  8126. } else {
  8127. for (uint32_t i = 0; i < n_outputs; ++i) {
  8128. lctx.output_ids[i] = i;
  8129. }
  8130. }
  8131. for (uint32_t cur_token = 0; cur_token < n_tokens_all; cur_token += n_ubatch) {
  8132. const uint32_t n_tokens = std::min(n_ubatch, n_tokens_all - cur_token);
  8133. llama_batch u_batch = {
  8134. /* .n_tokens = */ (int32_t) n_tokens,
  8135. /* .token = */ batch_all.token ? batch_all.token + cur_token : nullptr,
  8136. /* .embd = */ batch_all.embd ? batch_all.embd + cur_token*n_embd : nullptr,
  8137. /* .pos = */ batch_all.pos ? batch_all.pos + cur_token : nullptr,
  8138. /* .n_seq_id = */ batch_all.n_seq_id ? batch_all.n_seq_id + cur_token : nullptr,
  8139. /* .seq_id = */ batch_all.seq_id ? batch_all.seq_id + cur_token : nullptr,
  8140. /* .logits = */ batch_all.logits ? batch_all.logits + cur_token : nullptr,
  8141. /* .all_pos_0 = */ batch_all.all_pos_0 + (llama_pos) cur_token*batch_all.all_pos_1,
  8142. /* .all_pos_1 = */ batch_all.all_pos_1,
  8143. /* .all_seq_id = */ batch_all.all_seq_id,
  8144. };
  8145. // count the outputs in this u_batch
  8146. {
  8147. int32_t n_outputs_new = 0;
  8148. if (u_batch.logits) {
  8149. for (uint32_t i = 0; i < n_tokens; i++) {
  8150. n_outputs_new += u_batch.logits[i] != 0;
  8151. }
  8152. } else if (n_outputs == n_tokens_all) {
  8153. n_outputs_new = n_tokens;
  8154. } else {
  8155. // keep last output only
  8156. if (cur_token + n_tokens >= n_tokens_all) {
  8157. n_outputs_new = 1;
  8158. }
  8159. }
  8160. // needs to happen before the graph is built
  8161. lctx.n_outputs = n_outputs_new;
  8162. }
  8163. int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  8164. GGML_ASSERT(n_threads > 0);
  8165. // helpers for smoother batch API transition
  8166. // after deprecating the llama_eval calls, these will be removed
  8167. if (u_batch.pos == nullptr) {
  8168. pos.resize(n_tokens);
  8169. for (uint32_t i = 0; i < n_tokens; i++) {
  8170. pos[i] = u_batch.all_pos_0 + i*u_batch.all_pos_1;
  8171. }
  8172. u_batch.pos = pos.data();
  8173. }
  8174. if (u_batch.seq_id == nullptr) {
  8175. n_seq_id.resize(n_tokens);
  8176. seq_id.resize(n_tokens);
  8177. seq_id_arr.resize(n_tokens);
  8178. for (uint32_t i = 0; i < n_tokens; i++) {
  8179. n_seq_id[i] = 1;
  8180. seq_id[i].resize(1);
  8181. seq_id[i][0] = u_batch.all_seq_id;
  8182. seq_id_arr[i] = seq_id[i].data();
  8183. }
  8184. u_batch.n_seq_id = n_seq_id.data();
  8185. u_batch.seq_id = seq_id_arr.data();
  8186. }
  8187. // non-causal masks do not use the KV cache
  8188. if (hparams.causal_attn) {
  8189. llama_kv_cache_update(&lctx);
  8190. // if we have enough unused cells before the current head ->
  8191. // better to start searching from the beginning of the cache, hoping to fill it
  8192. if (kv_self.head > kv_self.used + 2*n_tokens) {
  8193. kv_self.head = 0;
  8194. }
  8195. if (!llama_kv_cache_find_slot(kv_self, u_batch)) {
  8196. return 1;
  8197. }
  8198. if (!kv_self.recurrent) {
  8199. // a heuristic, to avoid attending the full cache if it is not yet utilized
  8200. // after enough generations, the benefit from this heuristic disappears
  8201. // if we start defragmenting the cache, the benefit from this will be more important
  8202. kv_self.n = std::min(kv_self.size, std::max(32u, GGML_PAD(llama_kv_cache_cell_max(kv_self), 32)));
  8203. //kv_self.n = llama_kv_cache_cell_max(kv_self);
  8204. }
  8205. }
  8206. //printf("kv_self.n = %5d, kv_self.used = %5d, kv_self.head = %5d\n", kv_self.n, kv_self.used, kv_self.head);
  8207. ggml_backend_sched_reset(lctx.sched);
  8208. ggml_backend_sched_set_eval_callback(lctx.sched, lctx.cparams.cb_eval, lctx.cparams.cb_eval_user_data);
  8209. ggml_cgraph * gf = llama_build_graph(lctx, u_batch, false);
  8210. // the output is always the last tensor in the graph
  8211. struct ggml_tensor * res = gf->nodes[gf->n_nodes - 1];
  8212. struct ggml_tensor * embd = gf->nodes[gf->n_nodes - 2];
  8213. if (lctx.n_outputs == 0) {
  8214. // no output
  8215. res = nullptr;
  8216. embd = nullptr;
  8217. } else if (!hparams.causal_attn) {
  8218. res = nullptr; // do not extract logits for embedding models such as BERT
  8219. // token or sequence embeddings
  8220. embd = gf->nodes[gf->n_nodes - 1];
  8221. GGML_ASSERT(strcmp(embd->name, "result_embd") == 0 || strcmp(embd->name, "result_embd_pooled") == 0);
  8222. } else if (cparams.embeddings) {
  8223. // the embeddings could be in the second to last tensor, or any of the previous tensors
  8224. int i_embd = gf->n_nodes - 2;
  8225. for (int i = 3; strcmp(embd->name, "result_norm") != 0; ++i) {
  8226. i_embd = gf->n_nodes - i;
  8227. if (i_embd < 0) { break; }
  8228. embd = gf->nodes[i_embd];
  8229. }
  8230. GGML_ASSERT(i_embd >= 0 && "missing result_norm tensor");
  8231. // TODO: use a per-batch flag to know when to skip logits while keeping embeddings
  8232. if (!cparams.causal_attn) {
  8233. res = nullptr; // do not extract logits when not needed
  8234. // skip computing logits
  8235. // TODO: is this safe?
  8236. gf->n_nodes = i_embd + 1;
  8237. }
  8238. } else {
  8239. embd = nullptr; // do not extract embeddings when not needed
  8240. GGML_ASSERT(strcmp(res->name, "result_output") == 0 && "missing result_output tensor");
  8241. }
  8242. // 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);
  8243. // for big prompts, if BLAS is enabled, it is better to use only one thread
  8244. // otherwise, the threads are spin-lock waiting for the BLAS calls and are degrading the performance
  8245. // TODO: this is mostly important for Apple Silicon where CBLAS is still performing very well
  8246. // we still need some threads to process all non-mul_mat ops, but not too much to avoid interfering
  8247. // with the BLAS calls. need a better solution
  8248. // MoE Special Case: This logic applies when hparams.n_expert == 0, i.e. the model is NOT an MoE model. When an MoE is
  8249. // being processed then Accelerate/BLAS will not be involved, so capping would limit performance.
  8250. if (n_tokens >= 32 && hparams.n_expert == 0 && ggml_cpu_has_blas() && !ggml_cpu_has_gpublas()) {
  8251. n_threads = std::min(4, n_threads);
  8252. }
  8253. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  8254. llama_set_inputs(lctx, u_batch);
  8255. llama_graph_compute(lctx, gf, n_threads);
  8256. // update the kv ring buffer
  8257. {
  8258. kv_self.head += n_tokens;
  8259. // Ensure kv cache head points to a valid index.
  8260. if (kv_self.head >= kv_self.size) {
  8261. kv_self.head = 0;
  8262. }
  8263. }
  8264. #ifdef GGML_PERF
  8265. // print timing information per ggml operation (for debugging purposes)
  8266. // requires GGML_PERF to be defined
  8267. ggml_graph_print(gf);
  8268. #endif
  8269. // plot the computation graph in dot format (for debugging purposes)
  8270. //if (n_past%100 == 0) {
  8271. // ggml_graph_dump_dot(gf, NULL, "llama.dot");
  8272. //}
  8273. // extract logits
  8274. if (res) {
  8275. ggml_backend_t backend_res = ggml_backend_sched_get_tensor_backend(lctx.sched, res);
  8276. GGML_ASSERT(backend_res != nullptr);
  8277. GGML_ASSERT(lctx.logits != nullptr);
  8278. float * logits_out = lctx.logits + n_outputs_prev*n_vocab;
  8279. const int32_t n_outputs_new = lctx.n_outputs;
  8280. if (n_outputs_new) {
  8281. GGML_ASSERT( n_outputs_prev + n_outputs_new <= n_outputs);
  8282. GGML_ASSERT((n_outputs_prev + n_outputs_new)*n_vocab <= (int64_t) lctx.logits_size);
  8283. ggml_backend_tensor_get_async(backend_res, res, logits_out, 0, n_outputs_new*n_vocab*sizeof(float));
  8284. }
  8285. }
  8286. // extract embeddings
  8287. if (embd) {
  8288. ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend(lctx.sched, embd);
  8289. GGML_ASSERT(backend_embd != nullptr);
  8290. switch (cparams.pooling_type) {
  8291. case LLAMA_POOLING_TYPE_NONE:
  8292. {
  8293. // extract token embeddings
  8294. GGML_ASSERT(lctx.embd != nullptr);
  8295. float * embd_out = lctx.embd + n_outputs_prev*n_embd;
  8296. const int32_t n_outputs_new = lctx.n_outputs;
  8297. if (n_outputs_new) {
  8298. GGML_ASSERT( n_outputs_prev + n_outputs_new <= n_outputs);
  8299. GGML_ASSERT((n_outputs_prev + n_outputs_new)*n_embd <= (int64_t) lctx.embd_size);
  8300. ggml_backend_tensor_get_async(backend_embd, embd, embd_out, 0, n_outputs_new*n_embd*sizeof(float));
  8301. }
  8302. } break;
  8303. case LLAMA_POOLING_TYPE_CLS:
  8304. case LLAMA_POOLING_TYPE_MEAN:
  8305. {
  8306. GGML_ASSERT(strcmp(embd->name, "result_embd_pooled") == 0);
  8307. // extract sequence embeddings
  8308. auto & embd_seq_out = lctx.embd_seq;
  8309. embd_seq_out.clear();
  8310. for (uint32_t i = 0; i < n_tokens; i++) {
  8311. const llama_seq_id seq_id = u_batch.seq_id[i][0];
  8312. if (embd_seq_out.find(seq_id) != embd_seq_out.end()) {
  8313. continue;
  8314. }
  8315. embd_seq_out[seq_id].resize(n_embd);
  8316. ggml_backend_tensor_get_async(backend_embd, embd, embd_seq_out[seq_id].data(), (n_embd*seq_id)*sizeof(float), n_embd*sizeof(float));
  8317. }
  8318. } break;
  8319. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  8320. {
  8321. GGML_ASSERT(false && "unknown pooling type");
  8322. } break;
  8323. }
  8324. }
  8325. n_outputs_prev += lctx.n_outputs;
  8326. }
  8327. // wait for the computation to finish (automatically done when obtaining the model output)
  8328. //llama_synchronize(&lctx);
  8329. // decide if we need to defrag the kv cache
  8330. if (cparams.causal_attn && cparams.defrag_thold >= 0.0f) {
  8331. const float fragmentation = kv_self.n >= 128 ? 1.0f - float(kv_self.used)/float(kv_self.n) : 0.0f;
  8332. // queue defragmentation for next llama_kv_cache_update
  8333. if (fragmentation > cparams.defrag_thold) {
  8334. //LLAMA_LOG_INFO("fragmentation: %.2f\n", fragmentation);
  8335. llama_kv_cache_defrag(kv_self);
  8336. }
  8337. }
  8338. return 0;
  8339. }
  8340. // find holes from the beginning of the KV cache and fill them by moving data from the end of the cache
  8341. static void llama_kv_cache_defrag_internal(struct llama_context & lctx) {
  8342. auto & kv_self = lctx.kv_self;
  8343. const auto & hparams = lctx.model.hparams;
  8344. const uint32_t n_layer = hparams.n_layer;
  8345. const uint32_t n_kv = llama_kv_cache_cell_max(kv_self);
  8346. const uint32_t n_used = kv_self.used;
  8347. assert(n_used <= n_kv);
  8348. //const int64_t t_start = ggml_time_us();
  8349. // number of cells moved
  8350. uint32_t n_moves = 0;
  8351. // each move requires 6*n_layer tensors (see build_defrag)
  8352. // - source view, destination view, copy operation
  8353. // - x2 for keys and values
  8354. const uint32_t max_moves = LLAMA_MAX_NODES/(6*n_layer);
  8355. // determine which KV cells to move where
  8356. //
  8357. // cell i moves to ids[i]
  8358. //
  8359. // if ids[i] == i || ids[i] == n_kv, then cell i is not moved
  8360. //
  8361. std::vector<uint32_t> ids(n_kv, n_kv);
  8362. for (uint32_t i0 = 0; i0 < n_used; ++i0) {
  8363. const auto & cell0 = kv_self.cells[i0];
  8364. if (!cell0.is_empty()) {
  8365. ids[i0] = i0;
  8366. continue;
  8367. }
  8368. // found a hole - fill it with data from the end of the cache
  8369. uint32_t nh = 1;
  8370. // determine the size of the hole
  8371. while (i0 + nh < n_used && kv_self.cells[i0 + nh].is_empty()) {
  8372. nh++;
  8373. }
  8374. uint32_t nf = 0;
  8375. uint32_t is = n_kv - 1;
  8376. // starting from the end, find nh non-empty cells
  8377. for (; is > i0; --is) {
  8378. const auto & cell1 = kv_self.cells[is];
  8379. if (cell1.is_empty() || ids[is] != n_kv) {
  8380. continue;
  8381. }
  8382. // non-empty cell which is not yet moved
  8383. nf++;
  8384. if (nf == nh) {
  8385. break;
  8386. }
  8387. }
  8388. // this can only happen if `n_used` is not accurate, which would be a bug
  8389. GGML_ASSERT(nf == nh && "KV defrag bug: nf != nh");
  8390. nf = 0;
  8391. uint32_t i1 = is;
  8392. // are we moving a continuous block of memory?
  8393. bool cont = false;
  8394. // should we stop searching for the next move?
  8395. bool stop = false;
  8396. // go back and move the nf cells to the hole
  8397. for (; i1 < n_kv; ++i1) {
  8398. auto & cell1 = kv_self.cells[i1];
  8399. if (cell1.is_empty() || ids[i1] != n_kv) {
  8400. if (n_moves == max_moves) {
  8401. stop = true;
  8402. break;
  8403. }
  8404. cont = false;
  8405. continue;
  8406. }
  8407. // this cell goes to (i0 + nf)
  8408. ids[i1] = i0 + nf;
  8409. // move the cell meta data
  8410. kv_self.cells[i0 + nf] = cell1;
  8411. // clear the old cell and move the head there
  8412. cell1 = llama_kv_cell();
  8413. kv_self.head = n_used;
  8414. if (!cont) {
  8415. n_moves++;
  8416. cont = true;
  8417. }
  8418. nf++;
  8419. if (nf == nh) {
  8420. break;
  8421. }
  8422. }
  8423. if (stop || n_moves == max_moves) {
  8424. break;
  8425. }
  8426. //LLAMA_LOG_INFO("(tmp log) KV defrag: move [%u, %u) to [%u, %u)\n", is, i1 + 1, i0, i0 + nh);
  8427. i0 += nh - 1;
  8428. }
  8429. if (n_moves == 0) {
  8430. return;
  8431. }
  8432. //LLAMA_LOG_INFO("(tmp log) KV defrag cell moves: %u\n", n_moves);
  8433. //LLAMA_LOG_INFO("expected gf nodes: %u\n", 6*n_moves*n_layer);
  8434. #if 0
  8435. // CPU defrag
  8436. //
  8437. // TODO: optimizations are possible:
  8438. // - multiple threads
  8439. // - avoid copying to the host memory when already there
  8440. //
  8441. // likely not worth the effort, as we have ggml_graph based defrag
  8442. //
  8443. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  8444. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  8445. const uint32_t kv_size = kv_self.size;
  8446. std::vector<uint8_t> buf_k;
  8447. std::vector<uint8_t> buf_v;
  8448. for (uint32_t il = 0; il < n_layer; ++il) {
  8449. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  8450. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_size);
  8451. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  8452. const size_t v_size = ggml_row_size (kv_self.v_l[il]->type, n_embd_v_gqa*kv_size);
  8453. buf_k.resize(k_size);
  8454. buf_v.resize(v_size);
  8455. ggml_backend_tensor_get(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  8456. ggml_backend_tensor_get(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  8457. // batch move [i, i+nm) to [id, id+nm)
  8458. // note: cells can move only to a lower index
  8459. for (uint32_t i = 0; i < n_kv; ++i) {
  8460. const uint32_t id = ids[i];
  8461. if (i == id || id == n_kv) {
  8462. continue;
  8463. }
  8464. uint32_t nm = 1;
  8465. while (i + nm < n_kv && ids[i + nm] == id + nm) {
  8466. nm++;
  8467. }
  8468. // move keys
  8469. {
  8470. const int64_t os = i*k_size_row;
  8471. const int64_t od = id*k_size_row;
  8472. memcpy(buf_k.data() + od, buf_k.data() + os, nm*k_size_row);
  8473. }
  8474. // move values (note: they are transposed)
  8475. {
  8476. const int64_t os = i;
  8477. const int64_t od = id;
  8478. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  8479. 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);
  8480. }
  8481. }
  8482. i += nm - 1;
  8483. }
  8484. ggml_backend_tensor_set(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  8485. ggml_backend_tensor_set(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  8486. }
  8487. #else
  8488. // ggml_graph defrag
  8489. ggml_backend_sched_reset(lctx.sched);
  8490. ggml_cgraph * gf = llama_build_graph_defrag(lctx, ids);
  8491. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  8492. #endif
  8493. //const int64_t t_end = ggml_time_us();
  8494. //LLAMA_LOG_INFO("(tmp log) KV defrag time: %.3f ms\n", (t_end - t_start)/1000.0);
  8495. }
  8496. static void llama_kv_cache_update_internal(struct llama_context & lctx) {
  8497. bool need_reserve = false;
  8498. // apply K-shift if needed
  8499. if (lctx.model.hparams.rope_type != LLAMA_ROPE_TYPE_NONE && lctx.kv_self.has_shift) {
  8500. {
  8501. ggml_backend_sched_reset(lctx.sched);
  8502. ggml_cgraph * gf = llama_build_graph_k_shift(lctx);
  8503. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  8504. llama_set_k_shift(lctx);
  8505. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  8506. need_reserve = true;
  8507. }
  8508. {
  8509. auto & kv_self = lctx.kv_self;
  8510. kv_self.has_shift = false;
  8511. for (uint32_t i = 0; i < kv_self.size; ++i) {
  8512. kv_self.cells[i].delta = 0;
  8513. }
  8514. }
  8515. }
  8516. if (lctx.kv_self.recurrent && lctx.kv_self.do_copy) {
  8517. {
  8518. ggml_backend_sched_reset(lctx.sched);
  8519. ggml_cgraph * gf = llama_build_graph_s_copy(lctx);
  8520. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  8521. llama_set_s_copy(lctx);
  8522. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  8523. need_reserve = true;
  8524. }
  8525. {
  8526. auto & kv_self = lctx.kv_self;
  8527. kv_self.do_copy = false;
  8528. for (uint32_t i = 0; i < kv_self.size; ++i) {
  8529. kv_self.cells[i].src = i;
  8530. }
  8531. }
  8532. }
  8533. // defragment the KV cache if needed
  8534. if (lctx.kv_self.do_defrag) {
  8535. llama_kv_cache_defrag_internal(lctx);
  8536. need_reserve = true;
  8537. lctx.kv_self.do_defrag = false;
  8538. }
  8539. // reserve a worst case graph again
  8540. if (need_reserve) {
  8541. // TODO: extract to a function
  8542. // build worst-case graph
  8543. int n_tokens = (int)std::min(lctx.cparams.n_ctx, lctx.cparams.n_ubatch);
  8544. int n_past = lctx.cparams.n_ctx - n_tokens;
  8545. 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
  8546. ggml_cgraph * gf = llama_build_graph(lctx, llama_batch_get_one(&token, n_tokens, n_past, 0), true);
  8547. // initialize scheduler with the worst-case graph
  8548. ggml_backend_sched_reset(lctx.sched);
  8549. if (!ggml_backend_sched_reserve(lctx.sched, gf)) {
  8550. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  8551. }
  8552. }
  8553. }
  8554. //
  8555. // tokenizer
  8556. //
  8557. static enum llama_vocab_type llama_vocab_get_type(const llama_vocab & vocab) {
  8558. return vocab.type;
  8559. }
  8560. static bool llama_is_normal_token(const llama_vocab & vocab, llama_token id) {
  8561. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  8562. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL;
  8563. }
  8564. static bool llama_is_unknown_token(const llama_vocab & vocab, llama_token id) {
  8565. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  8566. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_UNKNOWN;
  8567. }
  8568. static bool llama_is_control_token(const llama_vocab & vocab, llama_token id) {
  8569. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  8570. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_CONTROL;
  8571. }
  8572. static bool llama_is_byte_token(const llama_vocab & vocab, llama_token id) {
  8573. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  8574. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_BYTE;
  8575. }
  8576. static bool llama_is_user_defined_token(const llama_vocab& vocab, llama_token id) {
  8577. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  8578. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_USER_DEFINED;
  8579. }
  8580. static uint8_t llama_token_to_byte(const llama_vocab& vocab, llama_token id) {
  8581. GGML_ASSERT(llama_vocab_get_type(vocab) != LLAMA_VOCAB_TYPE_NONE);
  8582. GGML_ASSERT(llama_is_byte_token(vocab, id));
  8583. const auto& token_data = vocab.id_to_token.at(id);
  8584. switch (llama_vocab_get_type(vocab)) {
  8585. case LLAMA_VOCAB_TYPE_SPM: {
  8586. auto buf = token_data.text.substr(3, 2);
  8587. return strtol(buf.c_str(), NULL, 16);
  8588. }
  8589. case LLAMA_VOCAB_TYPE_BPE: {
  8590. GGML_ASSERT(false);
  8591. return unicode_utf8_to_byte(token_data.text);
  8592. }
  8593. case LLAMA_VOCAB_TYPE_WPM: {
  8594. GGML_ASSERT(false);
  8595. }
  8596. default:
  8597. GGML_ASSERT(false);
  8598. }
  8599. }
  8600. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch) {
  8601. GGML_ASSERT(llama_vocab_get_type(vocab) != LLAMA_VOCAB_TYPE_NONE);
  8602. static const char * hex = "0123456789ABCDEF";
  8603. switch (llama_vocab_get_type(vocab)) {
  8604. case LLAMA_VOCAB_TYPE_SPM: {
  8605. const char buf[7] = { '<', '0', 'x', hex[ch >> 4], hex[ch & 15], '>', 0 };
  8606. auto token = vocab.token_to_id.find(buf);
  8607. if (token != vocab.token_to_id.end()) {
  8608. return (*token).second;
  8609. }
  8610. // Try to fall back to just the byte as a string
  8611. const char buf2[2] = { (char)ch, 0 };
  8612. return vocab.token_to_id.at(buf2);
  8613. }
  8614. case LLAMA_VOCAB_TYPE_WPM:
  8615. case LLAMA_VOCAB_TYPE_BPE: {
  8616. return vocab.token_to_id.at(unicode_byte_to_utf8(ch));
  8617. }
  8618. default:
  8619. GGML_ASSERT(false);
  8620. }
  8621. }
  8622. static void llama_escape_whitespace(std::string & text) {
  8623. replace_all(text, " ", "\xe2\x96\x81");
  8624. }
  8625. static void llama_unescape_whitespace(std::string & word) {
  8626. replace_all(word, "\xe2\x96\x81", " ");
  8627. }
  8628. struct llm_symbol {
  8629. using index = int;
  8630. index prev;
  8631. index next;
  8632. const char * text;
  8633. size_t n;
  8634. };
  8635. static_assert(std::is_trivially_copyable<llm_symbol>::value, "llm_symbol is not trivially copyable");
  8636. // SPM tokenizer
  8637. // original implementation:
  8638. // https://github.com/ggerganov/llama.cpp/commit/074bea2eb1f1349a0118239c4152914aecaa1be4
  8639. struct llm_bigram_spm {
  8640. struct comparator {
  8641. bool operator()(llm_bigram_spm & l, llm_bigram_spm & r) {
  8642. return (l.score < r.score) || (l.score == r.score && l.left > r.left);
  8643. }
  8644. };
  8645. using queue_storage = std::vector<llm_bigram_spm>;
  8646. using queue = std::priority_queue<llm_bigram_spm, queue_storage, comparator>;
  8647. llm_symbol::index left;
  8648. llm_symbol::index right;
  8649. float score;
  8650. size_t size;
  8651. };
  8652. struct llm_tokenizer_spm {
  8653. llm_tokenizer_spm(const llama_vocab & vocab) : vocab(vocab) {}
  8654. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  8655. // split string into utf8 chars
  8656. int index = 0;
  8657. size_t offs = 0;
  8658. while (offs < text.size()) {
  8659. llm_symbol sym;
  8660. size_t len = utf8_len(text[offs]);
  8661. sym.text = text.c_str() + offs;
  8662. sym.n = std::min(len, text.size() - offs);
  8663. offs += sym.n;
  8664. sym.prev = index - 1;
  8665. sym.next = offs == text.size() ? -1 : index + 1;
  8666. index++;
  8667. symbols.emplace_back(sym);
  8668. }
  8669. // seed the work queue with all possible 2-character tokens.
  8670. for (size_t i = 1; i < symbols.size(); ++i) {
  8671. try_add_bigram(i - 1, i);
  8672. }
  8673. // keep substituting the highest frequency pairs for as long as we can.
  8674. while (!work_queue.empty()) {
  8675. auto bigram = work_queue.top();
  8676. work_queue.pop();
  8677. auto & left_sym = symbols[bigram.left];
  8678. auto & right_sym = symbols[bigram.right];
  8679. // if one of the symbols already got merged, skip it.
  8680. if (left_sym.n == 0 || right_sym.n == 0 ||
  8681. left_sym.n + right_sym.n != bigram.size) {
  8682. continue;
  8683. }
  8684. // merge the right sym into the left one
  8685. left_sym.n += right_sym.n;
  8686. right_sym.n = 0;
  8687. //LLAMA_LOG_INFO("left = '%*s' size = %zu\n", (int) left_sym.n, left_sym.text, bigram.size);
  8688. // remove the right sym from the chain
  8689. left_sym.next = right_sym.next;
  8690. if (right_sym.next >= 0) {
  8691. symbols[right_sym.next].prev = bigram.left;
  8692. }
  8693. // find more substitutions
  8694. try_add_bigram(left_sym.prev, bigram.left);
  8695. try_add_bigram(bigram.left, left_sym.next);
  8696. }
  8697. for (int i = 0; i != -1; i = symbols[i].next) {
  8698. auto & symbol = symbols[i];
  8699. resegment(symbol, output);
  8700. }
  8701. }
  8702. private:
  8703. void resegment(llm_symbol & symbol, std::vector<llama_vocab::id> & output) {
  8704. auto text = std::string(symbol.text, symbol.n);
  8705. auto token = vocab.token_to_id.find(text);
  8706. // Do we need to support is_unused?
  8707. if (token != vocab.token_to_id.end()) {
  8708. output.push_back((*token).second);
  8709. return;
  8710. }
  8711. const auto p = rev_merge.find(text);
  8712. if (p == rev_merge.end()) {
  8713. // output any symbols that did not form tokens as bytes.
  8714. output.reserve(output.size() + symbol.n);
  8715. for (int j = 0; j < (int)symbol.n; ++j) {
  8716. llama_vocab::id token_id = llama_byte_to_token(vocab, symbol.text[j]);
  8717. output.push_back(token_id);
  8718. }
  8719. return;
  8720. }
  8721. resegment(symbols[p->second.first], output);
  8722. resegment(symbols[p->second.second], output);
  8723. }
  8724. void try_add_bigram(int left, int right) {
  8725. if (left == -1 || right == -1) {
  8726. return;
  8727. }
  8728. const std::string text = std::string(symbols[left].text, symbols[left].n + symbols[right].n);
  8729. auto token = vocab.token_to_id.find(text);
  8730. if (token == vocab.token_to_id.end()) {
  8731. return;
  8732. }
  8733. if (static_cast<size_t>((*token).second) >= vocab.id_to_token.size()) {
  8734. return;
  8735. }
  8736. const auto & tok_data = vocab.id_to_token[(*token).second];
  8737. llm_bigram_spm bigram;
  8738. bigram.left = left;
  8739. bigram.right = right;
  8740. bigram.score = tok_data.score;
  8741. bigram.size = text.size();
  8742. work_queue.push(bigram);
  8743. // Do we need to support is_unused?
  8744. rev_merge[text] = std::make_pair(left, right);
  8745. }
  8746. const llama_vocab & vocab;
  8747. std::vector<llm_symbol> symbols;
  8748. llm_bigram_spm::queue work_queue;
  8749. std::map<std::string, std::pair<int, int>> rev_merge;
  8750. };
  8751. // BPE tokenizer
  8752. // adapted from https://github.com/cmp-nct/ggllm.cpp [MIT License]
  8753. // tried to simplify unicode stuff, so most likely does not work 100% correctly!
  8754. // TODO: there are a lot of common parts between spm and bpe tokenizers, should be refactored and reused
  8755. struct llm_bigram_bpe {
  8756. struct comparator {
  8757. bool operator()(const llm_bigram_bpe & l, const llm_bigram_bpe & r) const {
  8758. return l.rank > r.rank || (l.rank == r.rank && l.left > r.left);
  8759. }
  8760. };
  8761. using queue_storage = std::vector<llm_bigram_bpe>;
  8762. using queue = std::priority_queue<llm_bigram_bpe, queue_storage, comparator>;
  8763. llm_symbol::index left;
  8764. llm_symbol::index right;
  8765. std::string text;
  8766. int rank;
  8767. size_t size;
  8768. };
  8769. struct llm_tokenizer_bpe {
  8770. llm_tokenizer_bpe(const llama_vocab & vocab): vocab(vocab) {}
  8771. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  8772. int final_prev_index = -1;
  8773. auto word_collection = bpe_gpt2_preprocess(text);
  8774. symbols_final.clear();
  8775. for (auto & word : word_collection) {
  8776. work_queue = llm_bigram_bpe::queue();
  8777. symbols.clear();
  8778. int index = 0;
  8779. size_t offset = 0;
  8780. while (offset < word.size()) {
  8781. llm_symbol sym;
  8782. size_t char_len = std::min(word.size() - offset, (size_t) ::utf8_len(word[offset]));
  8783. sym.text = word.c_str() + offset;
  8784. sym.n = char_len;
  8785. offset += sym.n;
  8786. sym.prev = index - 1;
  8787. sym.next = offset == word.size() ? -1 : index + 1;
  8788. index++;
  8789. symbols.emplace_back(sym);
  8790. }
  8791. for (size_t i = 1; i < symbols.size(); ++i) {
  8792. add_new_bigram(i - 1, i);
  8793. }
  8794. // build token(s)
  8795. while (!work_queue.empty()) {
  8796. auto bigram = work_queue.top();
  8797. work_queue.pop();
  8798. auto & left_symbol = symbols[bigram.left];
  8799. auto & right_symbol = symbols[bigram.right];
  8800. if (left_symbol.n == 0 || right_symbol.n == 0) {
  8801. continue;
  8802. }
  8803. std::string left_token = std::string(left_symbol.text, left_symbol.n);
  8804. std::string right_token = std::string(right_symbol.text, right_symbol.n);
  8805. if (left_token + right_token != bigram.text) {
  8806. continue; // Skip this bigram if it's outdated
  8807. }
  8808. // merge the right sym into the left one
  8809. left_symbol.n += right_symbol.n;
  8810. right_symbol.n = 0;
  8811. // remove the right sym from the chain
  8812. left_symbol.next = right_symbol.next;
  8813. if (right_symbol.next >= 0) {
  8814. symbols[right_symbol.next].prev = bigram.left;
  8815. }
  8816. add_new_bigram(left_symbol.prev, bigram.left); // left side of current symbol
  8817. add_new_bigram(bigram.left, left_symbol.next); // right side of current symbol
  8818. }
  8819. // add the fnished tokens to the final list keeping correct order for next and prev
  8820. for (auto & sym : symbols) {
  8821. if (sym.n > 0) {
  8822. sym.prev = final_prev_index;
  8823. sym.next = -1;
  8824. if (final_prev_index != -1) {
  8825. symbols_final[final_prev_index].next = symbols_final.size();
  8826. }
  8827. symbols_final.emplace_back(sym);
  8828. final_prev_index = symbols_final.size() - 1;
  8829. }
  8830. }
  8831. }
  8832. symbols = symbols_final;
  8833. if (!symbols.empty()) {
  8834. for (int i = 0; i != -1; i = symbols[i].next) {
  8835. auto & symbol = symbols[i];
  8836. if (symbol.n == 0) {
  8837. continue;
  8838. }
  8839. const std::string str = std::string(symbol.text, symbol.n);
  8840. const auto token = vocab.token_to_id.find(str);
  8841. if (token == vocab.token_to_id.end()) {
  8842. for (auto j = str.begin(); j != str.end(); ++j) {
  8843. std::string byte_str(1, *j);
  8844. auto token_multibyte = vocab.token_to_id.find(byte_str);
  8845. if (token_multibyte == vocab.token_to_id.end()) {
  8846. throw std::runtime_error("ERROR: byte not found in vocab");
  8847. }
  8848. output.push_back((*token_multibyte).second);
  8849. }
  8850. } else {
  8851. output.push_back((*token).second);
  8852. }
  8853. }
  8854. }
  8855. }
  8856. private:
  8857. void add_new_bigram(int left, int right) {
  8858. if (left == -1 || right == -1) {
  8859. return;
  8860. }
  8861. std::string left_token = std::string(symbols[left].text, symbols[left].n);
  8862. std::string right_token = std::string(symbols[right].text, symbols[right].n);
  8863. int rank_found = -1;
  8864. rank_found = vocab.find_bpe_rank(left_token, right_token);
  8865. if (rank_found < 0) {
  8866. return;
  8867. }
  8868. llm_bigram_bpe bigram;
  8869. bigram.left = left;
  8870. bigram.right = right;
  8871. bigram.text = left_token + right_token;
  8872. bigram.size = left_token.size() + right_token.size();
  8873. bigram.rank = rank_found;
  8874. work_queue.push(bigram);
  8875. }
  8876. std::vector<std::string> bpe_gpt2_preprocess(const std::string & text) {
  8877. std::vector<std::string> bpe_words;
  8878. std::vector<std::string> bpe_encoded_words;
  8879. std::string token = "";
  8880. // GPT2 system regex: 's|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+
  8881. bool collecting_numeric = false;
  8882. bool collecting_letter = false;
  8883. bool collecting_special = false;
  8884. bool collecting_whitespace_lookahead = false;
  8885. bool collecting = false;
  8886. std::vector<std::string> text_utf;
  8887. text_utf.reserve(text.size());
  8888. bpe_words.reserve(text.size());
  8889. bpe_encoded_words.reserve(text.size());
  8890. const auto cpts = unicode_cpts_from_utf8(text);
  8891. for (size_t i = 0; i < cpts.size(); ++i)
  8892. text_utf.emplace_back(unicode_cpt_to_utf8(cpts[i]));
  8893. for (int i = 0; i < (int)text_utf.size(); i++) {
  8894. const std::string & utf_char = text_utf[i];
  8895. bool split_condition = false;
  8896. int bytes_remain = text_utf.size() - i;
  8897. // forward backward lookups
  8898. const std::string & utf_char_next = (i + 1 < (int)text_utf.size()) ? text_utf[i + 1] : "";
  8899. const std::string & utf_char_next_next = (i + 2 < (int)text_utf.size()) ? text_utf[i + 2] : "";
  8900. // handling contractions
  8901. if (!split_condition && bytes_remain >= 2) {
  8902. // 's|'t|'m|'d
  8903. if (utf_char == "\'" && (utf_char_next == "s" || utf_char_next == "t" || utf_char_next == "m" || utf_char_next == "d")) {
  8904. split_condition = true;
  8905. }
  8906. if (split_condition) {
  8907. if (token.size()) {
  8908. bpe_words.emplace_back(token); // push previous content as token
  8909. }
  8910. token = utf_char + utf_char_next;
  8911. bpe_words.emplace_back(token);
  8912. token = "";
  8913. i++;
  8914. continue;
  8915. }
  8916. }
  8917. if (!split_condition && bytes_remain >= 3) {
  8918. // 're|'ve|'ll
  8919. if (utf_char == "\'" && (
  8920. (utf_char_next == "r" && utf_char_next_next == "e") ||
  8921. (utf_char_next == "v" && utf_char_next_next == "e") ||
  8922. (utf_char_next == "l" && utf_char_next_next == "l"))
  8923. ) {
  8924. split_condition = true;
  8925. }
  8926. if (split_condition) {
  8927. // current token + next token can be defined
  8928. if (token.size()) {
  8929. bpe_words.emplace_back(token); // push previous content as token
  8930. }
  8931. token = utf_char + utf_char_next + utf_char_next_next;
  8932. bpe_words.emplace_back(token); // the contraction
  8933. token = "";
  8934. i += 2;
  8935. continue;
  8936. }
  8937. }
  8938. if (!split_condition && !collecting) {
  8939. if (unicode_cpt_type(utf_char) == CODEPOINT_TYPE_LETTER || (!token.size() && utf_char == " " && unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_LETTER)) {
  8940. collecting_letter = true;
  8941. collecting = true;
  8942. }
  8943. else if (unicode_cpt_type(utf_char) == CODEPOINT_TYPE_DIGIT || (!token.size() && utf_char == " " && unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  8944. collecting_numeric = true;
  8945. collecting = true;
  8946. }
  8947. else if (
  8948. ((unicode_cpt_type(utf_char) != CODEPOINT_TYPE_LETTER && unicode_cpt_type(utf_char) != CODEPOINT_TYPE_DIGIT) && (unicode_cpt_type(utf_char) != CODEPOINT_TYPE_WHITESPACE)) ||
  8949. (!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)
  8950. ) {
  8951. collecting_special = true;
  8952. collecting = true;
  8953. }
  8954. else if (unicode_cpt_type(utf_char) == CODEPOINT_TYPE_WHITESPACE && unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_WHITESPACE) {
  8955. collecting_whitespace_lookahead = true;
  8956. collecting = true;
  8957. }
  8958. else if (unicode_cpt_type(utf_char) == CODEPOINT_TYPE_WHITESPACE) {
  8959. split_condition = true;
  8960. }
  8961. }
  8962. else if (!split_condition && collecting) {
  8963. if (collecting_letter && unicode_cpt_type(utf_char) != CODEPOINT_TYPE_LETTER) {
  8964. split_condition = true;
  8965. }
  8966. else if (collecting_numeric && unicode_cpt_type(utf_char) != CODEPOINT_TYPE_DIGIT) {
  8967. split_condition = true;
  8968. }
  8969. 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)) {
  8970. split_condition = true;
  8971. }
  8972. else if (collecting_whitespace_lookahead && (unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_LETTER || unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  8973. split_condition = true;
  8974. }
  8975. }
  8976. if (utf_char_next == "") {
  8977. split_condition = true; // final
  8978. token += utf_char;
  8979. }
  8980. if (split_condition) {
  8981. if (token.size()) {
  8982. bpe_words.emplace_back(token);
  8983. }
  8984. token = utf_char;
  8985. collecting = false;
  8986. collecting_letter = false;
  8987. collecting_numeric = false;
  8988. collecting_special = false;
  8989. collecting_whitespace_lookahead = false;
  8990. }
  8991. else {
  8992. token += utf_char;
  8993. }
  8994. }
  8995. for (std::string & word : bpe_words) {
  8996. std::string encoded_token = "";
  8997. for (char & c : word) {
  8998. encoded_token += unicode_byte_to_utf8(c);
  8999. }
  9000. bpe_encoded_words.emplace_back(encoded_token);
  9001. }
  9002. return bpe_encoded_words;
  9003. }
  9004. const llama_vocab & vocab;
  9005. std::vector<llm_symbol> symbols;
  9006. std::vector<llm_symbol> symbols_final;
  9007. llm_bigram_bpe::queue work_queue;
  9008. };
  9009. struct llm_tokenizer_wpm {
  9010. llm_tokenizer_wpm(const llama_vocab & vocab): vocab(vocab) {}
  9011. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  9012. auto * token_map = &vocab.token_to_id;
  9013. // normalize and split by whitespace
  9014. std::vector<std::string> words = preprocess(text);
  9015. // bos token prepended already
  9016. // find the longest tokens that form the words
  9017. for (const std::string &word : words) {
  9018. // skip empty words
  9019. if (word.size() == 0) {
  9020. continue;
  9021. }
  9022. // prepend phantom space
  9023. std::string word1 = "\xe2\x96\x81" + word;
  9024. int n = word1.size();
  9025. // we're at the start of a new word
  9026. int i = 0;
  9027. bool match_any = false;
  9028. // move through character position in word
  9029. while (i < n) {
  9030. // loop through possible match length
  9031. bool match = false;
  9032. for (int j = n; j > i; j--) {
  9033. auto it = token_map->find(word1.substr(i, j - i));
  9034. if (it != token_map->end()) {
  9035. output.push_back(it->second);
  9036. match = true;
  9037. match_any = true;
  9038. i = j;
  9039. break;
  9040. }
  9041. }
  9042. // must be an unknown character
  9043. if (!match) {
  9044. i++;
  9045. }
  9046. }
  9047. // we didn't find any matches for this word
  9048. if (!match_any) {
  9049. output.push_back(vocab.special_unk_id);
  9050. }
  9051. }
  9052. // append eos token
  9053. output.push_back(vocab.special_eos_id);
  9054. }
  9055. std::vector<std::string> preprocess(const std::string & text) {
  9056. std::vector<uint32_t> cpts_nfd = unicode_cpts_normalize_nfd(unicode_cpts_from_utf8(text));
  9057. // strip accents, strip control, uniformize whitespace,
  9058. // to lowercase, pad chinese characters, pad punctuation
  9059. std::string new_str = "";
  9060. for (uint32_t code : cpts_nfd) {
  9061. int type = unicode_cpt_type(code);
  9062. if (type == CODEPOINT_TYPE_ACCENT_MARK || type == CODEPOINT_TYPE_CONTROL) {
  9063. continue;
  9064. }
  9065. code = unicode_tolower(code);
  9066. if (type == CODEPOINT_TYPE_WHITESPACE) {
  9067. code = ' ';
  9068. }
  9069. std::string s = unicode_cpt_to_utf8(code);
  9070. if (type == CODEPOINT_TYPE_PUNCTUATION || is_ascii_punct(code) || is_chinese_char(code)) {
  9071. new_str += " ";
  9072. new_str += s;
  9073. new_str += " ";
  9074. } else {
  9075. new_str += s;
  9076. }
  9077. }
  9078. // split by whitespace
  9079. uint64_t l = 0;
  9080. uint64_t r = 0;
  9081. std::vector<std::string> words;
  9082. while (r < new_str.size()) {
  9083. // if is whitespace
  9084. if (isspace(new_str[r], std::locale::classic())) {
  9085. if (r > l) words.push_back(new_str.substr(l, (r - l)));
  9086. l = r + 1;
  9087. r = l;
  9088. } else {
  9089. r += 1;
  9090. }
  9091. }
  9092. if (r > l) {
  9093. words.push_back(new_str.substr(l, (r - l)));
  9094. }
  9095. return words;
  9096. }
  9097. bool is_ascii_punct(uint32_t code) {
  9098. if (code > 0xFF) {
  9099. return false;
  9100. }
  9101. auto c = char(static_cast<unsigned char>(code));
  9102. return ispunct(c, std::locale::classic());
  9103. }
  9104. bool is_chinese_char(uint32_t cpt) {
  9105. if ((cpt >= 0x4E00 && cpt <= 0x9FFF) ||
  9106. (cpt >= 0x3400 && cpt <= 0x4DBF) ||
  9107. (cpt >= 0x20000 && cpt <= 0x2A6DF) ||
  9108. (cpt >= 0x2A700 && cpt <= 0x2B73F) ||
  9109. (cpt >= 0x2B740 && cpt <= 0x2B81F) ||
  9110. (cpt >= 0x2B920 && cpt <= 0x2CEAF) || // this should be 0x2B820 but in hf rust code it is 0x2B920
  9111. (cpt >= 0xF900 && cpt <= 0xFAFF) ||
  9112. (cpt >= 0x2F800 && cpt <= 0x2FA1F) ||
  9113. (cpt >= 0x3000 && cpt <= 0x303F) ||
  9114. (cpt >= 0xFF00 && cpt <= 0xFFEF)) {
  9115. return true; // NOLINT
  9116. }
  9117. return false;
  9118. }
  9119. const llama_vocab & vocab;
  9120. };
  9121. typedef enum FRAGMENT_BUFFER_VARIANT_TYPE {
  9122. FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN,
  9123. FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT
  9124. } FRAGMENT_BUFFER_VARIANT_TYPE;
  9125. struct fragment_buffer_variant {
  9126. fragment_buffer_variant(llama_vocab::id _token)
  9127. :
  9128. type(FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN),
  9129. token(_token),
  9130. raw_text(_dummy),
  9131. offset(0),
  9132. length(0) {}
  9133. fragment_buffer_variant(const std::string & _raw_text, int64_t _offset, int64_t _length)
  9134. :
  9135. type(FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT),
  9136. token((llama_vocab::id) - 1),
  9137. raw_text(_raw_text),
  9138. offset(_offset),
  9139. length(_length){
  9140. GGML_ASSERT(_offset >= 0);
  9141. GGML_ASSERT(_length >= 1);
  9142. GGML_ASSERT(offset + length <= raw_text.length());
  9143. }
  9144. const FRAGMENT_BUFFER_VARIANT_TYPE type;
  9145. const llama_vocab::id token;
  9146. const std::string _dummy;
  9147. const std::string & raw_text;
  9148. const uint64_t offset;
  9149. const uint64_t length;
  9150. };
  9151. // #define PRETOKENIZERDEBUG
  9152. static void tokenizer_st_partition(const llama_vocab & vocab, std::forward_list<fragment_buffer_variant> & buffer) {
  9153. // for each special token
  9154. for (const auto & st: vocab.special_tokens_cache) {
  9155. const auto & special_token = st.first;
  9156. const auto & special_id = st.second;
  9157. // for each text fragment
  9158. std::forward_list<fragment_buffer_variant>::iterator it = buffer.begin();
  9159. while (it != buffer.end()) {
  9160. auto & fragment = (*it);
  9161. // if a fragment is text ( not yet processed )
  9162. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  9163. auto * raw_text = &(fragment.raw_text);
  9164. auto raw_text_base_offset = fragment.offset;
  9165. auto raw_text_base_length = fragment.length;
  9166. // loop over the text
  9167. while (true) {
  9168. // find the first occurrence of a given special token in this fragment
  9169. // passing offset argument only limit the "search area" but match coordinates
  9170. // are still relative to the source full raw_text
  9171. auto match = raw_text->find(special_token, raw_text_base_offset);
  9172. // no occurrences found, stop processing this fragment for a given special token
  9173. if (match == std::string::npos) break;
  9174. // check if match is within bounds of offset <-> length
  9175. if (match + special_token.length() > raw_text_base_offset + raw_text_base_length) break;
  9176. #ifdef PRETOKENIZERDEBUG
  9177. 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());
  9178. #endif
  9179. auto source = std::distance(buffer.begin(), it);
  9180. // if match is further than base offset
  9181. // then we have some text to the left of it
  9182. if (match > raw_text_base_offset) {
  9183. // left
  9184. const int64_t left_reminder_offset = raw_text_base_offset + 0;
  9185. const int64_t left_reminder_length = match - raw_text_base_offset;
  9186. buffer.emplace_after(it, (*raw_text), left_reminder_offset, left_reminder_length);
  9187. #ifdef PRETOKENIZERDEBUG
  9188. 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());
  9189. #endif
  9190. it++;
  9191. }
  9192. // special token
  9193. buffer.emplace_after(it, special_id);
  9194. it++;
  9195. // right
  9196. if (match + special_token.length() < raw_text_base_offset + raw_text_base_length) {
  9197. const int64_t right_reminder_offset = match + special_token.length();
  9198. const int64_t right_reminder_length = raw_text_base_length - ((match - raw_text_base_offset) + special_token.length());
  9199. buffer.emplace_after(it, (*raw_text), right_reminder_offset, right_reminder_length);
  9200. #ifdef PRETOKENIZERDEBUG
  9201. 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());
  9202. #endif
  9203. it++;
  9204. if (source == 0) {
  9205. buffer.erase_after(buffer.before_begin());
  9206. } else {
  9207. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  9208. }
  9209. // repeat for the right side
  9210. raw_text_base_offset = right_reminder_offset;
  9211. raw_text_base_length = right_reminder_length;
  9212. #ifdef PRETOKENIZERDEBUG
  9213. 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());
  9214. #endif
  9215. } else {
  9216. if (source == 0) {
  9217. buffer.erase_after(buffer.before_begin());
  9218. } else {
  9219. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  9220. }
  9221. break;
  9222. }
  9223. }
  9224. }
  9225. it++;
  9226. }
  9227. }
  9228. }
  9229. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special) {
  9230. std::vector<llama_vocab::id> output;
  9231. // OG tokenizer behavior:
  9232. //
  9233. // tokenizer.encode('', add_bos=True) returns [1]
  9234. // tokenizer.encode('', add_bos=False) returns []
  9235. if (bos && vocab.special_bos_id != -1) {
  9236. output.push_back(vocab.special_bos_id);
  9237. }
  9238. if (raw_text.empty()) {
  9239. return output;
  9240. }
  9241. std::forward_list<fragment_buffer_variant> fragment_buffer;
  9242. fragment_buffer.emplace_front(raw_text, 0, raw_text.length());
  9243. if (special) tokenizer_st_partition(vocab, fragment_buffer);
  9244. switch (vocab.type) {
  9245. case LLAMA_VOCAB_TYPE_SPM:
  9246. {
  9247. for (const auto & fragment : fragment_buffer) {
  9248. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  9249. // without adding this leading whitespace, we do not get the same results as the original tokenizer
  9250. // TODO: It's likely possible to get rid of this string copy entirely
  9251. // by modifying llm_tokenizer_x to operate with string offsets like pre-tokenizer
  9252. // and passing 'add space prefix' as bool argument
  9253. //
  9254. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  9255. if (&fragment == &fragment_buffer.front()) {
  9256. if (vocab.add_space_prefix) {
  9257. raw_text = " " + raw_text; // prefix with space if the first token is not special
  9258. }
  9259. }
  9260. #ifdef PRETOKENIZERDEBUG
  9261. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  9262. #endif
  9263. llm_tokenizer_spm tokenizer(vocab);
  9264. llama_escape_whitespace(raw_text);
  9265. tokenizer.tokenize(raw_text, output);
  9266. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  9267. output.push_back(fragment.token);
  9268. }
  9269. }
  9270. } break;
  9271. case LLAMA_VOCAB_TYPE_BPE:
  9272. {
  9273. for (const auto & fragment : fragment_buffer) {
  9274. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  9275. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  9276. #ifdef PRETOKENIZERDEBUG
  9277. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  9278. #endif
  9279. llm_tokenizer_bpe tokenizer(vocab);
  9280. tokenizer.tokenize(raw_text, output);
  9281. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  9282. output.push_back(fragment.token);
  9283. }
  9284. }
  9285. } break;
  9286. case LLAMA_VOCAB_TYPE_WPM:
  9287. {
  9288. for (const auto & fragment : fragment_buffer) {
  9289. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  9290. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  9291. #ifdef PRETOKENIZERDEBUG
  9292. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  9293. #endif
  9294. llm_tokenizer_wpm tokenizer(vocab);
  9295. tokenizer.tokenize(raw_text, output);
  9296. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  9297. output.push_back(fragment.token);
  9298. }
  9299. }
  9300. } break;
  9301. case LLAMA_VOCAB_TYPE_NONE:
  9302. GGML_ASSERT(false);
  9303. }
  9304. return output;
  9305. }
  9306. //
  9307. // grammar - internal
  9308. //
  9309. struct llama_partial_utf8 {
  9310. uint32_t value; // bit value so far (unshifted)
  9311. int n_remain; // num bytes remaining; -1 indicates invalid sequence
  9312. };
  9313. struct llama_grammar {
  9314. const std::vector<std::vector<llama_grammar_element>> rules;
  9315. std::vector<std::vector<const llama_grammar_element *>> stacks;
  9316. // buffer for partially generated UTF-8 sequence from accepted tokens
  9317. llama_partial_utf8 partial_utf8;
  9318. };
  9319. struct llama_grammar_candidate {
  9320. size_t index;
  9321. const uint32_t * code_points;
  9322. llama_partial_utf8 partial_utf8;
  9323. };
  9324. // Decodes a UTF-8 string which may end in an incomplete sequence. Adds a terminating 0 for use as
  9325. // pointer. If an invalid sequence is encountered, returns `llama_partial_utf8.n_remain == -1`.
  9326. static std::pair<std::vector<uint32_t>, llama_partial_utf8> decode_utf8(
  9327. const std::string & src,
  9328. llama_partial_utf8 partial_start) {
  9329. static const int lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 3, 4 };
  9330. const char * pos = src.c_str();
  9331. std::vector<uint32_t> code_points;
  9332. // common english strings have the same number of codepoints and bytes. `+ 1` for the terminating 0.
  9333. code_points.reserve(src.size() + 1);
  9334. uint32_t value = partial_start.value;
  9335. int n_remain = partial_start.n_remain;
  9336. // continue previous decode, if applicable
  9337. while (*pos != 0 && n_remain > 0) {
  9338. uint8_t next_byte = static_cast<uint8_t>(*pos);
  9339. if ((next_byte >> 6) != 2) {
  9340. // invalid sequence, abort
  9341. code_points.push_back(0);
  9342. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, -1 });
  9343. }
  9344. value = (value << 6) + (next_byte & 0x3F);
  9345. ++pos;
  9346. --n_remain;
  9347. }
  9348. if (partial_start.n_remain > 0 && n_remain == 0) {
  9349. code_points.push_back(value);
  9350. }
  9351. // decode any subsequent utf-8 sequences, which may end in an incomplete one
  9352. while (*pos != 0) {
  9353. uint8_t first_byte = static_cast<uint8_t>(*pos);
  9354. uint8_t highbits = first_byte >> 4;
  9355. n_remain = lookup[highbits] - 1;
  9356. if (n_remain < 0) {
  9357. // invalid sequence, abort
  9358. code_points.clear();
  9359. code_points.push_back(0);
  9360. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, n_remain });
  9361. }
  9362. uint8_t mask = (1 << (7 - n_remain)) - 1;
  9363. value = first_byte & mask;
  9364. ++pos;
  9365. while (*pos != 0 && n_remain > 0) {
  9366. value = (value << 6) + (static_cast<uint8_t>(*pos) & 0x3F);
  9367. ++pos;
  9368. --n_remain;
  9369. }
  9370. if (n_remain == 0) {
  9371. code_points.push_back(value);
  9372. }
  9373. }
  9374. code_points.push_back(0);
  9375. return std::make_pair(std::move(code_points), llama_partial_utf8{ value, n_remain });
  9376. }
  9377. // returns true iff pos points to the end of one of the definitions of a rule
  9378. static bool llama_grammar_is_end_of_sequence(const llama_grammar_element * pos) {
  9379. switch (pos->type) {
  9380. case LLAMA_GRETYPE_END: return true; // NOLINT
  9381. case LLAMA_GRETYPE_ALT: return true; // NOLINT
  9382. default: return false;
  9383. }
  9384. }
  9385. // returns true iff chr satisfies the char range at pos (regular or inverse range)
  9386. // asserts that pos is pointing to a char range element
  9387. static std::pair<bool, const llama_grammar_element *> llama_grammar_match_char(
  9388. const llama_grammar_element * pos,
  9389. const uint32_t chr) {
  9390. bool found = false;
  9391. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  9392. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT); // NOLINT
  9393. do {
  9394. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  9395. // inclusive range, e.g. [a-z]
  9396. found = found || (pos->value <= chr && chr <= pos[1].value);
  9397. pos += 2;
  9398. } else {
  9399. // exact char match, e.g. [a] or "a"
  9400. found = found || pos->value == chr;
  9401. pos += 1;
  9402. }
  9403. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  9404. return std::make_pair(found == is_positive_char, pos);
  9405. }
  9406. // returns true iff some continuation of the given partial UTF-8 sequence could satisfy the char
  9407. // range at pos (regular or inverse range)
  9408. // asserts that pos is pointing to a char range element
  9409. static bool llama_grammar_match_partial_char(
  9410. const llama_grammar_element * pos,
  9411. const llama_partial_utf8 partial_utf8) {
  9412. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  9413. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT);
  9414. uint32_t partial_value = partial_utf8.value;
  9415. int n_remain = partial_utf8.n_remain;
  9416. // invalid sequence or 7-bit char split across 2 bytes (overlong)
  9417. if (n_remain < 0 || (n_remain == 1 && partial_value < 2)) {
  9418. return false;
  9419. }
  9420. // range of possible code points this partial UTF-8 sequence could complete to
  9421. uint32_t low = partial_value << (n_remain * 6);
  9422. uint32_t high = low | ((1 << (n_remain * 6)) - 1);
  9423. if (low == 0) {
  9424. if (n_remain == 2) {
  9425. low = 1 << 11;
  9426. } else if (n_remain == 3) {
  9427. low = 1 << 16;
  9428. }
  9429. }
  9430. do {
  9431. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  9432. // inclusive range, e.g. [a-z]
  9433. if (pos->value <= high && low <= pos[1].value) {
  9434. return is_positive_char;
  9435. }
  9436. pos += 2;
  9437. } else {
  9438. // exact char match, e.g. [a] or "a"
  9439. if (low <= pos->value && pos->value <= high) {
  9440. return is_positive_char;
  9441. }
  9442. pos += 1;
  9443. }
  9444. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  9445. return !is_positive_char;
  9446. }
  9447. // transforms a grammar pushdown stack into N possible stacks, all ending
  9448. // at a character range (terminal element)
  9449. static void llama_grammar_advance_stack(
  9450. const std::vector<std::vector<llama_grammar_element>> & rules,
  9451. const std::vector<const llama_grammar_element *> & stack,
  9452. std::vector<std::vector<const llama_grammar_element *>> & new_stacks) {
  9453. if (stack.empty()) {
  9454. new_stacks.emplace_back(stack);
  9455. return;
  9456. }
  9457. const llama_grammar_element * pos = stack.back();
  9458. switch (pos->type) {
  9459. case LLAMA_GRETYPE_RULE_REF: {
  9460. const size_t rule_id = static_cast<size_t>(pos->value);
  9461. const llama_grammar_element * subpos = rules[rule_id].data();
  9462. do {
  9463. // init new stack without the top (pos)
  9464. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  9465. if (!llama_grammar_is_end_of_sequence(pos + 1)) {
  9466. // if this rule ref is followed by another element, add that to stack
  9467. new_stack.push_back(pos + 1);
  9468. }
  9469. if (!llama_grammar_is_end_of_sequence(subpos)) {
  9470. // if alternate is nonempty, add to stack
  9471. new_stack.push_back(subpos);
  9472. }
  9473. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  9474. while (!llama_grammar_is_end_of_sequence(subpos)) {
  9475. // scan to end of alternate def
  9476. subpos++;
  9477. }
  9478. if (subpos->type == LLAMA_GRETYPE_ALT) {
  9479. // there's another alternate def of this rule to process
  9480. subpos++;
  9481. } else {
  9482. break;
  9483. }
  9484. } while (true);
  9485. break;
  9486. }
  9487. case LLAMA_GRETYPE_CHAR:
  9488. case LLAMA_GRETYPE_CHAR_NOT:
  9489. new_stacks.emplace_back(stack);
  9490. break;
  9491. default:
  9492. // end of alternate (LLAMA_GRETYPE_END, LLAMA_GRETYPE_ALT) or middle of char range
  9493. // (LLAMA_GRETYPE_CHAR_ALT, LLAMA_GRETYPE_CHAR_RNG_UPPER); stack should never be left on
  9494. // those
  9495. GGML_ASSERT(false);
  9496. }
  9497. }
  9498. // takes a set of possible pushdown stacks on a grammar, which are required to
  9499. // be positioned at a character range (see `llama_grammar_advance_stack`), and
  9500. // produces the N possible stacks if the given char is accepted at those
  9501. // positions
  9502. static std::vector<std::vector<const llama_grammar_element *>> llama_grammar_accept(
  9503. const std::vector<std::vector<llama_grammar_element>> & rules,
  9504. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  9505. const uint32_t chr) {
  9506. std::vector<std::vector<const llama_grammar_element *>> new_stacks;
  9507. for (const auto & stack : stacks) {
  9508. if (stack.empty()) {
  9509. continue;
  9510. }
  9511. auto match = llama_grammar_match_char(stack.back(), chr);
  9512. if (match.first) {
  9513. const llama_grammar_element * pos = match.second;
  9514. // update top of stack to next element, if any
  9515. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  9516. if (!llama_grammar_is_end_of_sequence(pos)) {
  9517. new_stack.push_back(pos);
  9518. }
  9519. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  9520. }
  9521. }
  9522. return new_stacks;
  9523. }
  9524. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  9525. const std::vector<std::vector<llama_grammar_element>> & rules,
  9526. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  9527. const std::vector<llama_grammar_candidate> & candidates);
  9528. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates_for_stack(
  9529. const std::vector<std::vector<llama_grammar_element>> & rules,
  9530. const std::vector<const llama_grammar_element *> & stack,
  9531. const std::vector<llama_grammar_candidate> & candidates) {
  9532. std::vector<llama_grammar_candidate> rejects;
  9533. if (stack.empty()) {
  9534. for (const auto & tok : candidates) {
  9535. if (*tok.code_points != 0 || tok.partial_utf8.n_remain != 0) {
  9536. rejects.push_back(tok);
  9537. }
  9538. }
  9539. return rejects;
  9540. }
  9541. const llama_grammar_element * stack_pos = stack.back();
  9542. std::vector<llama_grammar_candidate> next_candidates;
  9543. for (const auto & tok : candidates) {
  9544. if (*tok.code_points == 0) {
  9545. // reached end of full codepoints in token, reject iff it ended in a partial sequence
  9546. // that cannot satisfy this position in grammar
  9547. if (tok.partial_utf8.n_remain != 0 &&
  9548. !llama_grammar_match_partial_char(stack_pos, tok.partial_utf8)) {
  9549. rejects.push_back(tok);
  9550. }
  9551. } else if (llama_grammar_match_char(stack_pos, *tok.code_points).first) {
  9552. next_candidates.push_back({ tok.index, tok.code_points + 1, tok.partial_utf8 });
  9553. } else {
  9554. rejects.push_back(tok);
  9555. }
  9556. }
  9557. const auto * stack_pos_after = llama_grammar_match_char(stack_pos, 0).second;
  9558. // update top of stack to next element, if any
  9559. std::vector<const llama_grammar_element *> stack_after(stack.begin(), stack.end() - 1);
  9560. if (!llama_grammar_is_end_of_sequence(stack_pos_after)) {
  9561. stack_after.push_back(stack_pos_after);
  9562. }
  9563. std::vector<std::vector<const llama_grammar_element *>> next_stacks;
  9564. llama_grammar_advance_stack(rules, stack_after, next_stacks);
  9565. auto next_rejects = llama_grammar_reject_candidates(rules, next_stacks, next_candidates);
  9566. for (const auto & tok : next_rejects) {
  9567. rejects.push_back({ tok.index, tok.code_points - 1, tok.partial_utf8 });
  9568. }
  9569. return rejects;
  9570. }
  9571. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  9572. const std::vector<std::vector<llama_grammar_element>> & rules,
  9573. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  9574. const std::vector<llama_grammar_candidate> & candidates) {
  9575. GGML_ASSERT(!stacks.empty()); // REVIEW
  9576. if (candidates.empty()) {
  9577. return std::vector<llama_grammar_candidate>();
  9578. }
  9579. auto rejects = llama_grammar_reject_candidates_for_stack(rules, stacks.front(), candidates);
  9580. for (size_t i = 1, size = stacks.size(); i < size; ++i) {
  9581. rejects = llama_grammar_reject_candidates_for_stack(rules, stacks[i], rejects);
  9582. }
  9583. return rejects;
  9584. }
  9585. //
  9586. // grammar - external
  9587. //
  9588. struct llama_grammar * llama_grammar_init(
  9589. const llama_grammar_element ** rules,
  9590. size_t n_rules,
  9591. size_t start_rule_index) {
  9592. const llama_grammar_element * pos;
  9593. // copy rule definitions into vectors
  9594. std::vector<std::vector<llama_grammar_element>> vec_rules(n_rules);
  9595. for (size_t i = 0; i < n_rules; i++) {
  9596. for (pos = rules[i]; pos->type != LLAMA_GRETYPE_END; pos++) {
  9597. vec_rules[i].push_back(*pos);
  9598. }
  9599. vec_rules[i].push_back({LLAMA_GRETYPE_END, 0});
  9600. }
  9601. // loop over alternates of start rule to build initial stacks
  9602. std::vector<std::vector<const llama_grammar_element *>> stacks;
  9603. pos = vec_rules[start_rule_index].data();
  9604. do {
  9605. std::vector<const llama_grammar_element *> stack;
  9606. if (!llama_grammar_is_end_of_sequence(pos)) {
  9607. // if alternate is nonempty, add to stack
  9608. stack.push_back(pos);
  9609. }
  9610. llama_grammar_advance_stack(vec_rules, stack, stacks);
  9611. while (!llama_grammar_is_end_of_sequence(pos)) {
  9612. // scan to end of alternate def
  9613. pos++;
  9614. }
  9615. if (pos->type == LLAMA_GRETYPE_ALT) {
  9616. // there's another alternate def of this rule to process
  9617. pos++;
  9618. } else {
  9619. break;
  9620. }
  9621. } while (true);
  9622. return new llama_grammar{ std::move(vec_rules), std::move(stacks), {} };
  9623. }
  9624. void llama_grammar_free(struct llama_grammar * grammar) {
  9625. delete grammar;
  9626. }
  9627. struct llama_grammar * llama_grammar_copy(const struct llama_grammar * grammar) {
  9628. llama_grammar * result = new llama_grammar{ grammar->rules, grammar->stacks, grammar->partial_utf8 };
  9629. // redirect elements in stacks to point to new rules
  9630. for (size_t is = 0; is < result->stacks.size(); is++) {
  9631. for (size_t ie = 0; ie < result->stacks[is].size(); ie++) {
  9632. for (size_t ir0 = 0; ir0 < grammar->rules.size(); ir0++) {
  9633. for (size_t ir1 = 0; ir1 < grammar->rules[ir0].size(); ir1++) {
  9634. if (grammar->stacks[is][ie] == &grammar->rules[ir0][ir1]) {
  9635. result->stacks[is][ie] = &result->rules[ir0][ir1];
  9636. }
  9637. }
  9638. }
  9639. }
  9640. }
  9641. return result;
  9642. }
  9643. //
  9644. // sampling
  9645. //
  9646. void llama_set_rng_seed(struct llama_context * ctx, uint32_t seed) {
  9647. if (seed == LLAMA_DEFAULT_SEED) {
  9648. seed = time(NULL);
  9649. }
  9650. ctx->rng.seed(seed);
  9651. }
  9652. void llama_sample_softmax(struct llama_context * ctx, llama_token_data_array * candidates) {
  9653. GGML_ASSERT(candidates->size > 0);
  9654. const int64_t t_start_sample_us = ggml_time_us();
  9655. // Sort the logits in descending order
  9656. if (!candidates->sorted) {
  9657. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  9658. return a.logit > b.logit;
  9659. });
  9660. candidates->sorted = true;
  9661. }
  9662. float max_l = candidates->data[0].logit;
  9663. float cum_sum = 0.0f;
  9664. for (size_t i = 0; i < candidates->size; ++i) {
  9665. float p = expf(candidates->data[i].logit - max_l);
  9666. candidates->data[i].p = p;
  9667. cum_sum += p;
  9668. }
  9669. for (size_t i = 0; i < candidates->size; ++i) {
  9670. candidates->data[i].p /= cum_sum;
  9671. }
  9672. if (ctx) {
  9673. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9674. }
  9675. }
  9676. void llama_sample_top_k(struct llama_context * ctx, llama_token_data_array * candidates, int32_t k, size_t min_keep) {
  9677. // TODO: move bucket sort to separate function so that top_p/tail_free/typical/softmax first is equally fast
  9678. // if (k >= (int32_t)candidates->size) {
  9679. // return;
  9680. // }
  9681. const int64_t t_start_sample_us = ggml_time_us();
  9682. if (k <= 0) {
  9683. k = candidates->size;
  9684. }
  9685. k = std::max(k, (int) min_keep);
  9686. k = std::min(k, (int) candidates->size);
  9687. // Sort scores in descending order
  9688. if (!candidates->sorted) {
  9689. auto comp = [](const llama_token_data & a, const llama_token_data & b) {
  9690. return a.logit > b.logit;
  9691. };
  9692. if (k <= 128) {
  9693. std::partial_sort(candidates->data, candidates->data + k, candidates->data + candidates->size, comp);
  9694. } else {
  9695. constexpr int nbuckets = 128;
  9696. constexpr float bucket_low = -10.0f;
  9697. constexpr float bucket_high = 10.0f;
  9698. constexpr float bucket_scale = nbuckets/(bucket_high - bucket_low);
  9699. constexpr float bucker_inter = -bucket_low * bucket_scale;
  9700. std::vector<int> bucket_idx(candidates->size);
  9701. std::vector<int> histo(nbuckets, 0);
  9702. for (int i = 0; i < (int)candidates->size; ++i) {
  9703. const float val = candidates->data[i].logit;
  9704. int ib = int(bucket_scale * val + bucker_inter); //nbuckets * (val - bucket_low) / (bucket_high - bucket_low);
  9705. ib = std::max(0, std::min(nbuckets-1, ib));
  9706. bucket_idx[i] = ib;
  9707. ++histo[ib];
  9708. }
  9709. int nhave = 0;
  9710. int ib = nbuckets - 1;
  9711. for ( ; ib >= 0; --ib) {
  9712. nhave += histo[ib];
  9713. if (nhave >= k) break;
  9714. }
  9715. std::vector<llama_token_data> tmp_tokens(nhave);
  9716. auto ptr = tmp_tokens.data();
  9717. std::vector<llama_token_data*> bucket_ptrs;
  9718. bucket_ptrs.reserve(nbuckets - ib);
  9719. for (int j = nbuckets - 1; j >= ib; --j) {
  9720. bucket_ptrs.push_back(ptr);
  9721. ptr += histo[j];
  9722. }
  9723. for (int i = 0; i < (int)candidates->size; ++i) {
  9724. int j = bucket_idx[i];
  9725. if (j >= ib) {
  9726. *bucket_ptrs[nbuckets-1-j]++ = candidates->data[i];
  9727. }
  9728. }
  9729. ptr = tmp_tokens.data();
  9730. int ndone = 0;
  9731. for (int j = nbuckets-1; j > ib; --j) {
  9732. std::sort(ptr, ptr + histo[j], comp);
  9733. ptr += histo[j];
  9734. ndone += histo[j];
  9735. }
  9736. std::partial_sort(ptr, ptr + k - ndone, ptr + histo[ib], comp);
  9737. std::memcpy(candidates->data, tmp_tokens.data(), k*sizeof(llama_token_data));
  9738. }
  9739. candidates->sorted = true;
  9740. }
  9741. candidates->size = k;
  9742. if (ctx) {
  9743. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9744. }
  9745. }
  9746. void llama_sample_top_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  9747. if (p >= 1.0f) {
  9748. return;
  9749. }
  9750. llama_sample_softmax(ctx, candidates);
  9751. const int64_t t_start_sample_us = ggml_time_us();
  9752. // Compute the cumulative probabilities
  9753. float cum_sum = 0.0f;
  9754. size_t last_idx = candidates->size;
  9755. for (size_t i = 0; i < candidates->size; ++i) {
  9756. cum_sum += candidates->data[i].p;
  9757. // Check if the running sum is at least p or if we have kept at least min_keep tokens
  9758. // we set the last index to i+1 to indicate that the current iterate should be included in the set
  9759. if (cum_sum >= p && i + 1 >= min_keep) {
  9760. last_idx = i + 1;
  9761. break;
  9762. }
  9763. }
  9764. // Resize the output vector to keep only the top-p tokens
  9765. candidates->size = last_idx;
  9766. if (ctx) {
  9767. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9768. }
  9769. }
  9770. void llama_sample_min_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  9771. if (p <= 0.0f || !candidates->size) {
  9772. return;
  9773. }
  9774. const int64_t t_start_sample_us = ggml_time_us();
  9775. bool min_p_applied = false;
  9776. // if the candidates aren't sorted, try the unsorted implementation first
  9777. if (!candidates->sorted) {
  9778. std::vector<llama_token_data> filtered_tokens;
  9779. float max_logit = -FLT_MAX;
  9780. for (size_t i = 0; i < candidates->size; ++i) {
  9781. max_logit = std::max(max_logit, candidates->data[i].logit);
  9782. }
  9783. const float min_logit = max_logit + logf(p); // min logit for p_i >= p * p_max
  9784. for (size_t i = 0; i < candidates->size; ++i) {
  9785. if (candidates->data[i].logit >= min_logit) {
  9786. filtered_tokens.push_back(candidates->data[i]);
  9787. }
  9788. }
  9789. // if we have enough values the operation was a success
  9790. if (filtered_tokens.size() >= min_keep) {
  9791. memcpy(candidates->data, filtered_tokens.data(), filtered_tokens.size()*sizeof(llama_token_data));
  9792. candidates->size = filtered_tokens.size();
  9793. min_p_applied = true;
  9794. }
  9795. }
  9796. // if the candidates are sorted or the unsorted implementation failed, use this implementation
  9797. if (!min_p_applied) {
  9798. // Sort the logits in descending order
  9799. if (!candidates->sorted) {
  9800. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  9801. return a.logit > b.logit;
  9802. });
  9803. candidates->sorted = true;
  9804. }
  9805. const float min_logit = candidates->data[0].logit + logf(p); // min logit for p_i >= p * p_max
  9806. size_t i = 1; // first token always matches
  9807. for (; i < candidates->size; ++i) {
  9808. if (candidates->data[i].logit < min_logit && i >= min_keep) {
  9809. break; // prob too small
  9810. }
  9811. }
  9812. // Resize the output vector to keep only the matching tokens
  9813. candidates->size = i;
  9814. }
  9815. if (ctx) {
  9816. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9817. }
  9818. }
  9819. void llama_sample_tail_free(struct llama_context * ctx, llama_token_data_array * candidates, float z, size_t min_keep) {
  9820. if (z >= 1.0f || candidates->size <= 2) {
  9821. return;
  9822. }
  9823. llama_sample_softmax(nullptr, candidates);
  9824. const int64_t t_start_sample_us = ggml_time_us();
  9825. // Compute the first and second derivatives
  9826. std::vector<float> first_derivatives(candidates->size - 1);
  9827. std::vector<float> second_derivatives(candidates->size - 2);
  9828. for (size_t i = 0; i < first_derivatives.size(); ++i) {
  9829. first_derivatives[i] = candidates->data[i].p - candidates->data[i + 1].p;
  9830. }
  9831. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  9832. second_derivatives[i] = first_derivatives[i] - first_derivatives[i + 1];
  9833. }
  9834. // Calculate absolute value of second derivatives
  9835. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  9836. second_derivatives[i] = std::abs(second_derivatives[i]);
  9837. }
  9838. // Normalize the second derivatives
  9839. {
  9840. const float second_derivatives_sum = std::accumulate(second_derivatives.begin(), second_derivatives.end(), 0.0f);
  9841. if (second_derivatives_sum > 1e-6f) {
  9842. for (float & value : second_derivatives) {
  9843. value /= second_derivatives_sum;
  9844. }
  9845. } else {
  9846. for (float & value : second_derivatives) {
  9847. value = 1.0f / second_derivatives.size();
  9848. }
  9849. }
  9850. }
  9851. float cum_sum = 0.0f;
  9852. size_t last_idx = candidates->size;
  9853. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  9854. cum_sum += second_derivatives[i];
  9855. // Check if the running sum is greater than z or if we have kept at least min_keep tokens
  9856. if (cum_sum > z && i >= min_keep) {
  9857. last_idx = i;
  9858. break;
  9859. }
  9860. }
  9861. // Resize the output vector to keep only the tokens above the tail location
  9862. candidates->size = last_idx;
  9863. if (ctx) {
  9864. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9865. }
  9866. }
  9867. void llama_sample_typical(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  9868. // Reference implementation:
  9869. // https://github.com/huggingface/transformers/compare/main...cimeister:typical-sampling:typical-pr
  9870. if (p >= 1.0f) {
  9871. return;
  9872. }
  9873. // Compute the softmax of logits and calculate entropy
  9874. llama_sample_softmax(nullptr, candidates);
  9875. const int64_t t_start_sample_us = ggml_time_us();
  9876. float entropy = 0.0f;
  9877. for (size_t i = 0; i < candidates->size; ++i) {
  9878. entropy += -candidates->data[i].p * logf(candidates->data[i].p);
  9879. }
  9880. // Compute the absolute difference between negative log probability and entropy for each candidate
  9881. std::vector<float> shifted_scores;
  9882. for (size_t i = 0; i < candidates->size; ++i) {
  9883. float shifted_score = fabsf(-logf(candidates->data[i].p) - entropy);
  9884. shifted_scores.push_back(shifted_score);
  9885. }
  9886. // Sort tokens based on the shifted_scores and their corresponding indices
  9887. std::vector<size_t> indices(candidates->size);
  9888. std::iota(indices.begin(), indices.end(), 0);
  9889. std::sort(indices.begin(), indices.end(), [&](size_t a, size_t b) {
  9890. return shifted_scores[a] < shifted_scores[b];
  9891. });
  9892. // Compute the cumulative probabilities
  9893. float cum_sum = 0.0f;
  9894. size_t last_idx = indices.size();
  9895. for (size_t i = 0; i < indices.size(); ++i) {
  9896. size_t idx = indices[i];
  9897. cum_sum += candidates->data[idx].p;
  9898. // Check if the running sum is greater than typical or if we have kept at least min_keep tokens
  9899. if (cum_sum > p && i >= min_keep - 1) {
  9900. last_idx = i + 1;
  9901. break;
  9902. }
  9903. }
  9904. // Resize the output vector to keep only the locally typical tokens
  9905. std::vector<llama_token_data> new_candidates;
  9906. for (size_t i = 0; i < last_idx; ++i) {
  9907. size_t idx = indices[i];
  9908. new_candidates.push_back(candidates->data[idx]);
  9909. }
  9910. // Replace the data in candidates with the new_candidates data
  9911. std::copy(new_candidates.begin(), new_candidates.end(), candidates->data);
  9912. candidates->size = new_candidates.size();
  9913. candidates->sorted = false;
  9914. if (ctx) {
  9915. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9916. }
  9917. }
  9918. void llama_sample_entropy(struct llama_context * ctx, llama_token_data_array * candidates_p, float min_temp, float max_temp, float exponent_val) {
  9919. const int64_t t_start_sample_us = ggml_time_us();
  9920. // no need to do anything if there is only one (or zero) candidates
  9921. if(candidates_p->size <= 1) {
  9922. return;
  9923. }
  9924. // Calculate maximum possible entropy
  9925. float max_entropy = -logf(1.0f / candidates_p->size);
  9926. llama_sample_softmax(nullptr, candidates_p);
  9927. // Calculate entropy of the softmax probabilities
  9928. float entropy = 0.0f;
  9929. for (size_t i = 0; i < candidates_p->size; ++i) {
  9930. float prob = candidates_p->data[i].p;
  9931. if (prob > 0.0f) { // Ensure no log(0)
  9932. entropy -= prob * logf(prob);
  9933. }
  9934. }
  9935. // Normalize the entropy (max_entropy cannot be 0 here because we checked candidates_p->size != 1 above)
  9936. float normalized_entropy = entropy / max_entropy;
  9937. // Map the normalized entropy to the desired temperature range using the power function
  9938. float dyn_temp = min_temp + (max_temp - min_temp) * powf(normalized_entropy, exponent_val);
  9939. #ifdef DEBUG
  9940. LLAMA_LOG_INFO("Your text maxtemp value is: %f\n", max_temp);
  9941. LLAMA_LOG_INFO("Entropy: %f\n", entropy);
  9942. LLAMA_LOG_INFO("Max Possible Entropy: %f\n", max_entropy);
  9943. LLAMA_LOG_INFO("Normalized Entropy: %f\n", normalized_entropy);
  9944. LLAMA_LOG_INFO("Exponent: %f\n", exponent_val);
  9945. LLAMA_LOG_INFO("Dynamic Temperature (dyn_temp): %f\n", dyn_temp);
  9946. #endif
  9947. // Apply the dynamically calculated temperature scaling
  9948. for (size_t i = 0; i < candidates_p->size; ++i) {
  9949. candidates_p->data[i].logit /= dyn_temp;
  9950. }
  9951. // Re-compute softmax probabilities after scaling logits with dynamic temperature
  9952. double max_l_double = candidates_p->data[0].logit;
  9953. double cum_sum_double = 0.0;
  9954. for (size_t i = 0; i < candidates_p->size; ++i) {
  9955. double p = exp(candidates_p->data[i].logit - max_l_double);
  9956. candidates_p->data[i].p = p; // Store the scaled probability
  9957. cum_sum_double += p;
  9958. }
  9959. for (size_t i = 0; i < candidates_p->size; ++i) {
  9960. candidates_p->data[i].p /= cum_sum_double; // Re-normalize the probabilities
  9961. }
  9962. #ifdef DEBUG
  9963. // Print the updated top 25 probabilities after temperature scaling
  9964. LLAMA_LOG_INFO("\nUpdated Top 25 Probabilities After Dynamic Temperature Scaling (in percentages):\n");
  9965. for (size_t i = 0; i < 25 && i < candidates_p->size; ++i) {
  9966. LLAMA_LOG_INFO("Token %zu: %f%%\n", i + 1, candidates_p->data[i].p * 100.0f);
  9967. }
  9968. #endif
  9969. if (ctx) {
  9970. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9971. }
  9972. }
  9973. void llama_sample_temp(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  9974. const int64_t t_start_sample_us = ggml_time_us();
  9975. for (size_t i = 0; i < candidates_p->size; ++i) {
  9976. candidates_p->data[i].logit /= temp;
  9977. }
  9978. if (ctx) {
  9979. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9980. }
  9981. }
  9982. void llama_sample_repetition_penalties(
  9983. struct llama_context * ctx,
  9984. llama_token_data_array * candidates,
  9985. const llama_token * last_tokens,
  9986. size_t penalty_last_n,
  9987. float penalty_repeat,
  9988. float penalty_freq,
  9989. float penalty_present) {
  9990. if (penalty_last_n == 0 || (penalty_repeat == 1.0f && penalty_freq == 0.0f && penalty_present == 0.0f)) {
  9991. return;
  9992. }
  9993. const int64_t t_start_sample_us = ggml_time_us();
  9994. // Create a frequency map to count occurrences of each token in last_tokens
  9995. std::unordered_map<llama_token, int> token_count;
  9996. for (size_t i = 0; i < penalty_last_n; ++i) {
  9997. token_count[last_tokens[i]]++;
  9998. }
  9999. // Apply frequency and presence penalties to the candidates
  10000. for (size_t i = 0; i < candidates->size; ++i) {
  10001. const auto token_iter = token_count.find(candidates->data[i].id);
  10002. if (token_iter == token_count.end()) {
  10003. continue;
  10004. }
  10005. const int count = token_iter->second;
  10006. // 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.
  10007. // This is common fix for this problem, which is to multiply by the penalty instead of dividing.
  10008. if (candidates->data[i].logit <= 0) {
  10009. candidates->data[i].logit *= penalty_repeat;
  10010. } else {
  10011. candidates->data[i].logit /= penalty_repeat;
  10012. }
  10013. candidates->data[i].logit -= float(count) * penalty_freq + float(count > 0) * penalty_present;
  10014. }
  10015. candidates->sorted = false;
  10016. if (ctx) {
  10017. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10018. }
  10019. }
  10020. void llama_sample_grammar(struct llama_context * ctx, llama_token_data_array * candidates, const struct llama_grammar * grammar) {
  10021. GGML_ASSERT(ctx);
  10022. const int64_t t_start_sample_us = ggml_time_us();
  10023. bool allow_eos = false;
  10024. for (const auto & stack : grammar->stacks) {
  10025. if (stack.empty()) {
  10026. allow_eos = true;
  10027. break;
  10028. }
  10029. }
  10030. const llama_token eos = llama_token_eos(&ctx->model);
  10031. std::vector<std::pair<std::vector<uint32_t>, llama_partial_utf8>> candidates_decoded;
  10032. candidates_decoded.reserve(candidates->size);
  10033. std::vector<llama_grammar_candidate> candidates_grammar;
  10034. candidates_grammar.reserve(candidates->size);
  10035. for (size_t i = 0; i < candidates->size; ++i) {
  10036. const llama_token id = candidates->data[i].id;
  10037. const std::string piece = llama_token_to_piece(ctx, id);
  10038. if (id == eos) {
  10039. if (!allow_eos) {
  10040. candidates->data[i].logit = -INFINITY;
  10041. }
  10042. } else if (piece.empty() || piece[0] == 0) {
  10043. candidates->data[i].logit = -INFINITY;
  10044. } else {
  10045. candidates_decoded.push_back(decode_utf8(piece, grammar->partial_utf8));
  10046. candidates_grammar.push_back({ i, candidates_decoded.back().first.data(), candidates_decoded.back().second });
  10047. }
  10048. }
  10049. const auto rejects = llama_grammar_reject_candidates(grammar->rules, grammar->stacks, candidates_grammar);
  10050. for (const auto & reject : rejects) {
  10051. candidates->data[reject.index].logit = -INFINITY;
  10052. }
  10053. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10054. }
  10055. static void llama_log_softmax(float * array, size_t size) {
  10056. float max_l = *std::max_element(array, array + size);
  10057. float sum = 0.f;
  10058. for (size_t i = 0; i < size; ++i) {
  10059. float p = expf(array[i] - max_l);
  10060. sum += p;
  10061. array[i] = p;
  10062. }
  10063. for (size_t i = 0; i < size; ++i) {
  10064. array[i] = logf(array[i] / sum);
  10065. }
  10066. }
  10067. void llama_sample_apply_guidance(
  10068. struct llama_context * ctx,
  10069. float * logits,
  10070. float * logits_guidance,
  10071. float scale) {
  10072. GGML_ASSERT(ctx);
  10073. const auto t_start_sample_us = ggml_time_us();
  10074. const auto n_vocab = llama_n_vocab(llama_get_model(ctx));
  10075. llama_log_softmax(logits, n_vocab);
  10076. llama_log_softmax(logits_guidance, n_vocab);
  10077. for (int i = 0; i < n_vocab; ++i) {
  10078. auto & l = logits[i];
  10079. const auto & g = logits_guidance[i];
  10080. l = scale * (l - g) + g;
  10081. }
  10082. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10083. }
  10084. llama_token llama_sample_token_mirostat(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, int32_t m, float * mu) {
  10085. GGML_ASSERT(ctx);
  10086. auto N = float(llama_n_vocab(llama_get_model(ctx)));
  10087. int64_t t_start_sample_us;
  10088. t_start_sample_us = ggml_time_us();
  10089. llama_sample_softmax(nullptr, candidates);
  10090. // Estimate s_hat using the most probable m tokens
  10091. float s_hat = 0.0;
  10092. float sum_ti_bi = 0.0;
  10093. float sum_ti_sq = 0.0;
  10094. for (size_t i = 0; i < size_t(m - 1) && i < candidates->size - 1; ++i) {
  10095. float t_i = logf(float(i + 2) / float(i + 1));
  10096. float b_i = logf(candidates->data[i].p / candidates->data[i + 1].p);
  10097. sum_ti_bi += t_i * b_i;
  10098. sum_ti_sq += t_i * t_i;
  10099. }
  10100. s_hat = sum_ti_bi / sum_ti_sq;
  10101. // Compute k from the estimated s_hat and target surprise value
  10102. float epsilon_hat = s_hat - 1;
  10103. float k = powf((epsilon_hat * powf(2, *mu)) / (1 - powf(N, -epsilon_hat)), 1 / s_hat);
  10104. // Sample the next word X using top-k sampling
  10105. llama_sample_top_k(nullptr, candidates, int(k), 1);
  10106. if (ctx) {
  10107. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10108. }
  10109. llama_token X = llama_sample_token(ctx, candidates);
  10110. t_start_sample_us = ggml_time_us();
  10111. // Compute error as the difference between observed surprise and target surprise value
  10112. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  10113. return candidate.id == X;
  10114. }));
  10115. float observed_surprise = -log2f(candidates->data[X_idx].p);
  10116. float e = observed_surprise - tau;
  10117. // Update mu using the learning rate and error
  10118. *mu = *mu - eta * e;
  10119. if (ctx) {
  10120. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10121. }
  10122. return X;
  10123. }
  10124. llama_token llama_sample_token_mirostat_v2(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, float * mu) {
  10125. int64_t t_start_sample_us;
  10126. t_start_sample_us = ggml_time_us();
  10127. llama_sample_softmax(ctx, candidates);
  10128. // Truncate the words with surprise values greater than mu
  10129. candidates->size = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  10130. return -log2f(candidate.p) > *mu;
  10131. }));
  10132. if (candidates->size == 0) {
  10133. candidates->size = 1;
  10134. }
  10135. if (ctx) {
  10136. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10137. }
  10138. // Normalize the probabilities of the remaining words
  10139. llama_sample_softmax(ctx, candidates);
  10140. // Sample the next word X from the remaining words
  10141. llama_token X = llama_sample_token(ctx, candidates);
  10142. t_start_sample_us = ggml_time_us();
  10143. // Compute error as the difference between observed surprise and target surprise value
  10144. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  10145. return candidate.id == X;
  10146. }));
  10147. float observed_surprise = -log2f(candidates->data[X_idx].p);
  10148. float e = observed_surprise - tau;
  10149. // Update mu using the learning rate and error
  10150. *mu = *mu - eta * e;
  10151. if (ctx) {
  10152. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10153. }
  10154. return X;
  10155. }
  10156. llama_token llama_sample_token_greedy(struct llama_context * ctx, llama_token_data_array * candidates) {
  10157. const int64_t t_start_sample_us = ggml_time_us();
  10158. // Find max element
  10159. auto * max_iter = std::max_element(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  10160. return a.logit < b.logit;
  10161. });
  10162. llama_token result = max_iter->id;
  10163. if (ctx) {
  10164. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10165. ctx->n_sample++;
  10166. }
  10167. return result;
  10168. }
  10169. llama_token llama_sample_token(struct llama_context * ctx, llama_token_data_array * candidates) {
  10170. GGML_ASSERT(ctx);
  10171. const int64_t t_start_sample_us = ggml_time_us();
  10172. llama_sample_softmax(nullptr, candidates);
  10173. std::vector<float> probs;
  10174. probs.reserve(candidates->size);
  10175. for (size_t i = 0; i < candidates->size; ++i) {
  10176. probs.push_back(candidates->data[i].p);
  10177. }
  10178. std::discrete_distribution<> dist(probs.begin(), probs.end());
  10179. auto & rng = ctx->rng;
  10180. int idx = dist(rng);
  10181. llama_token result = candidates->data[idx].id;
  10182. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10183. ctx->n_sample++;
  10184. return result;
  10185. }
  10186. void llama_grammar_accept_token(struct llama_context * ctx, struct llama_grammar * grammar, llama_token token) {
  10187. const int64_t t_start_sample_us = ggml_time_us();
  10188. if (token == llama_token_eos(&ctx->model)) {
  10189. for (const auto & stack : grammar->stacks) {
  10190. if (stack.empty()) {
  10191. return;
  10192. }
  10193. }
  10194. GGML_ASSERT(false);
  10195. }
  10196. const std::string piece = llama_token_to_piece(ctx, token);
  10197. // Note terminating 0 in decoded string
  10198. const auto decoded = decode_utf8(piece, grammar->partial_utf8);
  10199. const auto & code_points = decoded.first;
  10200. for (auto it = code_points.begin(), end = code_points.end() - 1; it != end; ++it) {
  10201. grammar->stacks = llama_grammar_accept(grammar->rules, grammar->stacks, *it);
  10202. }
  10203. grammar->partial_utf8 = decoded.second;
  10204. GGML_ASSERT(!grammar->stacks.empty());
  10205. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10206. }
  10207. //
  10208. // Beam search
  10209. //
  10210. struct llama_beam {
  10211. std::vector<llama_token> tokens;
  10212. float p; // Cumulative beam probability (renormalized relative to all beams)
  10213. bool eob; // Initialize end-of-beam to false. Callback sets this to true.
  10214. // Sort beams by probability. In case of ties, prefer beams at eob.
  10215. bool operator<(const llama_beam & rhs) const {
  10216. return std::make_pair(p, eob) < std::make_pair(rhs.p, rhs.eob);
  10217. }
  10218. // Shift off first n tokens and discard them.
  10219. void shift_tokens(const size_t n) {
  10220. if (n) {
  10221. std::copy(tokens.begin() + n, tokens.end(), tokens.begin());
  10222. tokens.resize(tokens.size() - n);
  10223. }
  10224. }
  10225. llama_beam_view view() const { return {tokens.data(), tokens.size(), p, eob}; }
  10226. };
  10227. // A struct for calculating logit-related info.
  10228. struct llama_logit_info {
  10229. const float * const logits;
  10230. const int n_vocab;
  10231. const float max_l;
  10232. const float normalizer;
  10233. struct sum_exp {
  10234. float max_l;
  10235. float operator()(float sum, float l) const { return sum + std::exp(l - max_l); }
  10236. };
  10237. llama_logit_info(llama_context * ctx)
  10238. : logits(llama_get_logits(ctx))
  10239. , n_vocab(llama_n_vocab(llama_get_model(ctx)))
  10240. , max_l(*std::max_element(logits, logits + n_vocab))
  10241. , normalizer(1.0f / std::accumulate(logits, logits + n_vocab, 0.0f, sum_exp{max_l}))
  10242. { }
  10243. llama_token_data get_token_data(const llama_token token_id) const {
  10244. constexpr auto p = std::numeric_limits<float>::quiet_NaN(); // never used
  10245. return {token_id, logits[token_id], p};
  10246. }
  10247. // Return top k token_data by logit.
  10248. std::vector<llama_token_data> top_k(size_t k) {
  10249. std::vector<llama_token_data> min_heap; // min-heap by logit
  10250. const llama_token k_min = std::min(static_cast<llama_token>(k), n_vocab);
  10251. min_heap.reserve(k_min);
  10252. for (llama_token token_id = 0 ; token_id < k_min ; ++token_id) {
  10253. min_heap.push_back(get_token_data(token_id));
  10254. }
  10255. auto comp = [](const llama_token_data & a, const llama_token_data & b) { return a.logit > b.logit; };
  10256. std::make_heap(min_heap.begin(), min_heap.end(), comp);
  10257. for (llama_token token_id = k_min ; token_id < n_vocab ; ++token_id) {
  10258. if (min_heap.front().logit < logits[token_id]) {
  10259. std::pop_heap(min_heap.begin(), min_heap.end(), comp);
  10260. min_heap.back().id = token_id;
  10261. min_heap.back().logit = logits[token_id];
  10262. std::push_heap(min_heap.begin(), min_heap.end(), comp);
  10263. }
  10264. }
  10265. return min_heap;
  10266. }
  10267. float probability_from_logit(float logit) const {
  10268. return normalizer * std::exp(logit - max_l);
  10269. }
  10270. };
  10271. struct llama_beam_search_data {
  10272. llama_context * ctx;
  10273. size_t n_beams;
  10274. int n_past;
  10275. int n_predict;
  10276. std::vector<llama_beam> beams;
  10277. std::vector<llama_beam> next_beams;
  10278. // Re-calculated on each loop iteration
  10279. size_t common_prefix_length;
  10280. // Used to communicate to/from callback on beams state.
  10281. std::vector<llama_beam_view> beam_views;
  10282. llama_beam_search_data(llama_context * ctx, size_t n_beams, int n_past, int n_predict)
  10283. : ctx(ctx)
  10284. , n_beams(n_beams)
  10285. , n_past(n_past)
  10286. , n_predict(n_predict)
  10287. , beam_views(n_beams) {
  10288. beams.reserve(n_beams);
  10289. next_beams.reserve(n_beams);
  10290. }
  10291. // Collapse beams to a single beam given by index.
  10292. void collapse_beams(const size_t beam_idx) {
  10293. if (0u < beam_idx) {
  10294. std::swap(beams[0], beams[beam_idx]);
  10295. }
  10296. beams.resize(1);
  10297. }
  10298. // Min-heaps are used to efficiently collect the top-k elements (k=n_beams).
  10299. // The repetitive patterns below reflect the 2 stages of heaps:
  10300. // * Gather elements until the vector is full, then call std::make_heap() on it.
  10301. // * If the heap is full and a new element is found that should be included, pop the
  10302. // least element to the back(), replace it with the new, then push it into the heap.
  10303. void fill_next_beams_by_top_probabilities(llama_beam & beam) {
  10304. // Min-heaps use a greater-than comparator.
  10305. const auto comp = [](const llama_beam & a, const llama_beam & b) { return a.p > b.p; };
  10306. if (beam.eob) {
  10307. // beam is at end-of-sentence, so just copy it to next_beams if its probability is high enough.
  10308. if (next_beams.size() < n_beams) {
  10309. next_beams.push_back(std::move(beam));
  10310. if (next_beams.size() == n_beams) {
  10311. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  10312. }
  10313. } else if (next_beams.front().p < beam.p) {
  10314. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  10315. next_beams.back() = std::move(beam);
  10316. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  10317. }
  10318. } else {
  10319. // beam is not at end-of-sentence, so branch with next top_k tokens.
  10320. if (!beam.tokens.empty()) {
  10321. llama_decode(ctx, llama_batch_get_one(beam.tokens.data(), beam.tokens.size(), n_past, 0));
  10322. }
  10323. llama_logit_info logit_info(ctx);
  10324. std::vector<llama_token_data> next_tokens = logit_info.top_k(n_beams);
  10325. size_t i=0;
  10326. if (next_beams.size() < n_beams) {
  10327. for (; next_beams.size() < n_beams ; ++i) {
  10328. llama_beam next_beam = beam;
  10329. next_beam.tokens.push_back(next_tokens[i].id);
  10330. next_beam.p *= logit_info.probability_from_logit(next_tokens[i].logit);
  10331. next_beams.push_back(std::move(next_beam));
  10332. }
  10333. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  10334. } else {
  10335. for (; next_beams.front().p == 0.0f ; ++i) {
  10336. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  10337. next_beams.back() = beam;
  10338. next_beams.back().tokens.push_back(next_tokens[i].id);
  10339. next_beams.back().p *= logit_info.probability_from_logit(next_tokens[i].logit);
  10340. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  10341. }
  10342. }
  10343. for (; i < n_beams ; ++i) {
  10344. const float next_p = beam.p * logit_info.probability_from_logit(next_tokens[i].logit);
  10345. if (next_beams.front().p < next_p) {
  10346. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  10347. next_beams.back() = beam;
  10348. next_beams.back().tokens.push_back(next_tokens[i].id);
  10349. next_beams.back().p = next_p;
  10350. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  10351. }
  10352. }
  10353. }
  10354. }
  10355. // Find common_prefix_length based on beams.
  10356. // Requires beams is not empty.
  10357. size_t find_common_prefix_length() {
  10358. size_t common_prefix_length = beams[0].tokens.size();
  10359. for (size_t i = 1 ; i < beams.size() ; ++i) {
  10360. common_prefix_length = std::min(common_prefix_length, beams[i].tokens.size());
  10361. for (size_t j = 0 ; j < common_prefix_length ; ++j) {
  10362. if (beams[0].tokens[j] != beams[i].tokens[j]) {
  10363. common_prefix_length = j;
  10364. break;
  10365. }
  10366. }
  10367. }
  10368. return common_prefix_length;
  10369. }
  10370. // Construct beams_state to send back to caller via the callback function.
  10371. // Side effect: set common_prefix_length = find_common_prefix_length();
  10372. llama_beams_state get_beams_state(const bool last_call) {
  10373. for (size_t i = 0 ; i < beams.size() ; ++i) {
  10374. beam_views[i] = beams[i].view();
  10375. }
  10376. common_prefix_length = find_common_prefix_length();
  10377. return {beam_views.data(), beams.size(), common_prefix_length, last_call};
  10378. }
  10379. // Loop:
  10380. // * while i < n_predict, AND
  10381. // * any of the beams have not yet reached end-of-beam (eob), AND
  10382. // * the highest probability beam(s) (plural in case of ties) are not at end-of-sentence
  10383. // (since all other beam probabilities can only decrease)
  10384. void loop(const llama_beam_search_callback_fn_t callback, void * const callback_data) {
  10385. beams.push_back({{}, 1.0f, false}); // Start with one empty beam w/ probability = 1.0 and !eob.
  10386. const auto not_eob = [](const llama_beam & beam) { return !beam.eob; };
  10387. for (int i = 0 ; i < n_predict && std::any_of(beams.begin(),beams.end(),not_eob) &&
  10388. !beams[top_beam_index()].eob ; ++i) {
  10389. callback(callback_data, get_beams_state(false)); // Sets common_prefix_length
  10390. update_beams_from_beam_views(); // Update values (p,eob) that callback may have changed.
  10391. if (common_prefix_length) {
  10392. llama_decode(ctx, llama_batch_get_one(beams[0].tokens.data(), common_prefix_length, n_past, 0));
  10393. n_past += common_prefix_length;
  10394. }
  10395. // Zero-out next_beam probabilities to place them last in following min-heap.
  10396. std::for_each(next_beams.begin(), next_beams.end(), [](llama_beam & beam) { beam.p = 0.0f; });
  10397. for (llama_beam & beam : beams) {
  10398. beam.shift_tokens(common_prefix_length);
  10399. fill_next_beams_by_top_probabilities(beam);
  10400. }
  10401. // next_beams become the beams of next/final iteration. Swap them to re-use memory.
  10402. beams.swap(next_beams);
  10403. renormalize_beam_probabilities(beams);
  10404. }
  10405. collapse_beams(top_beam_index());
  10406. callback(callback_data, get_beams_state(true));
  10407. }
  10408. // As beams grow, the cumulative probabilities decrease.
  10409. // Renormalize them to avoid floating point underflow.
  10410. static void renormalize_beam_probabilities(std::vector<llama_beam> & beams) {
  10411. const auto sum_p = [](float sum, llama_beam & beam) { return sum + beam.p; };
  10412. const float inv_sum = 1.0f / std::accumulate(beams.begin(), beams.end(), 0.0f, sum_p);
  10413. std::for_each(beams.begin(), beams.end(), [=](llama_beam & beam) { beam.p *= inv_sum; });
  10414. }
  10415. // Assumes beams is non-empty. Uses llama_beam::operator<() for ordering.
  10416. size_t top_beam_index() {
  10417. return std::max_element(beams.begin(), beams.end()) - beams.begin();
  10418. }
  10419. // Copy (p,eob) for each beam which may have been changed by the callback.
  10420. void update_beams_from_beam_views() {
  10421. for (size_t i = 0 ; i < beams.size() ; ++i) {
  10422. beams[i].p = beam_views[i].p;
  10423. beams[i].eob = beam_views[i].eob;
  10424. }
  10425. }
  10426. };
  10427. void llama_beam_search(llama_context * ctx,
  10428. llama_beam_search_callback_fn_t callback, void * callback_data,
  10429. size_t n_beams, int n_past, int n_predict) {
  10430. assert(ctx);
  10431. const int64_t t_start_sample_us = ggml_time_us();
  10432. llama_beam_search_data beam_search_data(ctx, n_beams, n_past, n_predict);
  10433. beam_search_data.loop(callback, callback_data);
  10434. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  10435. ctx->n_sample++;
  10436. }
  10437. //
  10438. // quantization
  10439. //
  10440. struct quantize_state_internal {
  10441. const llama_model & model;
  10442. const llama_model_quantize_params * params;
  10443. int n_attention_wv = 0;
  10444. int n_ffn_down = 0;
  10445. int n_ffn_gate = 0;
  10446. int n_ffn_up = 0;
  10447. int i_attention_wv = 0;
  10448. int i_ffn_down = 0;
  10449. int i_ffn_gate = 0;
  10450. int i_ffn_up = 0;
  10451. int n_k_quantized = 0;
  10452. int n_fallback = 0;
  10453. bool has_imatrix = false;
  10454. // used to figure out if a model shares tok_embd with the output weight
  10455. bool has_output = false;
  10456. quantize_state_internal(const llama_model & model, const llama_model_quantize_params * params)
  10457. : model(model)
  10458. , params(params)
  10459. {}
  10460. };
  10461. static void llama_tensor_dequantize_internal(
  10462. struct ggml_tensor * tensor, std::vector<no_init<float>> & output, std::vector<std::thread> & workers,
  10463. const size_t nelements, const int nthread
  10464. ) {
  10465. if (output.size() < nelements) {
  10466. output.resize(nelements);
  10467. }
  10468. float * f32_output = (float *) output.data();
  10469. ggml_type_traits_t qtype;
  10470. if (ggml_is_quantized(tensor->type)) {
  10471. qtype = ggml_internal_get_type_traits(tensor->type);
  10472. if (qtype.to_float == NULL) {
  10473. throw std::runtime_error(format("type %s unsupported for integer quantization: no dequantization available", ggml_type_name(tensor->type)));
  10474. }
  10475. } else if (tensor->type != GGML_TYPE_F16) {
  10476. throw std::runtime_error(format("cannot dequantize/convert tensor type %s", ggml_type_name(tensor->type)));
  10477. }
  10478. if (nthread < 2) {
  10479. if (tensor->type == GGML_TYPE_F16) {
  10480. ggml_fp16_to_fp32_row((ggml_fp16_t *)tensor->data, f32_output, nelements);
  10481. } else if (ggml_is_quantized(tensor->type)) {
  10482. qtype.to_float(tensor->data, f32_output, nelements);
  10483. } else {
  10484. GGML_ASSERT(false); // unreachable
  10485. }
  10486. return;
  10487. }
  10488. size_t block_size = tensor->type == GGML_TYPE_F16 ? 1 : (size_t)ggml_blck_size(tensor->type);
  10489. size_t block_size_bytes = ggml_type_size(tensor->type);
  10490. GGML_ASSERT(nelements % block_size == 0);
  10491. size_t nblocks = nelements / block_size;
  10492. size_t blocks_per_thread = nblocks / nthread;
  10493. size_t spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count
  10494. size_t in_buff_offs = 0;
  10495. size_t out_buff_offs = 0;
  10496. for (int tnum = 0; tnum < nthread; tnum++) {
  10497. size_t thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread
  10498. size_t thr_elems = thr_blocks * block_size; // number of elements for this thread
  10499. size_t thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread
  10500. auto compute = [qtype] (ggml_type typ, uint8_t * inbuf, float * outbuf, int nels) {
  10501. if (typ == GGML_TYPE_F16) {
  10502. ggml_fp16_to_fp32_row((ggml_fp16_t *)inbuf, outbuf, nels);
  10503. } else {
  10504. qtype.to_float(inbuf, outbuf, nels);
  10505. }
  10506. };
  10507. workers.emplace_back(compute, tensor->type, (uint8_t *) tensor->data + in_buff_offs, f32_output + out_buff_offs, thr_elems);
  10508. in_buff_offs += thr_block_bytes;
  10509. out_buff_offs += thr_elems;
  10510. }
  10511. for (auto & w : workers) { w.join(); }
  10512. workers.clear();
  10513. }
  10514. static ggml_type llama_tensor_get_type(quantize_state_internal & qs, ggml_type new_type, const ggml_tensor * tensor, llama_ftype ftype) {
  10515. const std::string name = ggml_get_name(tensor);
  10516. // TODO: avoid hardcoded tensor names - use the TN_* constants
  10517. const llm_arch arch = qs.model.arch;
  10518. const auto tn = LLM_TN(arch);
  10519. auto use_more_bits = [](int i_layer, int num_layers) -> bool {
  10520. return i_layer < num_layers/8 || i_layer >= 7*num_layers/8 || (i_layer - num_layers/8)%3 == 2;
  10521. };
  10522. const int n_expert = std::max(1, (int)qs.model.hparams.n_expert);
  10523. auto layer_info = [n_expert] (int i_layer, int n_layer, const char * name) {
  10524. if (n_expert > 1) {
  10525. // Believe it or not, "experts" in the FFN of Mixtral-8x7B are not consecutive, but iccasionally randomly
  10526. // sprinkled in the model. Hence, simply dividing i_ffn_down by n_expert does not work
  10527. // for getting the current layer as I initially thought, and we need to resort to parsing the
  10528. // tensor name.
  10529. n_layer /= n_expert;
  10530. if (sscanf(name, "blk.%d.", &i_layer) != 1) {
  10531. throw std::runtime_error(format("Failed to determine layer for tensor %s", name));
  10532. }
  10533. if (i_layer < 0 || i_layer >= n_layer) {
  10534. throw std::runtime_error(format("Bad layer %d for tensor %s. Must be in [0, %d)", i_layer, name, n_layer));
  10535. }
  10536. }
  10537. return std::make_pair(i_layer, n_layer);
  10538. };
  10539. // for arches that share the same tensor between the token embeddings and the output, we quantize the token embeddings
  10540. // with the quantization of the output tensor
  10541. if (name == tn(LLM_TENSOR_OUTPUT, "weight") || (!qs.has_output && name == tn(LLM_TENSOR_TOKEN_EMBD, "weight"))) {
  10542. if (qs.params->output_tensor_type < GGML_TYPE_COUNT) {
  10543. new_type = qs.params->output_tensor_type;
  10544. } else {
  10545. int nx = tensor->ne[0];
  10546. if (arch == LLM_ARCH_FALCON || nx % QK_K != 0) {
  10547. new_type = GGML_TYPE_Q8_0;
  10548. }
  10549. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  10550. ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ||
  10551. ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  10552. new_type = GGML_TYPE_Q5_K;
  10553. }
  10554. else if (new_type != GGML_TYPE_Q8_0) {
  10555. new_type = GGML_TYPE_Q6_K;
  10556. }
  10557. }
  10558. } else if (name == "token_embd.weight") {
  10559. if (qs.params->token_embedding_type < GGML_TYPE_COUNT) {
  10560. new_type = qs.params->token_embedding_type;
  10561. } else {
  10562. if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS ||
  10563. ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  10564. new_type = GGML_TYPE_Q2_K;
  10565. }
  10566. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) {
  10567. new_type = GGML_TYPE_IQ3_S;
  10568. }
  10569. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  10570. new_type = GGML_TYPE_IQ3_S;
  10571. }
  10572. }
  10573. } else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S ||
  10574. ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) {
  10575. if (name.find("attn_v.weight") != std::string::npos) {
  10576. if (qs.model.hparams.n_gqa() >= 4 || qs.model.hparams.n_expert >= 4) new_type = GGML_TYPE_Q4_K;
  10577. else new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  10578. ++qs.i_attention_wv;
  10579. }
  10580. else if (qs.model.hparams.n_expert == 8 && name.find("attn_k.weight") != std::string::npos) {
  10581. new_type = GGML_TYPE_Q4_K;
  10582. }
  10583. else if (name.find("ffn_down") != std::string::npos) {
  10584. if (qs.i_ffn_down < qs.n_ffn_down/8) {
  10585. new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  10586. }
  10587. ++qs.i_ffn_down;
  10588. }
  10589. else if (name.find("attn_output.weight") != std::string::npos) {
  10590. if (qs.model.hparams.n_expert == 8) {
  10591. new_type = GGML_TYPE_Q5_K;
  10592. } else {
  10593. if (ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) new_type = GGML_TYPE_IQ2_XXS;
  10594. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) new_type = GGML_TYPE_IQ3_S;
  10595. }
  10596. }
  10597. } else if (name.find("attn_v.weight") != std::string::npos) {
  10598. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) {
  10599. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  10600. }
  10601. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && qs.model.hparams.n_gqa() >= 4) {
  10602. new_type = GGML_TYPE_Q4_K;
  10603. }
  10604. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  10605. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : !qs.has_imatrix ? GGML_TYPE_IQ3_S : GGML_TYPE_IQ3_XXS;
  10606. }
  10607. else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S) && qs.model.hparams.n_gqa() >= 4) {
  10608. new_type = GGML_TYPE_Q4_K;
  10609. }
  10610. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  10611. new_type = GGML_TYPE_Q4_K;
  10612. }
  10613. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  10614. new_type = qs.i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  10615. }
  10616. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  10617. else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && qs.model.hparams.n_gqa() >= 4) {
  10618. new_type = GGML_TYPE_Q5_K;
  10619. }
  10620. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
  10621. use_more_bits(qs.i_attention_wv, qs.n_attention_wv)) new_type = GGML_TYPE_Q6_K;
  10622. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && qs.i_attention_wv < 4) new_type = GGML_TYPE_Q5_K;
  10623. else if (QK_K == 64 && (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S) &&
  10624. (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;
  10625. if (qs.model.type == MODEL_70B) {
  10626. // In the 70B model we have 8 heads sharing the same attn_v weights. As a result, the attn_v.weight tensor is
  10627. // 8x smaller compared to attn_q.weight. Hence, we can get a nice boost in quantization accuracy with
  10628. // nearly negligible increase in model size by quantizing this tensor with more bits:
  10629. if (new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K) new_type = GGML_TYPE_Q5_K;
  10630. }
  10631. if (qs.model.hparams.n_expert == 8) {
  10632. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  10633. // TODO: explore better strategies
  10634. new_type = GGML_TYPE_Q8_0;
  10635. }
  10636. ++qs.i_attention_wv;
  10637. } else if (name.find("attn_k.weight") != std::string::npos) {
  10638. if (qs.model.hparams.n_expert == 8) {
  10639. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  10640. // TODO: explore better strategies
  10641. new_type = GGML_TYPE_Q8_0;
  10642. }
  10643. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  10644. new_type = GGML_TYPE_IQ3_XXS;
  10645. }
  10646. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  10647. new_type = GGML_TYPE_IQ2_S;
  10648. }
  10649. } else if (name.find("attn_q.weight") != std::string::npos) {
  10650. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  10651. new_type = GGML_TYPE_IQ3_XXS;
  10652. }
  10653. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  10654. new_type = GGML_TYPE_IQ2_S;
  10655. }
  10656. } else if (name.find("ffn_down") != std::string::npos) {
  10657. auto info = layer_info(qs.i_ffn_down, qs.n_ffn_down, name.c_str());
  10658. int i_layer = info.first, n_layer = info.second;
  10659. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  10660. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S) {
  10661. if (i_layer < n_layer/8) new_type = GGML_TYPE_Q4_K;
  10662. }
  10663. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS && !qs.has_imatrix) {
  10664. new_type = i_layer < n_layer/8 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  10665. }
  10666. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  10667. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q5_K
  10668. : arch != LLM_ARCH_FALCON || use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q4_K
  10669. : GGML_TYPE_Q3_K;
  10670. }
  10671. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M && (i_layer < n_layer/8 ||
  10672. (qs.model.hparams.n_expert == 8 && use_more_bits(i_layer, n_layer)))) {
  10673. new_type = GGML_TYPE_Q4_K;
  10674. }
  10675. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) {
  10676. new_type = arch == LLM_ARCH_FALCON ? GGML_TYPE_Q4_K : GGML_TYPE_Q5_K;
  10677. }
  10678. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  10679. if (arch == LLM_ARCH_FALCON) {
  10680. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q6_K :
  10681. use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  10682. } else {
  10683. if (use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  10684. }
  10685. }
  10686. else if (i_layer < n_layer/8 && (ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && !qs.has_imatrix) {
  10687. new_type = GGML_TYPE_Q5_K;
  10688. }
  10689. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M && use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  10690. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && arch != LLM_ARCH_FALCON && i_layer < n_layer/8) {
  10691. new_type = GGML_TYPE_Q5_K;
  10692. }
  10693. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_0 || ftype == LLAMA_FTYPE_MOSTLY_Q5_0)
  10694. && qs.has_imatrix && i_layer < n_layer/8) {
  10695. // Guard against craziness in the first few ffn_down layers that can happen even with imatrix for Q4_0/Q5_0.
  10696. // We only do it when an imatrix is provided because a) we want to make sure that one can always get the
  10697. // same quantization as before imatrix stuff, and b) Q4_1/Q5_1 do go crazy on ffn_down without an imatrix.
  10698. new_type = ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ? GGML_TYPE_Q4_1 : GGML_TYPE_Q5_1;
  10699. }
  10700. ++qs.i_ffn_down;
  10701. } else if (name.find("attn_output.weight") != std::string::npos) {
  10702. if (arch != LLM_ARCH_FALCON) {
  10703. if (qs.model.hparams.n_expert == 8) {
  10704. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  10705. ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL ||
  10706. ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S ||
  10707. ftype == LLAMA_FTYPE_MOSTLY_IQ3_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) {
  10708. new_type = GGML_TYPE_Q5_K;
  10709. }
  10710. } else {
  10711. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K ) new_type = GGML_TYPE_Q3_K;
  10712. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) new_type = GGML_TYPE_IQ3_S;
  10713. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M ) new_type = GGML_TYPE_Q4_K;
  10714. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L ) new_type = GGML_TYPE_Q5_K;
  10715. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M ) new_type = GGML_TYPE_Q4_K;
  10716. }
  10717. } else {
  10718. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  10719. }
  10720. }
  10721. else if (name.find("attn_qkv.weight") != std::string::npos) {
  10722. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L || ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  10723. new_type = GGML_TYPE_Q4_K;
  10724. }
  10725. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) new_type = GGML_TYPE_Q5_K;
  10726. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) new_type = GGML_TYPE_Q6_K;
  10727. }
  10728. else if (name.find("ffn_gate") != std::string::npos) {
  10729. auto info = layer_info(qs.i_ffn_gate, qs.n_ffn_gate, name.c_str());
  10730. int i_layer = info.first, n_layer = info.second;
  10731. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  10732. new_type = GGML_TYPE_IQ3_XXS;
  10733. }
  10734. ++qs.i_ffn_gate;
  10735. }
  10736. else if (name.find("ffn_up") != std::string::npos) {
  10737. auto info = layer_info(qs.i_ffn_up, qs.n_ffn_up, name.c_str());
  10738. int i_layer = info.first, n_layer = info.second;
  10739. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  10740. new_type = GGML_TYPE_IQ3_XXS;
  10741. }
  10742. ++qs.i_ffn_up;
  10743. }
  10744. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  10745. //}
  10746. // IK: let's remove this, else Q2_K is almost the same as Q3_K_S
  10747. //else if (name.find("ffn_gate") != std::string::npos || name.find("ffn_up") != std::string::npos) {
  10748. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  10749. //}
  10750. // This can be used to reduce the size of the Q5_K_S model.
  10751. // The associated PPL increase is fully in line with the size reduction
  10752. //else {
  10753. // if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_S) new_type = GGML_TYPE_Q4_K;
  10754. //}
  10755. bool convert_incompatible_tensor = false;
  10756. if (new_type == GGML_TYPE_Q2_K || new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K ||
  10757. new_type == GGML_TYPE_Q5_K || new_type == GGML_TYPE_Q6_K || new_type == GGML_TYPE_IQ4_XS ||
  10758. new_type == GGML_TYPE_IQ2_XS || new_type == GGML_TYPE_IQ2_XXS || new_type == GGML_TYPE_IQ2_S ||
  10759. new_type == GGML_TYPE_IQ3_XXS || new_type == GGML_TYPE_IQ1_S || new_type == GGML_TYPE_IQ3_S ||
  10760. new_type == GGML_TYPE_IQ1_M) {
  10761. int nx = tensor->ne[0];
  10762. int ny = tensor->ne[1];
  10763. if (nx % QK_K != 0) {
  10764. 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));
  10765. convert_incompatible_tensor = true;
  10766. } else {
  10767. ++qs.n_k_quantized;
  10768. }
  10769. }
  10770. if (convert_incompatible_tensor) {
  10771. switch (new_type) {
  10772. case GGML_TYPE_IQ2_XXS:
  10773. case GGML_TYPE_IQ2_XS:
  10774. case GGML_TYPE_IQ2_S:
  10775. case GGML_TYPE_IQ3_XXS:
  10776. case GGML_TYPE_IQ3_S:
  10777. case GGML_TYPE_IQ1_S:
  10778. case GGML_TYPE_IQ1_M:
  10779. case GGML_TYPE_Q2_K:
  10780. case GGML_TYPE_Q3_K:
  10781. case GGML_TYPE_IQ4_XS: new_type = GGML_TYPE_IQ4_NL; break;
  10782. case GGML_TYPE_Q4_K: new_type = GGML_TYPE_Q5_0; break;
  10783. case GGML_TYPE_Q5_K: new_type = GGML_TYPE_Q5_1; break;
  10784. case GGML_TYPE_Q6_K: new_type = GGML_TYPE_Q8_0; break;
  10785. default: throw std::runtime_error("\nUnsupported tensor size encountered\n");
  10786. }
  10787. LLAMA_LOG_WARN(" - using fallback quantization %s\n", ggml_type_name(new_type));
  10788. ++qs.n_fallback;
  10789. }
  10790. return new_type;
  10791. }
  10792. 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) {
  10793. std::mutex mutex;
  10794. int counter = 0;
  10795. size_t new_size = 0;
  10796. if (nthread < 2) {
  10797. // single-thread
  10798. return ggml_quantize_chunk(new_type, f32_data, new_data, 0, nrows, n_per_row, imatrix);
  10799. }
  10800. auto compute = [&mutex, &counter, &new_size, new_type, f32_data, new_data, chunk_size,
  10801. nrows, n_per_row, imatrix]() {
  10802. const int nrows_per_chunk = chunk_size / n_per_row;
  10803. size_t local_size = 0;
  10804. while (true) {
  10805. std::unique_lock<std::mutex> lock(mutex);
  10806. int first_row = counter; counter += nrows_per_chunk;
  10807. if (first_row >= nrows) {
  10808. if (local_size > 0) {
  10809. new_size += local_size;
  10810. }
  10811. break;
  10812. }
  10813. lock.unlock();
  10814. const int this_nrow = std::min(nrows - first_row, nrows_per_chunk);
  10815. local_size += ggml_quantize_chunk(new_type, f32_data, new_data, first_row * n_per_row, this_nrow, n_per_row, imatrix);
  10816. }
  10817. };
  10818. for (int it = 0; it < nthread - 1; ++it) {
  10819. workers.emplace_back(compute);
  10820. }
  10821. compute();
  10822. for (auto & w : workers) { w.join(); }
  10823. workers.clear();
  10824. return new_size;
  10825. }
  10826. static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) {
  10827. ggml_type default_type;
  10828. llama_ftype ftype = params->ftype;
  10829. switch (params->ftype) {
  10830. case LLAMA_FTYPE_MOSTLY_Q4_0: default_type = GGML_TYPE_Q4_0; break;
  10831. case LLAMA_FTYPE_MOSTLY_Q4_1: default_type = GGML_TYPE_Q4_1; break;
  10832. case LLAMA_FTYPE_MOSTLY_Q5_0: default_type = GGML_TYPE_Q5_0; break;
  10833. case LLAMA_FTYPE_MOSTLY_Q5_1: default_type = GGML_TYPE_Q5_1; break;
  10834. case LLAMA_FTYPE_MOSTLY_Q8_0: default_type = GGML_TYPE_Q8_0; break;
  10835. case LLAMA_FTYPE_MOSTLY_F16: default_type = GGML_TYPE_F16; break;
  10836. case LLAMA_FTYPE_ALL_F32: default_type = GGML_TYPE_F32; break;
  10837. // K-quants
  10838. case LLAMA_FTYPE_MOSTLY_Q2_K_S:
  10839. case LLAMA_FTYPE_MOSTLY_Q2_K: default_type = GGML_TYPE_Q2_K; break;
  10840. case LLAMA_FTYPE_MOSTLY_IQ3_XS: default_type = GGML_TYPE_IQ3_S; break;
  10841. case LLAMA_FTYPE_MOSTLY_Q3_K_S:
  10842. case LLAMA_FTYPE_MOSTLY_Q3_K_M:
  10843. case LLAMA_FTYPE_MOSTLY_Q3_K_L: default_type = GGML_TYPE_Q3_K; break;
  10844. case LLAMA_FTYPE_MOSTLY_Q4_K_S:
  10845. case LLAMA_FTYPE_MOSTLY_Q4_K_M: default_type = GGML_TYPE_Q4_K; break;
  10846. case LLAMA_FTYPE_MOSTLY_Q5_K_S:
  10847. case LLAMA_FTYPE_MOSTLY_Q5_K_M: default_type = GGML_TYPE_Q5_K; break;
  10848. case LLAMA_FTYPE_MOSTLY_Q6_K: default_type = GGML_TYPE_Q6_K; break;
  10849. case LLAMA_FTYPE_MOSTLY_IQ2_XXS: default_type = GGML_TYPE_IQ2_XXS; break;
  10850. case LLAMA_FTYPE_MOSTLY_IQ2_XS: default_type = GGML_TYPE_IQ2_XS; break;
  10851. case LLAMA_FTYPE_MOSTLY_IQ2_S: default_type = GGML_TYPE_IQ2_XS; break;
  10852. case LLAMA_FTYPE_MOSTLY_IQ2_M: default_type = GGML_TYPE_IQ2_S; break;
  10853. case LLAMA_FTYPE_MOSTLY_IQ3_XXS: default_type = GGML_TYPE_IQ3_XXS; break;
  10854. case LLAMA_FTYPE_MOSTLY_IQ1_S: default_type = GGML_TYPE_IQ1_S; break;
  10855. case LLAMA_FTYPE_MOSTLY_IQ1_M: default_type = GGML_TYPE_IQ1_M; break;
  10856. case LLAMA_FTYPE_MOSTLY_IQ4_NL: default_type = GGML_TYPE_IQ4_NL; break;
  10857. case LLAMA_FTYPE_MOSTLY_IQ4_XS: default_type = GGML_TYPE_IQ4_XS; break;
  10858. case LLAMA_FTYPE_MOSTLY_IQ3_S: default_type = GGML_TYPE_IQ3_S; break;
  10859. case LLAMA_FTYPE_MOSTLY_IQ3_M: default_type = GGML_TYPE_IQ3_S; break;
  10860. default: throw std::runtime_error(format("invalid output file type %d\n", ftype));
  10861. }
  10862. int nthread = params->nthread;
  10863. if (nthread <= 0) {
  10864. nthread = std::thread::hardware_concurrency();
  10865. }
  10866. // mmap consistently increases speed Linux, and also increases speed on Windows with
  10867. // hot cache. It may cause a slowdown on macOS, possibly related to free memory.
  10868. #if defined(__linux__) || defined(_WIN32)
  10869. constexpr bool use_mmap = true;
  10870. #else
  10871. constexpr bool use_mmap = false;
  10872. #endif
  10873. llama_model_kv_override * kv_overrides = nullptr;
  10874. if (params->kv_overrides) {
  10875. auto v = (std::vector<llama_model_kv_override>*)params->kv_overrides;
  10876. kv_overrides = v->data();
  10877. }
  10878. llama_model_loader ml(fname_inp, use_mmap, kv_overrides);
  10879. ml.init_mappings(false); // no prefetching?
  10880. llama_model model;
  10881. llm_load_arch(ml, model);
  10882. llm_load_hparams(ml, model);
  10883. struct quantize_state_internal qs(model, params);
  10884. if (params->only_copy) {
  10885. ftype = model.ftype;
  10886. }
  10887. const std::unordered_map<std::string, std::vector<float>> * imatrix_data = nullptr;
  10888. if (params->imatrix) {
  10889. imatrix_data = static_cast<const std::unordered_map<std::string, std::vector<float>>*>(params->imatrix);
  10890. if (imatrix_data) {
  10891. LLAMA_LOG_INFO("================================ Have weights data with %d entries\n",int(imatrix_data->size()));
  10892. qs.has_imatrix = true;
  10893. }
  10894. }
  10895. const size_t align = GGUF_DEFAULT_ALIGNMENT;
  10896. struct gguf_context * ctx_out = gguf_init_empty();
  10897. // copy the KV pairs from the input file
  10898. gguf_set_kv (ctx_out, ml.meta);
  10899. gguf_set_val_u32(ctx_out, "general.quantization_version", GGML_QNT_VERSION);
  10900. gguf_set_val_u32(ctx_out, "general.file_type", ftype);
  10901. if (params->kv_overrides) {
  10902. const std::vector<llama_model_kv_override> & overrides = *(const std::vector<llama_model_kv_override> *)params->kv_overrides;
  10903. for (auto & o : overrides) {
  10904. if (o.key[0] == 0) break;
  10905. if (o.tag == LLAMA_KV_OVERRIDE_TYPE_FLOAT) {
  10906. gguf_set_val_f32(ctx_out, o.key, o.float_value);
  10907. } else if (o.tag == LLAMA_KV_OVERRIDE_TYPE_INT) {
  10908. gguf_set_val_i32(ctx_out, o.key, o.int_value);
  10909. } else if (o.tag == LLAMA_KV_OVERRIDE_TYPE_BOOL) {
  10910. gguf_set_val_bool(ctx_out, o.key, o.bool_value);
  10911. } else {
  10912. LLAMA_LOG_WARN("%s: unknown KV override type for key %s\n", __func__, o.key);
  10913. }
  10914. }
  10915. }
  10916. for (int i = 0; i < ml.n_tensors; ++i) {
  10917. const struct ggml_tensor * meta = ml.get_tensor_meta(i);
  10918. const std::string name = ggml_get_name(meta);
  10919. // TODO: avoid hardcoded tensor names - use the TN_* constants
  10920. if (name.find("attn_v.weight") != std::string::npos || name.find("attn_qkv.weight") != std::string::npos) {
  10921. ++qs.n_attention_wv;
  10922. } else if (name.find("ffn_down") != std::string::npos) {
  10923. ++qs.n_ffn_down;
  10924. } else if (name.find("ffn_gate") != std::string::npos) {
  10925. ++qs.n_ffn_gate;
  10926. } else if (name.find("ffn_up") != std::string::npos) {
  10927. ++qs.n_ffn_up;
  10928. } else if (name == LLM_TN(model.arch)(LLM_TENSOR_OUTPUT, "weight")) {
  10929. qs.has_output = true;
  10930. }
  10931. }
  10932. if (qs.n_attention_wv != qs.n_ffn_down || (uint32_t) qs.n_attention_wv != model.hparams.n_layer) {
  10933. LLAMA_LOG_WARN("%s ============ Strange model: n_attention_wv = %d, n_ffn_down = %d, hparams.n_layer = %d\n",
  10934. __func__, qs.n_attention_wv, qs.n_ffn_down, model.hparams.n_layer);
  10935. }
  10936. size_t total_size_org = 0;
  10937. size_t total_size_new = 0;
  10938. std::vector<std::thread> workers;
  10939. workers.reserve(nthread);
  10940. int idx = 0;
  10941. std::vector<no_init<uint8_t>> read_data;
  10942. std::vector<no_init<uint8_t>> work;
  10943. std::vector<no_init<float>> f32_conv_buf;
  10944. // populate the original tensors so we get an initial meta data
  10945. for (int i = 0; i < ml.n_tensors; ++i) {
  10946. const struct ggml_tensor * meta = ml.get_tensor_meta(i);
  10947. gguf_add_tensor(ctx_out, meta);
  10948. }
  10949. std::ofstream fout(fname_out, std::ios::binary);
  10950. fout.exceptions(std::ofstream::failbit); // fail fast on write errors
  10951. const size_t meta_size = gguf_get_meta_size(ctx_out);
  10952. LLAMA_LOG_INFO("%s: meta size = %zu bytes\n", __func__, meta_size);
  10953. // placeholder for the meta data
  10954. ::zeros(fout, meta_size);
  10955. for (int i = 0; i < ml.n_tensors; ++i) {
  10956. struct ggml_tensor * tensor = ml.get_tensor_meta(i);
  10957. const std::string name = ggml_get_name(tensor);
  10958. if (!ml.use_mmap) {
  10959. if (read_data.size() < ggml_nbytes(tensor)) {
  10960. read_data.resize(ggml_nbytes(tensor));
  10961. }
  10962. tensor->data = read_data.data();
  10963. }
  10964. ml.load_data_for(tensor);
  10965. LLAMA_LOG_INFO("[%4d/%4d] %36s - [%s], type = %6s, ",
  10966. ++idx, ml.n_tensors,
  10967. ggml_get_name(tensor),
  10968. llama_format_tensor_shape(tensor).c_str(),
  10969. ggml_type_name(tensor->type));
  10970. // This used to be a regex, but <regex> has an extreme cost to compile times.
  10971. bool quantize = name.rfind("weight") == name.size() - 6; // ends with 'weight'?
  10972. // quantize only 2D tensors
  10973. quantize &= (ggml_n_dims(tensor) == 2);
  10974. quantize &= params->quantize_output_tensor || name != "output.weight";
  10975. quantize &= !params->only_copy;
  10976. // do not quantize expert gating tensors
  10977. // NOTE: can't use LLM_TN here because the layer number is not known
  10978. quantize &= name.find("ffn_gate_inp.weight") == std::string::npos;
  10979. // do not quantize positional embeddings and token types (BERT)
  10980. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_POS_EMBD, "weight");
  10981. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_TOKEN_TYPES, "weight");
  10982. // do not quantize Mamba's small yet 2D weights
  10983. // NOTE: can't use LLM_TN here because the layer number is not known
  10984. quantize &= name.find("ssm_conv1d.weight") == std::string::npos;
  10985. quantize &= name.find("ssm_x.weight") == std::string::npos;
  10986. quantize &= name.find("ssm_dt.weight") == std::string::npos;
  10987. enum ggml_type new_type;
  10988. void * new_data;
  10989. size_t new_size;
  10990. if (quantize) {
  10991. new_type = default_type;
  10992. // get more optimal quantization type based on the tensor shape, layer, etc.
  10993. if (!params->pure && ggml_is_quantized(default_type)) {
  10994. new_type = llama_tensor_get_type(qs, new_type, tensor, ftype);
  10995. }
  10996. else if (params->token_embedding_type < GGML_TYPE_COUNT && strcmp(tensor->name, "token_embd.weight") == 0) {
  10997. new_type = params->token_embedding_type;
  10998. }
  10999. else if (params->output_tensor_type < GGML_TYPE_COUNT && strcmp(tensor->name, "output.weight") == 0) {
  11000. new_type = params->output_tensor_type;
  11001. }
  11002. // If we've decided to quantize to the same type the tensor is already
  11003. // in then there's nothing to do.
  11004. quantize = tensor->type != new_type;
  11005. }
  11006. if (!quantize) {
  11007. new_type = tensor->type;
  11008. new_data = tensor->data;
  11009. new_size = ggml_nbytes(tensor);
  11010. LLAMA_LOG_INFO("size = %8.3f MB\n", ggml_nbytes(tensor)/1024.0/1024.0);
  11011. } else {
  11012. const size_t nelements = ggml_nelements(tensor);
  11013. const float * imatrix = nullptr;
  11014. if (imatrix_data) {
  11015. auto it = imatrix_data->find(tensor->name);
  11016. if (it == imatrix_data->end()) {
  11017. LLAMA_LOG_INFO("\n====== %s: did not find weights for %s\n", __func__, tensor->name);
  11018. } else {
  11019. if (it->second.size() == (size_t)tensor->ne[0]) {
  11020. imatrix = it->second.data();
  11021. } else {
  11022. LLAMA_LOG_INFO("\n====== %s: imatrix size %d is different from tensor size %d for %s\n", __func__,
  11023. int(it->second.size()), int(tensor->ne[0]), tensor->name);
  11024. }
  11025. }
  11026. }
  11027. if ((new_type == GGML_TYPE_IQ2_XXS ||
  11028. new_type == GGML_TYPE_IQ2_XS ||
  11029. new_type == GGML_TYPE_IQ2_S ||
  11030. new_type == GGML_TYPE_IQ1_S ||
  11031. (new_type == GGML_TYPE_IQ1_M && strcmp(tensor->name, "token_embd.weight") && strcmp(tensor->name, "output.weight")) ||
  11032. (new_type == GGML_TYPE_Q2_K && params->ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && strcmp(tensor->name, "token_embd.weight") != 0)) && !imatrix) {
  11033. LLAMA_LOG_ERROR("\n\n============================================================\n");
  11034. LLAMA_LOG_ERROR("Missing importance matrix for tensor %s in a very low-bit quantization\n", tensor->name);
  11035. LLAMA_LOG_ERROR("The result will be garbage, so bailing out\n");
  11036. LLAMA_LOG_ERROR("============================================================\n\n");
  11037. throw std::runtime_error(format("Missing importance matrix for tensor %s in a very low-bit quantization", tensor->name));
  11038. }
  11039. float * f32_data;
  11040. if (tensor->type == GGML_TYPE_F32) {
  11041. f32_data = (float *) tensor->data;
  11042. } else if (ggml_is_quantized(tensor->type) && !params->allow_requantize) {
  11043. throw std::runtime_error(format("requantizing from type %s is disabled", ggml_type_name(tensor->type)));
  11044. } else {
  11045. llama_tensor_dequantize_internal(tensor, f32_conv_buf, workers, nelements, nthread);
  11046. f32_data = (float *) f32_conv_buf.data();
  11047. }
  11048. LLAMA_LOG_INFO("converting to %s .. ", ggml_type_name(new_type));
  11049. fflush(stdout);
  11050. if (work.size() < nelements * 4) {
  11051. work.resize(nelements * 4); // upper bound on size
  11052. }
  11053. new_data = work.data();
  11054. const int n_per_row = tensor->ne[0];
  11055. const int nrows = nelements / n_per_row;
  11056. static const int min_chunk_size = 32 * 512;
  11057. 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);
  11058. const int nchunk = (nelements + chunk_size - 1)/chunk_size;
  11059. const int nthread_use = nthread > 1 ? std::max(1, std::min(nthread, nchunk)) : 1;
  11060. new_size = llama_tensor_quantize_internal(new_type, f32_data, new_data, chunk_size, nrows, n_per_row, imatrix, workers, nthread_use);
  11061. LLAMA_LOG_INFO("size = %8.2f MiB -> %8.2f MiB\n", ggml_nbytes(tensor)/1024.0/1024.0, new_size/1024.0/1024.0);
  11062. }
  11063. total_size_org += ggml_nbytes(tensor);
  11064. total_size_new += new_size;
  11065. // update the gguf meta data as we go
  11066. gguf_set_tensor_type(ctx_out, name.c_str(), new_type);
  11067. gguf_set_tensor_data(ctx_out, name.c_str(), new_data, new_size);
  11068. // write tensor data + padding
  11069. fout.write((const char *) new_data, new_size);
  11070. zeros(fout, GGML_PAD(new_size, align) - new_size);
  11071. }
  11072. // go back to beginning of file and write the updated meta data
  11073. {
  11074. fout.seekp(0);
  11075. std::vector<uint8_t> data(gguf_get_meta_size(ctx_out));
  11076. gguf_get_meta_data(ctx_out, data.data());
  11077. fout.write((const char *) data.data(), data.size());
  11078. }
  11079. fout.close();
  11080. gguf_free(ctx_out);
  11081. LLAMA_LOG_INFO("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  11082. LLAMA_LOG_INFO("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  11083. if (qs.n_fallback > 0) {
  11084. LLAMA_LOG_WARN("%s: WARNING: %d of %d tensor(s) required fallback quantization\n",
  11085. __func__, qs.n_fallback, qs.n_k_quantized + qs.n_fallback);
  11086. }
  11087. }
  11088. static int llama_apply_lora_from_file_internal(
  11089. const struct llama_model & model, const char * path_lora, float scale, const char * path_base_model, int n_threads
  11090. ) {
  11091. LLAMA_LOG_INFO("%s: applying lora adapter from '%s' - please wait ...\n", __func__, path_lora);
  11092. const int64_t t_start_lora_us = ggml_time_us();
  11093. llama_file fin(path_lora, "rb");
  11094. // verify magic and version
  11095. {
  11096. uint32_t magic = fin.read_u32();
  11097. if (magic != LLAMA_FILE_MAGIC_GGLA) {
  11098. LLAMA_LOG_ERROR("%s: bad file magic\n", __func__);
  11099. return 1;
  11100. }
  11101. uint32_t format_version = fin.read_u32();
  11102. if (format_version != 1) {
  11103. LLAMA_LOG_ERROR("%s: unsupported file version\n", __func__ );
  11104. return 1;
  11105. }
  11106. }
  11107. int32_t lora_r = fin.read_u32();
  11108. int32_t lora_alpha = fin.read_u32();
  11109. float scaling = scale * (float)lora_alpha / (float)lora_r;
  11110. LLAMA_LOG_INFO("%s: r = %d, alpha = %d, scaling = %.2f\n", __func__, lora_r, lora_alpha, scaling);
  11111. // load base model
  11112. std::unique_ptr<llama_model_loader> ml;
  11113. if (path_base_model) {
  11114. LLAMA_LOG_INFO("%s: loading base model from '%s'\n", __func__, path_base_model);
  11115. ml.reset(new llama_model_loader(path_base_model, /*use_mmap*/ true, /*kv_overrides*/ nullptr));
  11116. ml->init_mappings(/*prefetch*/ false); // no prefetching
  11117. }
  11118. struct tensor_meta {
  11119. std::string name;
  11120. ggml_type type;
  11121. int32_t ne[2];
  11122. size_t offset;
  11123. };
  11124. std::map<std::string, tensor_meta> tensor_meta_map;
  11125. // load all tensor meta
  11126. while (true) {
  11127. if (fin.tell() == fin.size) {
  11128. // eof
  11129. break;
  11130. }
  11131. int32_t n_dims;
  11132. int32_t name_len;
  11133. int32_t ftype;
  11134. fin.read_raw(&n_dims, sizeof(n_dims));
  11135. fin.read_raw(&name_len, sizeof(name_len));
  11136. fin.read_raw(&ftype, sizeof(ftype));
  11137. if (n_dims != 1 && n_dims != 2) {
  11138. LLAMA_LOG_ERROR("%s: unsupported tensor dimension %d\n", __func__, n_dims);
  11139. return 1;
  11140. }
  11141. int32_t ne[2] = { 1, 1 };
  11142. for (int i = 0; i < n_dims; ++i) {
  11143. fin.read_raw(&ne[i], sizeof(ne[i]));
  11144. }
  11145. std::string name;
  11146. {
  11147. GGML_ASSERT(name_len < GGML_MAX_NAME);
  11148. char buf[GGML_MAX_NAME];
  11149. fin.read_raw(buf, name_len);
  11150. name = std::string(buf, name_len);
  11151. }
  11152. // check for lora suffix
  11153. std::string lora_suffix;
  11154. if (name.length() > 6) {
  11155. lora_suffix = name.substr(name.length() - 6);
  11156. }
  11157. if (lora_suffix != ".loraA" && lora_suffix != ".loraB") {
  11158. LLAMA_LOG_ERROR("%s: error: '%s' is not a lora tensor\n", __func__, name.c_str());
  11159. return 1;
  11160. }
  11161. // tensor type
  11162. ggml_type wtype;
  11163. switch (ftype) {
  11164. case 0: wtype = GGML_TYPE_F32; break;
  11165. case 1: wtype = GGML_TYPE_F16; break;
  11166. default:
  11167. {
  11168. LLAMA_LOG_ERROR("%s: invalid tensor data type '%d'\n",
  11169. __func__, ftype);
  11170. return 1;
  11171. }
  11172. }
  11173. // data offset
  11174. size_t offset = fin.tell();
  11175. offset = (offset + 31) & -32;
  11176. // skip tensor data
  11177. fin.seek(offset + ggml_row_size(wtype, ne[0]) * ne[1], SEEK_SET);
  11178. tensor_meta_map.emplace(name, tensor_meta{ name, wtype, { ne[0], ne[1] }, offset });
  11179. }
  11180. bool warned = false;
  11181. int n_tensors = 0;
  11182. // apply
  11183. ggml_backend_t backend_cpu = ggml_backend_cpu_init();
  11184. if (backend_cpu == nullptr) {
  11185. LLAMA_LOG_ERROR("%s: error: failed to initialize cpu backend\n", __func__);
  11186. return 1;
  11187. }
  11188. ggml_backend_cpu_set_n_threads(backend_cpu, n_threads);
  11189. std::vector<no_init<uint8_t>> read_buf;
  11190. for (const auto & it : model.tensors_by_name) {
  11191. const std::string & base_name = it.first;
  11192. ggml_tensor * model_t = it.second;
  11193. if (tensor_meta_map.find(base_name + ".loraA") == tensor_meta_map.end() ||
  11194. tensor_meta_map.find(base_name + ".loraB") == tensor_meta_map.end()) {
  11195. continue;
  11196. }
  11197. tensor_meta & metaA = tensor_meta_map.at(base_name + ".loraA");
  11198. tensor_meta & metaB = tensor_meta_map.at(base_name + ".loraB");
  11199. ggml_init_params lora_init_params = {
  11200. /* .mem_size */ ggml_tensor_overhead()*128 + ggml_graph_overhead(),
  11201. /* .mem_buffer */ nullptr,
  11202. /* .no_alloc */ true,
  11203. };
  11204. ggml_context * lora_ctx = ggml_init(lora_init_params);
  11205. if (lora_ctx == nullptr) {
  11206. LLAMA_LOG_ERROR("%s: error: failed to initialize lora context\n", __func__);
  11207. ggml_backend_free(backend_cpu);
  11208. return 1;
  11209. }
  11210. // create tensors
  11211. ggml_tensor * loraA = ggml_new_tensor_2d(lora_ctx, metaA.type, metaA.ne[0], metaA.ne[1]);
  11212. ggml_tensor * loraB = ggml_new_tensor_2d(lora_ctx, metaB.type, metaB.ne[0], metaB.ne[1]);
  11213. ggml_set_name(loraA, metaA.name.c_str());
  11214. ggml_set_name(loraB, metaB.name.c_str());
  11215. ggml_tensor * base_t;
  11216. if (ml) {
  11217. if (!ml->get_tensor_meta(base_name.c_str())) {
  11218. LLAMA_LOG_ERROR("%s: error: tensor '%s' not found in base model\n", __func__, base_name.c_str());
  11219. return 1;
  11220. }
  11221. base_t = ggml_dup_tensor(lora_ctx, ml->get_tensor_meta(base_name.c_str()));
  11222. } else {
  11223. base_t = ggml_dup_tensor(lora_ctx, model_t);
  11224. }
  11225. ggml_set_name(base_t, base_name.c_str());
  11226. // allocate in backend buffer
  11227. ggml_backend_buffer_t lora_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  11228. if (lora_buf == nullptr) {
  11229. LLAMA_LOG_ERROR("%s: error: failed to allocate lora tensors\n", __func__);
  11230. return 1;
  11231. }
  11232. // load tensor data
  11233. auto load_tensor = [&read_buf, &fin](const tensor_meta & tensor_meta, ggml_tensor * tensor) {
  11234. read_buf.resize(ggml_nbytes(tensor));
  11235. fin.seek(tensor_meta.offset, SEEK_SET);
  11236. fin.read_raw(read_buf.data(), ggml_nbytes(tensor));
  11237. ggml_backend_tensor_set(tensor, read_buf.data(), 0, read_buf.size());
  11238. };
  11239. load_tensor(metaA, loraA);
  11240. load_tensor(metaB, loraB);
  11241. // load base model tensor data
  11242. if (ml) {
  11243. ml->load_data_for(base_t);
  11244. } else {
  11245. ggml_backend_tensor_copy(model_t, base_t);
  11246. }
  11247. if (ggml_is_quantized(base_t->type) && !warned) {
  11248. LLAMA_LOG_WARN("%s: warning: using a lora adapter with a quantized model may result in poor quality, "
  11249. "use a f16 or f32 base model with --lora-base\n", __func__);
  11250. warned = true;
  11251. }
  11252. if (base_t->ne[0] != loraA->ne[1] || base_t->ne[1] != loraB->ne[1]) {
  11253. LLAMA_LOG_ERROR("%s: incompatible tensor dimensions (%" PRId64 " and %" PRId64 ");"
  11254. " are you sure that this adapter is for this model?\n", __func__, base_t->ne[0], loraA->ne[1]);
  11255. ggml_free(lora_ctx);
  11256. ggml_backend_buffer_free(lora_buf);
  11257. ggml_backend_free(backend_cpu);
  11258. return 1;
  11259. }
  11260. auto build_lora_graph = [&]() {
  11261. // w = w + BA*s
  11262. ggml_tensor * BA = ggml_mul_mat(lora_ctx, loraA, loraB);
  11263. ggml_set_name(BA, "BA");
  11264. if (scaling != 1.0f) {
  11265. BA = ggml_scale(lora_ctx, BA, scaling);
  11266. ggml_set_name(BA, "BA_scaled");
  11267. }
  11268. ggml_tensor * r;
  11269. r = ggml_add_inplace(lora_ctx, base_t, BA);
  11270. ggml_set_name(r, "r_add");
  11271. if (base_t->type != model_t->type) {
  11272. // convert the result to the model type
  11273. r = ggml_cast(lora_ctx, r, model_t->type);
  11274. ggml_set_name(r, "r_cast");
  11275. }
  11276. return r;
  11277. };
  11278. ggml_cgraph * gf = ggml_new_graph(lora_ctx);
  11279. ggml_tensor * r = build_lora_graph();
  11280. ggml_build_forward_expand(gf, r);
  11281. ggml_backend_buffer_t graph_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  11282. if (graph_buf == nullptr) {
  11283. LLAMA_LOG_ERROR("%s: error: failed to allocate graph tensors\n", __func__);
  11284. ggml_free(lora_ctx);
  11285. ggml_backend_buffer_free(lora_buf);
  11286. ggml_backend_free(backend_cpu);
  11287. return 1;
  11288. }
  11289. ggml_backend_graph_compute(backend_cpu, gf);
  11290. ggml_backend_tensor_set(model_t, r->data, 0, ggml_nbytes(r));
  11291. #if 0
  11292. // TODO: use scheduler with fallback to CPU for less copies between CPU and GPU
  11293. //ggml_backend_sched_t sched = ggml_backend_sched_new(backends.data(), backends.size(), GGML_DEFAULT_GRAPH_SIZE);
  11294. // sched compute
  11295. ggml_build_forward_expand(gf, build_graph());
  11296. ggml_backend_sched_init_measure(sched, gf);
  11297. // create the graph again, since the previous one was destroyed by the measure
  11298. ggml_graph_clear(gf);
  11299. ggml_build_forward_expand(gf, build_graph());
  11300. ggml_backend_sched_graph_compute(sched, gf);
  11301. ggml_backend_sched_free(sched);
  11302. #endif
  11303. ggml_backend_buffer_free(lora_buf);
  11304. ggml_backend_buffer_free(graph_buf);
  11305. ggml_free(lora_ctx);
  11306. n_tensors++;
  11307. if (n_tensors % 4 == 0) {
  11308. LLAMA_LOG_INFO(".");
  11309. }
  11310. }
  11311. ggml_backend_free(backend_cpu);
  11312. const int64_t t_lora_us = ggml_time_us() - t_start_lora_us;
  11313. LLAMA_LOG_INFO(" done (%.2f ms)\n", t_lora_us / 1000.0);
  11314. return 0;
  11315. }
  11316. //
  11317. // interface implementation
  11318. //
  11319. struct llama_model_params llama_model_default_params() {
  11320. struct llama_model_params result = {
  11321. /*.n_gpu_layers =*/ 0,
  11322. /*.split_mode =*/ LLAMA_SPLIT_MODE_LAYER,
  11323. /*.main_gpu =*/ 0,
  11324. /*.tensor_split =*/ nullptr,
  11325. /*.progress_callback =*/ nullptr,
  11326. /*.progress_callback_user_data =*/ nullptr,
  11327. /*.kv_overrides =*/ nullptr,
  11328. /*.vocab_only =*/ false,
  11329. /*.use_mmap =*/ true,
  11330. /*.use_mlock =*/ false,
  11331. };
  11332. #ifdef GGML_USE_METAL
  11333. // note: we usually have plenty of VRAM, so by default offload all layers to the GPU
  11334. result.n_gpu_layers = 999;
  11335. #endif
  11336. return result;
  11337. }
  11338. struct llama_context_params llama_context_default_params() {
  11339. struct llama_context_params result = {
  11340. /*.seed =*/ LLAMA_DEFAULT_SEED,
  11341. /*.n_ctx =*/ 512,
  11342. /*.n_batch =*/ 2048,
  11343. /*.n_ubatch =*/ 512,
  11344. /*.n_seq_max =*/ 1,
  11345. /*.n_threads =*/ GGML_DEFAULT_N_THREADS, // TODO: better default
  11346. /*.n_threads_batch =*/ GGML_DEFAULT_N_THREADS,
  11347. /*.rope_scaling_type =*/ LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED,
  11348. /*.pooling_type =*/ LLAMA_POOLING_TYPE_UNSPECIFIED,
  11349. /*.rope_freq_base =*/ 0.0f,
  11350. /*.rope_freq_scale =*/ 0.0f,
  11351. /*.yarn_ext_factor =*/ -1.0f,
  11352. /*.yarn_attn_factor =*/ 1.0f,
  11353. /*.yarn_beta_fast =*/ 32.0f,
  11354. /*.yarn_beta_slow =*/ 1.0f,
  11355. /*.yarn_orig_ctx =*/ 0,
  11356. /*.defrag_thold =*/ -1.0f,
  11357. /*.cb_eval =*/ nullptr,
  11358. /*.cb_eval_user_data =*/ nullptr,
  11359. /*.type_k =*/ GGML_TYPE_F16,
  11360. /*.type_v =*/ GGML_TYPE_F16,
  11361. /*.logits_all =*/ false,
  11362. /*.embeddings =*/ false,
  11363. /*.offload_kqv =*/ true,
  11364. /*.abort_callback =*/ nullptr,
  11365. /*.abort_callback_data =*/ nullptr,
  11366. };
  11367. return result;
  11368. }
  11369. struct llama_model_quantize_params llama_model_quantize_default_params() {
  11370. struct llama_model_quantize_params result = {
  11371. /*.nthread =*/ 0,
  11372. /*.ftype =*/ LLAMA_FTYPE_MOSTLY_Q5_1,
  11373. /*.output_tensor_type =*/ GGML_TYPE_COUNT,
  11374. /*.token_embedding_type =*/ GGML_TYPE_COUNT,
  11375. /*.allow_requantize =*/ false,
  11376. /*.quantize_output_tensor =*/ true,
  11377. /*.only_copy =*/ false,
  11378. /*.pure =*/ false,
  11379. /*.imatrix =*/ nullptr,
  11380. /*.kv_overrides =*/ nullptr,
  11381. };
  11382. return result;
  11383. }
  11384. size_t llama_max_devices(void) {
  11385. #if defined(GGML_USE_METAL)
  11386. return 1;
  11387. #elif defined(GGML_USE_CUDA)
  11388. return GGML_CUDA_MAX_DEVICES;
  11389. #elif defined(GGML_USE_SYCL)
  11390. return GGML_SYCL_MAX_DEVICES;
  11391. #elif defined(GGML_USE_VULKAN)
  11392. return GGML_VK_MAX_DEVICES;
  11393. #else
  11394. return 1;
  11395. #endif
  11396. }
  11397. bool llama_supports_mmap(void) {
  11398. return llama_mmap::SUPPORTED;
  11399. }
  11400. bool llama_supports_mlock(void) {
  11401. return llama_mlock::SUPPORTED;
  11402. }
  11403. bool llama_supports_gpu_offload(void) {
  11404. #if defined(GGML_USE_CUDA) || defined(GGML_USE_CLBLAST) || defined(GGML_USE_METAL) || defined(GGML_USE_VULKAN) || \
  11405. defined(GGML_USE_SYCL) || defined(GGML_USE_KOMPUTE)
  11406. // Defined when llama.cpp is compiled with support for offloading model layers to GPU.
  11407. return true;
  11408. #else
  11409. return false;
  11410. #endif
  11411. }
  11412. void llama_backend_init(void) {
  11413. ggml_time_init();
  11414. // needed to initialize f16 tables
  11415. {
  11416. struct ggml_init_params params = { 0, NULL, false };
  11417. struct ggml_context * ctx = ggml_init(params);
  11418. ggml_free(ctx);
  11419. }
  11420. #ifdef GGML_USE_MPI
  11421. ggml_mpi_backend_init();
  11422. #endif
  11423. }
  11424. void llama_numa_init(enum ggml_numa_strategy numa) {
  11425. if (numa != GGML_NUMA_STRATEGY_DISABLED) {
  11426. ggml_numa_init(numa);
  11427. }
  11428. }
  11429. void llama_backend_free(void) {
  11430. #ifdef GGML_USE_MPI
  11431. ggml_mpi_backend_free();
  11432. #endif
  11433. ggml_quantize_free();
  11434. }
  11435. int64_t llama_time_us(void) {
  11436. return ggml_time_us();
  11437. }
  11438. struct llama_model * llama_load_model_from_file(
  11439. const char * path_model,
  11440. struct llama_model_params params) {
  11441. ggml_time_init();
  11442. llama_model * model = new llama_model;
  11443. unsigned cur_percentage = 0;
  11444. if (params.progress_callback == NULL) {
  11445. params.progress_callback_user_data = &cur_percentage;
  11446. params.progress_callback = [](float progress, void * ctx) {
  11447. unsigned * cur_percentage_p = (unsigned *) ctx;
  11448. unsigned percentage = (unsigned) (100 * progress);
  11449. while (percentage > *cur_percentage_p) {
  11450. *cur_percentage_p = percentage;
  11451. LLAMA_LOG_INFO(".");
  11452. if (percentage >= 100) {
  11453. LLAMA_LOG_INFO("\n");
  11454. }
  11455. }
  11456. return true;
  11457. };
  11458. }
  11459. int status = llama_model_load(path_model, *model, params);
  11460. GGML_ASSERT(status <= 0);
  11461. if (status < 0) {
  11462. if (status == -1) {
  11463. LLAMA_LOG_ERROR("%s: failed to load model\n", __func__);
  11464. } else if (status == -2) {
  11465. LLAMA_LOG_INFO("%s: cancelled model load\n", __func__);
  11466. }
  11467. delete model;
  11468. return nullptr;
  11469. }
  11470. return model;
  11471. }
  11472. void llama_free_model(struct llama_model * model) {
  11473. delete model;
  11474. }
  11475. struct llama_context * llama_new_context_with_model(
  11476. struct llama_model * model,
  11477. struct llama_context_params params) {
  11478. if (!model) {
  11479. LLAMA_LOG_ERROR("%s: model cannot be NULL\n", __func__);
  11480. return nullptr;
  11481. }
  11482. if (params.n_batch == 0 && params.n_ubatch == 0) {
  11483. LLAMA_LOG_ERROR("%s: n_batch and n_ubatch cannot both be zero\n", __func__);
  11484. return nullptr;
  11485. }
  11486. if (params.n_ctx == 0 && model->hparams.n_ctx_train == 0) {
  11487. LLAMA_LOG_ERROR("%s: n_ctx and model->hparams.n_ctx_train cannot both be zero\n", __func__);
  11488. return nullptr;
  11489. }
  11490. llama_context * ctx = new llama_context(*model);
  11491. const auto & hparams = model->hparams;
  11492. auto & cparams = ctx->cparams;
  11493. cparams.n_seq_max = std::max(1u, params.n_seq_max);
  11494. cparams.n_threads = params.n_threads;
  11495. cparams.n_threads_batch = params.n_threads_batch;
  11496. cparams.yarn_ext_factor = params.yarn_ext_factor;
  11497. cparams.yarn_attn_factor = params.yarn_attn_factor;
  11498. cparams.yarn_beta_fast = params.yarn_beta_fast;
  11499. cparams.yarn_beta_slow = params.yarn_beta_slow;
  11500. cparams.defrag_thold = params.defrag_thold;
  11501. cparams.embeddings = params.embeddings;
  11502. cparams.offload_kqv = params.offload_kqv;
  11503. cparams.pooling_type = params.pooling_type;
  11504. cparams.n_ctx = params.n_ctx == 0 ? hparams.n_ctx_train : params.n_ctx;
  11505. cparams.rope_freq_base = params.rope_freq_base == 0.0f ? hparams.rope_freq_base_train : params.rope_freq_base;
  11506. cparams.rope_freq_scale = params.rope_freq_scale == 0.0f ? hparams.rope_freq_scale_train : params.rope_freq_scale;
  11507. // this is necessary due to kv_self.n being padded later during inference
  11508. cparams.n_ctx = GGML_PAD(cparams.n_ctx, 32);
  11509. // with causal attention, the batch size is limited by the context size
  11510. cparams.n_batch = hparams.causal_attn ? std::min(cparams.n_ctx, params.n_batch) : params.n_batch;
  11511. cparams.n_ubatch = std::min(cparams.n_batch, params.n_ubatch == 0 ? params.n_batch : params.n_ubatch);
  11512. cparams.n_yarn_orig_ctx = params.yarn_orig_ctx != 0 ? params.yarn_orig_ctx :
  11513. hparams.n_yarn_orig_ctx != 0 ? hparams.n_yarn_orig_ctx :
  11514. hparams.n_ctx_train;
  11515. cparams.cb_eval = params.cb_eval;
  11516. cparams.cb_eval_user_data = params.cb_eval_user_data;
  11517. auto rope_scaling_type = params.rope_scaling_type;
  11518. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED) {
  11519. rope_scaling_type = hparams.rope_scaling_type_train;
  11520. }
  11521. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_NONE) {
  11522. cparams.rope_freq_scale = 1.0f; // never scale if scaling type is none
  11523. }
  11524. if (cparams.yarn_ext_factor < 0.0f) { // negative indicates 'not set'
  11525. cparams.yarn_ext_factor = rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_YARN ? 1.0f : 0.0f;
  11526. }
  11527. cparams.causal_attn = hparams.causal_attn;
  11528. if (cparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  11529. if (hparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  11530. cparams.pooling_type = LLAMA_POOLING_TYPE_NONE;
  11531. } else {
  11532. cparams.pooling_type = hparams.pooling_type;
  11533. }
  11534. }
  11535. if (params.seed == LLAMA_DEFAULT_SEED) {
  11536. params.seed = time(NULL);
  11537. }
  11538. LLAMA_LOG_INFO("%s: n_ctx = %u\n", __func__, cparams.n_ctx);
  11539. LLAMA_LOG_INFO("%s: n_batch = %u\n", __func__, cparams.n_batch);
  11540. LLAMA_LOG_INFO("%s: n_ubatch = %u\n", __func__, cparams.n_ubatch);
  11541. LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, cparams.rope_freq_base);
  11542. LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, cparams.rope_freq_scale);
  11543. ctx->abort_callback = params.abort_callback;
  11544. ctx->abort_callback_data = params.abort_callback_data;
  11545. ctx->rng = std::mt19937(params.seed);
  11546. ctx->logits_all = params.logits_all;
  11547. uint32_t kv_size = cparams.n_ctx;
  11548. ggml_type type_k = params.type_k;
  11549. ggml_type type_v = params.type_v;
  11550. // Mamba only needs a constant number of KV cache cells per sequence
  11551. if (model->arch == LLM_ARCH_MAMBA) {
  11552. // Mamba needs at least as many KV cells as there are sequences kept at any time
  11553. kv_size = std::max((uint32_t) 1, params.n_seq_max);
  11554. // it's probably best to keep as much precision as possible for the states
  11555. type_k = GGML_TYPE_F32; // required by ggml_ssm_conv for Mamba's conv_states
  11556. type_v = GGML_TYPE_F32; // required by ggml_ssm_scan for Mamba's ssm_states
  11557. }
  11558. GGML_ASSERT(hparams.n_embd_head_k % ggml_blck_size(type_k) == 0);
  11559. GGML_ASSERT(hparams.n_embd_head_v % ggml_blck_size(type_v) == 0);
  11560. if (!hparams.vocab_only) {
  11561. // initialize backends
  11562. #ifdef GGML_USE_METAL
  11563. if (model->n_gpu_layers > 0) {
  11564. ctx->backend_metal = ggml_backend_metal_init();
  11565. if (ctx->backend_metal == nullptr) {
  11566. LLAMA_LOG_ERROR("%s: failed to initialize Metal backend\n", __func__);
  11567. llama_free(ctx);
  11568. return nullptr;
  11569. }
  11570. ctx->backends.push_back(ctx->backend_metal);
  11571. }
  11572. #elif defined(GGML_USE_CUDA)
  11573. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  11574. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  11575. ggml_backend_t backend = ggml_backend_cuda_init(model->main_gpu);
  11576. if (backend == nullptr) {
  11577. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, model->main_gpu);
  11578. llama_free(ctx);
  11579. return nullptr;
  11580. }
  11581. ctx->backends.push_back(backend);
  11582. } else {
  11583. // LLAMA_SPLIT_MODE_LAYER requires a backend for each GPU
  11584. for (int device = 0; device < ggml_backend_cuda_get_device_count(); ++device) {
  11585. ggml_backend_t backend = ggml_backend_cuda_init(device);
  11586. if (backend == nullptr) {
  11587. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, device);
  11588. llama_free(ctx);
  11589. return nullptr;
  11590. }
  11591. ctx->backends.push_back(backend);
  11592. }
  11593. }
  11594. #elif defined(GGML_USE_VULKAN)
  11595. if (model->n_gpu_layers > 0) {
  11596. for (int device = 0; device < ggml_backend_vk_get_device_count(); ++device) {
  11597. ggml_backend_t backend = ggml_backend_vk_init(device);
  11598. if (backend == nullptr) {
  11599. LLAMA_LOG_ERROR("%s: failed to initialize Vulkan%d backend\n", __func__, device);
  11600. llama_free(ctx);
  11601. return nullptr;
  11602. }
  11603. ctx->backends.push_back(backend);
  11604. }
  11605. }
  11606. #elif defined(GGML_USE_SYCL)
  11607. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  11608. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  11609. ggml_backend_t backend = ggml_backend_sycl_init(model->main_gpu);
  11610. if (backend == nullptr) {
  11611. int main_gpu_id = ggml_backend_sycl_get_device_id(model->main_gpu);
  11612. LLAMA_LOG_ERROR("%s: failed to initialize SYCL%d (index %d) backend\n", __func__, main_gpu_id, model->main_gpu);
  11613. llama_free(ctx);
  11614. return nullptr;
  11615. }
  11616. ctx->backends.push_back(backend);
  11617. } else {
  11618. // LLAMA_SPLIT_LAYER requires a backend for each GPU
  11619. for (int i = 0; i < ggml_backend_sycl_get_device_count(); ++i) {
  11620. ggml_backend_t backend = ggml_backend_sycl_init(i);
  11621. if (backend == nullptr) {
  11622. int id_list[GGML_SYCL_MAX_DEVICES];
  11623. ggml_sycl_get_gpu_list(id_list, GGML_SYCL_MAX_DEVICES);
  11624. LLAMA_LOG_ERROR("%s: failed to initialize SYCL%d (index %d) backend\n", __func__, id_list[i], i);
  11625. llama_free(ctx);
  11626. return nullptr;
  11627. }
  11628. ctx->backends.push_back(backend);
  11629. }
  11630. }
  11631. #elif defined(GGML_USE_KOMPUTE)
  11632. if (model->n_gpu_layers > 0) {
  11633. auto * backend = ggml_backend_kompute_init(model->main_gpu);
  11634. if (backend == nullptr) {
  11635. LLAMA_LOG_ERROR("%s: failed to initialize Kompute backend\n", __func__);
  11636. llama_free(ctx);
  11637. return nullptr;
  11638. }
  11639. ctx->backends.push_back(backend);
  11640. }
  11641. #endif
  11642. ctx->backend_cpu = ggml_backend_cpu_init();
  11643. if (ctx->backend_cpu == nullptr) {
  11644. LLAMA_LOG_ERROR("%s: failed to initialize CPU backend\n", __func__);
  11645. llama_free(ctx);
  11646. return nullptr;
  11647. }
  11648. ctx->backends.push_back(ctx->backend_cpu);
  11649. if (!llama_kv_cache_init(ctx->kv_self, ctx->model, type_k, type_v, kv_size, cparams.offload_kqv)) {
  11650. LLAMA_LOG_ERROR("%s: llama_kv_cache_init() failed for self-attention cache\n", __func__);
  11651. llama_free(ctx);
  11652. return nullptr;
  11653. }
  11654. {
  11655. size_t memory_size_k = 0;
  11656. size_t memory_size_v = 0;
  11657. for (auto & k : ctx->kv_self.k_l) {
  11658. memory_size_k += ggml_nbytes(k);
  11659. }
  11660. for (auto & v : ctx->kv_self.v_l) {
  11661. memory_size_v += ggml_nbytes(v);
  11662. }
  11663. LLAMA_LOG_INFO("%s: KV self size = %7.2f MiB, K (%s): %7.2f MiB, V (%s): %7.2f MiB\n", __func__,
  11664. (float)(memory_size_k + memory_size_v) / (1024.0f * 1024.0f),
  11665. ggml_type_name(type_k), (float)memory_size_k / (1024.0f * 1024.0f),
  11666. ggml_type_name(type_v), (float)memory_size_v / (1024.0f * 1024.0f));
  11667. }
  11668. // graph outputs buffer
  11669. {
  11670. // resized during inference when a batch uses more outputs
  11671. if (llama_output_reserve(*ctx, params.n_seq_max) < params.n_seq_max) {
  11672. LLAMA_LOG_ERROR("%s: failed to reserve initial output buffer\n", __func__);
  11673. llama_free(ctx);
  11674. return nullptr;
  11675. }
  11676. LLAMA_LOG_INFO("%s: %10s output buffer size = %8.2f MiB\n", __func__,
  11677. ggml_backend_buffer_name(ctx->buf_output),
  11678. ggml_backend_buffer_get_size(ctx->buf_output) / 1024.0 / 1024.0);
  11679. }
  11680. // scheduler and compute buffers
  11681. {
  11682. // buffer types used for the compute buffer of each backend
  11683. std::vector<ggml_backend_buffer_type_t> backend_buft;
  11684. for (auto * backend : ctx->backends) {
  11685. if (ggml_backend_is_cpu(backend)) {
  11686. // use host buffers for the CPU backend compute buffer
  11687. backend_buft.push_back(llama_default_buffer_type_cpu(true));
  11688. } else {
  11689. backend_buft.push_back(ggml_backend_get_default_buffer_type(backend));
  11690. }
  11691. }
  11692. // buffer used to store the computation graph and the tensor meta data
  11693. ctx->buf_compute_meta.resize(ggml_tensor_overhead()*LLAMA_MAX_NODES + ggml_graph_overhead_custom(LLAMA_MAX_NODES, false));
  11694. // enabling pipeline parallelism in the scheduler increases memory usage, so it is only done when necessary
  11695. bool pipeline_parallel = llama_get_device_count() > 1 && model->n_gpu_layers > (int)model->hparams.n_layer && model->split_mode == LLAMA_SPLIT_MODE_LAYER;
  11696. #ifndef GGML_USE_CUDA
  11697. // pipeline parallelism requires support for async compute and events
  11698. // currently this is only implemented in the CUDA backend
  11699. pipeline_parallel = false;
  11700. #endif
  11701. ctx->sched = ggml_backend_sched_new(ctx->backends.data(), backend_buft.data(), ctx->backends.size(), LLAMA_MAX_NODES, pipeline_parallel);
  11702. if (pipeline_parallel) {
  11703. LLAMA_LOG_INFO("%s: pipeline parallelism enabled (n_copies=%d)\n", __func__, ggml_backend_sched_get_n_copies(ctx->sched));
  11704. }
  11705. // build worst-case graph
  11706. int n_tokens = (int)std::min(cparams.n_ctx, cparams.n_ubatch);
  11707. int n_past = cparams.n_ctx - n_tokens;
  11708. 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
  11709. ggml_cgraph * gf = llama_build_graph(*ctx, llama_batch_get_one(&token, n_tokens, n_past, 0), true);
  11710. // initialize scheduler with the worst-case graph
  11711. if (!ggml_backend_sched_reserve(ctx->sched, gf)) {
  11712. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  11713. llama_free(ctx);
  11714. return nullptr;
  11715. }
  11716. for (size_t i = 0; i < ctx->backends.size(); i++) {
  11717. ggml_backend_t backend = ctx->backends[i];
  11718. ggml_backend_buffer_type_t buft = backend_buft[i];
  11719. size_t size = ggml_backend_sched_get_buffer_size(ctx->sched, backend);
  11720. if (size > 1) {
  11721. LLAMA_LOG_INFO("%s: %10s compute buffer size = %8.2f MiB\n", __func__,
  11722. ggml_backend_buft_name(buft),
  11723. size / 1024.0 / 1024.0);
  11724. }
  11725. }
  11726. // note: the number of splits during measure is higher than during inference due to the kv shift
  11727. int n_splits = ggml_backend_sched_get_n_splits(ctx->sched);
  11728. LLAMA_LOG_INFO("%s: graph nodes = %d\n", __func__, gf->n_nodes);
  11729. LLAMA_LOG_INFO("%s: graph splits = %d\n", __func__, n_splits);
  11730. }
  11731. }
  11732. #ifdef GGML_USE_MPI
  11733. ctx->ctx_mpi = ggml_mpi_init();
  11734. if (ggml_mpi_rank(ctx->ctx_mpi) > 0) {
  11735. // Enter a blocking eval loop with dummy input, letting rank=0 drive the process
  11736. // TODO: needs fix after #3228
  11737. GGML_ASSERT(false && "not implemented");
  11738. //const std::vector<llama_token> tmp(ctx->model.hparams.n_ctx, llama_token_bos(ctx));
  11739. //while (!llama_eval(ctx, tmp.data(), tmp.size(), 0, 0)) {};
  11740. llama_backend_free();
  11741. exit(1);
  11742. }
  11743. #endif
  11744. return ctx;
  11745. }
  11746. void llama_free(struct llama_context * ctx) {
  11747. delete ctx;
  11748. }
  11749. const llama_model * llama_get_model(const struct llama_context * ctx) {
  11750. return &ctx->model;
  11751. }
  11752. uint32_t llama_n_ctx(const struct llama_context * ctx) {
  11753. return ctx->cparams.n_ctx;
  11754. }
  11755. uint32_t llama_n_batch(const struct llama_context * ctx) {
  11756. return ctx->cparams.n_batch;
  11757. }
  11758. uint32_t llama_n_ubatch(const struct llama_context * ctx) {
  11759. return ctx->cparams.n_ubatch;
  11760. }
  11761. uint32_t llama_n_seq_max(const struct llama_context * ctx) {
  11762. return ctx->kv_self.size;
  11763. }
  11764. enum llama_vocab_type llama_vocab_type(const struct llama_model * model) {
  11765. return model->vocab.type;
  11766. }
  11767. enum llama_rope_type llama_rope_type(const struct llama_model * model) {
  11768. switch (model->arch) {
  11769. // these models do not use RoPE
  11770. case LLM_ARCH_GPT2:
  11771. case LLM_ARCH_GPTJ:
  11772. case LLM_ARCH_GPTNEOX:
  11773. case LLM_ARCH_MPT:
  11774. case LLM_ARCH_REFACT:
  11775. case LLM_ARCH_BLOOM:
  11776. case LLM_ARCH_MAMBA:
  11777. return LLAMA_ROPE_TYPE_NONE;
  11778. // use what we call a normal RoPE, operating on pairs of consecutive head values
  11779. case LLM_ARCH_LLAMA:
  11780. case LLM_ARCH_BAICHUAN:
  11781. case LLM_ARCH_STARCODER:
  11782. case LLM_ARCH_PLAMO:
  11783. case LLM_ARCH_CODESHELL:
  11784. case LLM_ARCH_ORION:
  11785. case LLM_ARCH_INTERNLM2:
  11786. case LLM_ARCH_MINICPM:
  11787. case LLM_ARCH_COMMAND_R:
  11788. return LLAMA_ROPE_TYPE_NORM;
  11789. // the pairs of head values are offset by n_rot/2
  11790. case LLM_ARCH_FALCON:
  11791. case LLM_ARCH_GROK:
  11792. case LLM_ARCH_PERSIMMON:
  11793. case LLM_ARCH_BERT:
  11794. case LLM_ARCH_NOMIC_BERT:
  11795. case LLM_ARCH_STABLELM:
  11796. case LLM_ARCH_QWEN:
  11797. case LLM_ARCH_QWEN2:
  11798. case LLM_ARCH_PHI2:
  11799. case LLM_ARCH_GEMMA:
  11800. case LLM_ARCH_STARCODER2:
  11801. return LLAMA_ROPE_TYPE_NEOX;
  11802. // all model arches should be listed explicitly here
  11803. case LLM_ARCH_UNKNOWN:
  11804. GGML_ASSERT(false && "unknown architecture");
  11805. break;
  11806. }
  11807. return LLAMA_ROPE_TYPE_NONE;
  11808. }
  11809. int32_t llama_n_vocab(const struct llama_model * model) {
  11810. return model->hparams.n_vocab;
  11811. }
  11812. int32_t llama_n_ctx_train(const struct llama_model * model) {
  11813. return model->hparams.n_ctx_train;
  11814. }
  11815. int32_t llama_n_embd(const struct llama_model * model) {
  11816. return model->hparams.n_embd;
  11817. }
  11818. int32_t llama_n_layer(const struct llama_model * model) {
  11819. return model->hparams.n_layer;
  11820. }
  11821. float llama_rope_freq_scale_train(const struct llama_model * model) {
  11822. return model->hparams.rope_freq_scale_train;
  11823. }
  11824. int32_t llama_model_meta_val_str(const struct llama_model * model, const char * key, char * buf, size_t buf_size) {
  11825. const auto & it = model->gguf_kv.find(key);
  11826. if (it == model->gguf_kv.end()) {
  11827. if (buf_size > 0) {
  11828. buf[0] = '\0';
  11829. }
  11830. return -1;
  11831. }
  11832. return snprintf(buf, buf_size, "%s", it->second.c_str());
  11833. }
  11834. int32_t llama_model_meta_count(const struct llama_model * model) {
  11835. return (int)model->gguf_kv.size();
  11836. }
  11837. int32_t llama_model_meta_key_by_index(const struct llama_model * model, int i, char * buf, size_t buf_size) {
  11838. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  11839. if (buf_size > 0) {
  11840. buf[0] = '\0';
  11841. }
  11842. return -1;
  11843. }
  11844. auto it = model->gguf_kv.begin();
  11845. std::advance(it, i);
  11846. return snprintf(buf, buf_size, "%s", it->first.c_str());
  11847. }
  11848. int32_t llama_model_meta_val_str_by_index(const struct llama_model * model, int32_t i, char * buf, size_t buf_size) {
  11849. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  11850. if (buf_size > 0) {
  11851. buf[0] = '\0';
  11852. }
  11853. return -1;
  11854. }
  11855. auto it = model->gguf_kv.begin();
  11856. std::advance(it, i);
  11857. return snprintf(buf, buf_size, "%s", it->second.c_str());
  11858. }
  11859. int32_t llama_model_desc(const struct llama_model * model, char * buf, size_t buf_size) {
  11860. return snprintf(buf, buf_size, "%s %s %s",
  11861. llama_model_arch_name(model->arch),
  11862. llama_model_type_name(model->type),
  11863. llama_model_ftype_name(model->ftype).c_str());
  11864. }
  11865. uint64_t llama_model_size(const struct llama_model * model) {
  11866. uint64_t size = 0;
  11867. for (const auto & it : model->tensors_by_name) {
  11868. size += ggml_nbytes(it.second);
  11869. }
  11870. return size;
  11871. }
  11872. uint64_t llama_model_n_params(const struct llama_model * model) {
  11873. uint64_t nparams = 0;
  11874. for (const auto & it : model->tensors_by_name) {
  11875. nparams += ggml_nelements(it.second);
  11876. }
  11877. return nparams;
  11878. }
  11879. struct ggml_tensor * llama_get_model_tensor(struct llama_model * model, const char * name) {
  11880. auto it = std::find_if(model->tensors_by_name.begin(), model->tensors_by_name.end(),
  11881. [name](const std::pair<std::string, struct ggml_tensor *> & it) {
  11882. return it.first == name;
  11883. });
  11884. if (it == model->tensors_by_name.end()) {
  11885. return nullptr;
  11886. }
  11887. return it->second;
  11888. }
  11889. uint32_t llama_model_quantize(
  11890. const char * fname_inp,
  11891. const char * fname_out,
  11892. const llama_model_quantize_params * params) {
  11893. try {
  11894. llama_model_quantize_internal(fname_inp, fname_out, params);
  11895. return 0;
  11896. } catch (const std::exception & err) {
  11897. LLAMA_LOG_ERROR("%s: failed to quantize: %s\n", __func__, err.what());
  11898. return 1;
  11899. }
  11900. }
  11901. 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) {
  11902. try {
  11903. return llama_apply_lora_from_file_internal(*model, path_lora, scale, path_base_model, n_threads);
  11904. } catch (const std::exception & err) {
  11905. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  11906. return 1;
  11907. }
  11908. }
  11909. static bool llama_control_vector_init(struct llama_control_vector & cvec, const llama_model & model) {
  11910. GGML_ASSERT(cvec.tensors.empty());
  11911. GGML_ASSERT(cvec.ctxs.empty());
  11912. GGML_ASSERT(cvec.bufs.empty());
  11913. // count layer buffer types
  11914. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  11915. for (int64_t i = 0; i < model.hparams.n_layer; i++) {
  11916. buft_layer_count[model.buft_layer[i].buft]++;
  11917. }
  11918. // allocate contexts
  11919. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  11920. for (auto & it : buft_layer_count) {
  11921. int n_layers = it.second;
  11922. struct ggml_init_params params = {
  11923. /*.mem_size =*/ n_layers * ggml_tensor_overhead(),
  11924. /*.mem_buffer =*/ NULL,
  11925. /*.no_alloc =*/ true,
  11926. };
  11927. ggml_context * ctx = ggml_init(params);
  11928. if (!ctx) {
  11929. LLAMA_LOG_ERROR("%s: failed to allocate context for control vector\n", __func__);
  11930. return 1;
  11931. }
  11932. ctx_map[it.first] = ctx;
  11933. }
  11934. // make tensors
  11935. cvec.tensors.push_back(nullptr); // there's never a tensor for layer 0
  11936. for (size_t il = 1; il < model.hparams.n_layer; il++) {
  11937. struct ggml_context * ctx = ctx_map.at(model.buft_layer[il].buft);
  11938. ggml_tensor * tensor = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, model.hparams.n_embd);
  11939. cvec.tensors.push_back(tensor);
  11940. }
  11941. // allocate tensors / buffers and zero
  11942. for (auto it : ctx_map) {
  11943. ggml_backend_buffer_type_t buft = it.first;
  11944. ggml_context * ctx = it.second;
  11945. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  11946. if (!buf) {
  11947. LLAMA_LOG_ERROR("%s: failed to allocate buffer for control vector\n", __func__);
  11948. return false;
  11949. }
  11950. ggml_backend_buffer_clear(buf, 0);
  11951. cvec.ctxs.push_back(ctx);
  11952. cvec.bufs.push_back(buf);
  11953. }
  11954. return true;
  11955. }
  11956. 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) {
  11957. const llama_model & model = lctx->model;
  11958. llama_control_vector & cvec = lctx->cvec;
  11959. if (data == nullptr) {
  11960. // disable the current control vector (but leave allocated for later)
  11961. cvec.layer_start = -1;
  11962. cvec.layer_end = -1;
  11963. return 0;
  11964. }
  11965. if (n_embd != (int) model.hparams.n_embd) {
  11966. LLAMA_LOG_ERROR("%s: control vector n_embd does not match model\n", __func__);
  11967. return 1;
  11968. }
  11969. if (cvec.tensors.empty()) {
  11970. if (!llama_control_vector_init(cvec, model)) {
  11971. return 1;
  11972. }
  11973. }
  11974. cvec.layer_start = il_start;
  11975. cvec.layer_end = il_end;
  11976. for (size_t il = 1; il < model.hparams.n_layer; il++) {
  11977. assert(cvec.tensors[il] != nullptr);
  11978. const size_t off = n_embd * (il - 1); // buffer doesn't have data for layer 0, since it's never present
  11979. if (off + n_embd <= len) {
  11980. ggml_backend_tensor_set(cvec.tensors[il], data + off, 0, n_embd * ggml_element_size(cvec.tensors[il]));
  11981. }
  11982. }
  11983. return 0;
  11984. }
  11985. struct llama_kv_cache_view llama_kv_cache_view_init(const struct llama_context * ctx, int32_t n_seq_max) {
  11986. struct llama_kv_cache_view result = {
  11987. /*.n_cells = */ 0,
  11988. /*.n_seq_max = */ n_seq_max,
  11989. /*.token_count = */ 0,
  11990. /*.used_cells = */ llama_get_kv_cache_used_cells(ctx),
  11991. /*.max_contiguous = */ 0,
  11992. /*.max_contiguous_idx = */ -1,
  11993. /*.cells = */ nullptr,
  11994. /*.cells_sequences = */ nullptr,
  11995. };
  11996. return result;
  11997. }
  11998. void llama_kv_cache_view_free(struct llama_kv_cache_view * view) {
  11999. if (view->cells != nullptr) {
  12000. free(view->cells);
  12001. view->cells = nullptr;
  12002. }
  12003. if (view->cells_sequences != nullptr) {
  12004. free(view->cells_sequences);
  12005. view->cells_sequences = nullptr;
  12006. }
  12007. }
  12008. void llama_kv_cache_view_update(const struct llama_context * ctx, struct llama_kv_cache_view * view) {
  12009. if (uint32_t(view->n_cells) < ctx->kv_self.size || view->cells == nullptr) {
  12010. view->n_cells = int32_t(ctx->kv_self.size);
  12011. void * p = realloc(view->cells, sizeof(struct llama_kv_cache_view_cell) * view->n_cells);
  12012. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells");
  12013. view->cells = (struct llama_kv_cache_view_cell *)p;
  12014. p = realloc(view->cells_sequences, sizeof(llama_seq_id) * view->n_seq_max * view->n_cells);
  12015. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells sequences");
  12016. view->cells_sequences = (llama_seq_id *)p;
  12017. }
  12018. const std::vector<llama_kv_cell> & kv_cells = ctx->kv_self.cells;
  12019. llama_kv_cache_view_cell * c_curr = view->cells;
  12020. llama_seq_id * cs_curr = view->cells_sequences;
  12021. int32_t used_cells = 0;
  12022. int32_t token_count = 0;
  12023. int32_t curr_contig_idx = -1;
  12024. uint32_t max_contig = 0;
  12025. int32_t max_contig_idx = -1;
  12026. for (int32_t i = 0; i < int32_t(ctx->kv_self.size); i++, c_curr++, cs_curr += view->n_seq_max) {
  12027. const size_t curr_size = kv_cells[i].seq_id.size();
  12028. token_count += curr_size;
  12029. c_curr->pos = kv_cells[i].pos + kv_cells[i].delta;
  12030. if (curr_size > 0) {
  12031. if (curr_contig_idx >= 0 && uint32_t(i - curr_contig_idx) > max_contig) {
  12032. max_contig = i - curr_contig_idx;
  12033. max_contig_idx = curr_contig_idx;
  12034. }
  12035. curr_contig_idx = -1;
  12036. } else if (curr_contig_idx < 0) {
  12037. curr_contig_idx = i;
  12038. }
  12039. int seq_idx = 0;
  12040. for (const llama_seq_id it : kv_cells[i].seq_id) {
  12041. if (seq_idx >= view->n_seq_max) {
  12042. break;
  12043. }
  12044. cs_curr[seq_idx] = it;
  12045. seq_idx++;
  12046. }
  12047. if (seq_idx != 0) {
  12048. used_cells++;
  12049. }
  12050. for (; seq_idx < view->n_seq_max; seq_idx++) {
  12051. cs_curr[seq_idx] = -1;
  12052. }
  12053. }
  12054. if (curr_contig_idx >= 0 && kv_cells.size() - curr_contig_idx > max_contig) {
  12055. max_contig_idx = curr_contig_idx;
  12056. max_contig = kv_cells.size() - curr_contig_idx;
  12057. }
  12058. view->max_contiguous = max_contig;
  12059. view->max_contiguous_idx = max_contig_idx;
  12060. view->token_count = token_count;
  12061. view->used_cells = used_cells;
  12062. if (uint32_t(used_cells) != ctx->kv_self.used) {
  12063. LLAMA_LOG_ERROR("%s: used cells mismatch. kv_cache says %d but we calculated %d\n",
  12064. __func__, ctx->kv_self.used, used_cells);
  12065. }
  12066. }
  12067. int32_t llama_get_kv_cache_token_count(const struct llama_context * ctx) {
  12068. int result = 0;
  12069. for (uint32_t i = 0; i < ctx->kv_self.size; i++) {
  12070. result += ctx->kv_self.cells[i].seq_id.size();
  12071. }
  12072. return result;
  12073. }
  12074. int32_t llama_get_kv_cache_used_cells(const struct llama_context * ctx) {
  12075. return ctx->kv_self.used;
  12076. }
  12077. void llama_kv_cache_clear(struct llama_context * ctx) {
  12078. llama_kv_cache_clear(ctx->kv_self);
  12079. }
  12080. bool llama_kv_cache_seq_rm(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
  12081. return llama_kv_cache_seq_rm(ctx->kv_self, seq_id, p0, p1);
  12082. }
  12083. 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) {
  12084. if (seq_id_src == seq_id_dst) {
  12085. return;
  12086. }
  12087. llama_kv_cache_seq_cp(ctx->kv_self, seq_id_src, seq_id_dst, p0, p1);
  12088. }
  12089. void llama_kv_cache_seq_keep(struct llama_context * ctx, llama_seq_id seq_id) {
  12090. llama_kv_cache_seq_keep(ctx->kv_self, seq_id);
  12091. }
  12092. void llama_kv_cache_seq_add(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos delta) {
  12093. if (delta == 0) {
  12094. return;
  12095. }
  12096. llama_kv_cache_seq_add(ctx->kv_self, seq_id, p0, p1, delta);
  12097. }
  12098. void llama_kv_cache_seq_div(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) {
  12099. if (d == 1) {
  12100. return;
  12101. }
  12102. llama_kv_cache_seq_div(ctx->kv_self, seq_id, p0, p1, d);
  12103. }
  12104. llama_pos llama_kv_cache_seq_pos_max(struct llama_context * ctx, llama_seq_id seq_id) {
  12105. return llama_kv_cache_seq_pos_max(ctx->kv_self, seq_id);
  12106. }
  12107. void llama_kv_cache_defrag(struct llama_context * ctx) {
  12108. llama_kv_cache_defrag(ctx->kv_self);
  12109. }
  12110. void llama_kv_cache_update(struct llama_context * ctx) {
  12111. llama_kv_cache_update_internal(*ctx);
  12112. }
  12113. // Returns the *maximum* size of the state
  12114. size_t llama_get_state_size(const struct llama_context * ctx) {
  12115. const auto & cparams = ctx->cparams;
  12116. const auto & hparams = ctx->model.hparams;
  12117. // we don't know size of rng until we actually serialize it. so reserve more than enough memory for its serialized state.
  12118. // for reference, std::mt19937(1337) serializes to 6701 bytes.
  12119. const size_t s_rng_size = sizeof(size_t);
  12120. const size_t s_rng = LLAMA_MAX_RNG_STATE;
  12121. const size_t s_n_outputs = sizeof(size_t);
  12122. // assume worst case for outputs although only currently set ones are serialized
  12123. const size_t s_output_pos = ctx->cparams.n_batch * sizeof(int32_t);
  12124. const size_t s_logits_size = sizeof(size_t);
  12125. const size_t s_logits = ctx->logits_size ? cparams.n_batch * hparams.n_vocab * sizeof(float) : 0;
  12126. const size_t s_embedding_size = sizeof(size_t);
  12127. const size_t s_embedding = ctx->embd_size ? cparams.n_batch * hparams.n_embd * sizeof(float) : 0;
  12128. const size_t s_kv_buf_size = sizeof(size_t);
  12129. const size_t s_kv_head = sizeof(uint32_t);
  12130. const size_t s_kv_size = sizeof(uint32_t);
  12131. const size_t s_kv_used = sizeof(uint32_t);
  12132. const size_t s_kv = ctx->kv_self.total_size();
  12133. const size_t s_kv_cell = sizeof(llama_pos) + sizeof(size_t) + cparams.n_seq_max*sizeof(llama_seq_id);
  12134. const size_t s_kv_cells = ctx->kv_self.size * s_kv_cell;
  12135. const size_t s_total = (
  12136. + s_rng_size
  12137. + s_rng
  12138. + s_n_outputs
  12139. + s_output_pos
  12140. + s_logits_size
  12141. + s_logits
  12142. + s_embedding_size
  12143. + s_embedding
  12144. + s_kv_buf_size
  12145. + s_kv_head
  12146. + s_kv_size
  12147. + s_kv_used
  12148. + s_kv
  12149. + s_kv_cells
  12150. );
  12151. return s_total;
  12152. }
  12153. // llama_context_data
  12154. struct llama_data_context {
  12155. virtual void write(const void * src, size_t size) = 0;
  12156. virtual size_t get_size_written() = 0;
  12157. virtual ~llama_data_context() = default;
  12158. };
  12159. struct llama_data_buffer_context : llama_data_context {
  12160. uint8_t * ptr;
  12161. size_t size_written = 0;
  12162. llama_data_buffer_context(uint8_t * p) : ptr(p) {}
  12163. void write(const void * src, size_t size) override {
  12164. memcpy(ptr, src, size);
  12165. ptr += size;
  12166. size_written += size;
  12167. }
  12168. size_t get_size_written() override {
  12169. return size_written;
  12170. }
  12171. };
  12172. struct llama_data_file_context : llama_data_context {
  12173. llama_file * file;
  12174. size_t size_written = 0;
  12175. llama_data_file_context(llama_file * f) : file(f) {}
  12176. void write(const void * src, size_t size) override {
  12177. file->write_raw(src, size);
  12178. size_written += size;
  12179. }
  12180. size_t get_size_written() override {
  12181. return size_written;
  12182. }
  12183. };
  12184. /** copy state data into either a buffer or file depending on the passed in context
  12185. *
  12186. * file context:
  12187. * llama_file file("/path", "wb");
  12188. * llama_data_file_context data_ctx(&file);
  12189. * llama_copy_state_data(ctx, &data_ctx);
  12190. *
  12191. * buffer context:
  12192. * std::vector<uint8_t> buf(max_size, 0);
  12193. * llama_data_buffer_context data_ctx(&buf.data());
  12194. * llama_copy_state_data(ctx, &data_ctx);
  12195. *
  12196. */
  12197. static void llama_copy_state_data_internal(struct llama_context * ctx, llama_data_context * data_ctx) {
  12198. // copy rng
  12199. {
  12200. std::ostringstream rng_ss;
  12201. rng_ss << ctx->rng;
  12202. const std::string & rng_str = rng_ss.str();
  12203. const size_t rng_size = rng_str.size();
  12204. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  12205. data_ctx->write(&rng_size, sizeof(rng_size));
  12206. data_ctx->write(rng_str.data(), rng_size);
  12207. }
  12208. // copy outputs
  12209. {
  12210. // Can't use ctx->n_outputs because it's not for the
  12211. // entire last batch when n_ubatch is smaller than n_batch
  12212. size_t n_outputs = 0;
  12213. // copy output ids
  12214. {
  12215. std::vector<int32_t> output_pos;
  12216. const size_t n_batch = ctx->cparams.n_batch;
  12217. const auto & output_ids = ctx->output_ids;
  12218. output_pos.resize(ctx->output_size);
  12219. // build a more compact representation of the output ids
  12220. for (size_t i = 0; i < n_batch; ++i) {
  12221. // map an output id to a position in the batch
  12222. int32_t pos = output_ids[i];
  12223. if (pos >= 0) {
  12224. if ((size_t) pos >= n_outputs) {
  12225. n_outputs = pos + 1;
  12226. }
  12227. GGML_ASSERT((size_t) pos < ctx->output_size);
  12228. output_pos[pos] = i;
  12229. }
  12230. }
  12231. data_ctx->write(&n_outputs, sizeof(n_outputs));
  12232. if (n_outputs) {
  12233. data_ctx->write(output_pos.data(), n_outputs * sizeof(int32_t));
  12234. }
  12235. }
  12236. // copy logits
  12237. {
  12238. const size_t logits_size = std::min(ctx->logits_size, n_outputs * ctx->model.hparams.n_vocab);
  12239. data_ctx->write(&logits_size, sizeof(logits_size));
  12240. if (logits_size) {
  12241. data_ctx->write(ctx->logits, logits_size * sizeof(float));
  12242. }
  12243. }
  12244. // copy embeddings
  12245. {
  12246. const size_t embeddings_size = std::min(ctx->embd_size, n_outputs * ctx->model.hparams.n_embd);
  12247. data_ctx->write(&embeddings_size, sizeof(embeddings_size));
  12248. if (embeddings_size) {
  12249. data_ctx->write(ctx->embd, embeddings_size * sizeof(float));
  12250. }
  12251. }
  12252. }
  12253. // copy kv cache
  12254. {
  12255. const auto & kv_self = ctx->kv_self;
  12256. const auto & hparams = ctx->model.hparams;
  12257. const uint32_t n_layer = hparams.n_layer;
  12258. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  12259. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  12260. // NOTE: kv_size and kv_buf_size are mostly used for sanity checks
  12261. const uint32_t kv_head = llama_kv_cache_cell_max(kv_self);
  12262. const uint32_t kv_size = kv_self.size;
  12263. const size_t kv_buf_size = kv_self.total_size() / (kv_size ? kv_size : 1) * kv_head;
  12264. const uint32_t kv_used = kv_self.used;
  12265. data_ctx->write(&kv_buf_size, sizeof(kv_buf_size));
  12266. data_ctx->write(&kv_head, sizeof(kv_head));
  12267. data_ctx->write(&kv_size, sizeof(kv_size));
  12268. data_ctx->write(&kv_used, sizeof(kv_used));
  12269. if (kv_buf_size) {
  12270. const size_t pre_kv_buf_size = data_ctx->get_size_written();
  12271. std::vector<uint8_t> tmp_buf;
  12272. for (int il = 0; il < (int) n_layer; ++il) {
  12273. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_head);
  12274. tmp_buf.resize(k_size);
  12275. ggml_backend_tensor_get(kv_self.k_l[il], tmp_buf.data(), 0, tmp_buf.size());
  12276. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  12277. if (kv_self.recurrent) {
  12278. // v is contiguous for recurrent models
  12279. // TODO: use other tensors for state models than k and v
  12280. const size_t v_size = ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa*kv_head);
  12281. tmp_buf.resize(v_size);
  12282. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), 0, tmp_buf.size());
  12283. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  12284. continue;
  12285. }
  12286. // v is not contiguous, copy row by row
  12287. const size_t v_row_size = ggml_row_size(kv_self.v_l[il]->type, kv_head);
  12288. const size_t v_row_stride = ggml_row_size(kv_self.v_l[il]->type, kv_size);
  12289. tmp_buf.resize(v_row_size);
  12290. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  12291. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), ir*v_row_stride, tmp_buf.size());
  12292. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  12293. }
  12294. }
  12295. GGML_ASSERT(kv_buf_size == data_ctx->get_size_written() - pre_kv_buf_size);
  12296. }
  12297. for (uint32_t i = 0; i < kv_head; ++i) {
  12298. const auto & cell = kv_self.cells[i];
  12299. const llama_pos pos = cell.pos;
  12300. const size_t seq_id_size = cell.seq_id.size();
  12301. data_ctx->write(&pos, sizeof(pos));
  12302. data_ctx->write(&seq_id_size, sizeof(seq_id_size));
  12303. for (auto seq_id : cell.seq_id) {
  12304. data_ctx->write(&seq_id, sizeof(seq_id));
  12305. }
  12306. }
  12307. }
  12308. }
  12309. size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dst) {
  12310. llama_data_buffer_context data_ctx(dst);
  12311. llama_copy_state_data_internal(ctx, &data_ctx);
  12312. return data_ctx.get_size_written();
  12313. }
  12314. // Sets the state reading from the specified source address
  12315. size_t llama_set_state_data(struct llama_context * ctx, const uint8_t * src) {
  12316. const uint8_t * inp = src;
  12317. // set rng
  12318. {
  12319. size_t rng_size;
  12320. memcpy(&rng_size, inp, sizeof(rng_size)); inp += sizeof(rng_size);
  12321. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  12322. std::string rng_str((const char *)inp, rng_size); inp += rng_size;
  12323. std::istringstream rng_ss(rng_str);
  12324. rng_ss >> ctx->rng;
  12325. GGML_ASSERT(!rng_ss.fail());
  12326. }
  12327. // set output ids
  12328. {
  12329. size_t n_outputs;
  12330. std::vector<int32_t> output_pos;
  12331. memcpy(&n_outputs, inp, sizeof(n_outputs)); inp += sizeof(n_outputs);
  12332. GGML_ASSERT(n_outputs <= llama_output_reserve(*ctx, n_outputs));
  12333. if (n_outputs) {
  12334. output_pos.resize(n_outputs);
  12335. memcpy(output_pos.data(), inp, n_outputs * sizeof(int32_t));
  12336. inp += n_outputs * sizeof(int32_t);
  12337. for (int32_t i = 0; i < (int32_t) output_pos.size(); ++i) {
  12338. int32_t id = output_pos[i];
  12339. GGML_ASSERT((uint32_t) id < ctx->cparams.n_batch);
  12340. ctx->output_ids[id] = i;
  12341. }
  12342. }
  12343. }
  12344. // set logits
  12345. {
  12346. size_t logits_size;
  12347. memcpy(&logits_size, inp, sizeof(logits_size)); inp += sizeof(logits_size);
  12348. GGML_ASSERT(ctx->logits_size >= logits_size);
  12349. if (logits_size) {
  12350. memcpy(ctx->logits, inp, logits_size * sizeof(float));
  12351. inp += logits_size * sizeof(float);
  12352. }
  12353. }
  12354. // set embeddings
  12355. {
  12356. size_t embeddings_size;
  12357. memcpy(&embeddings_size, inp, sizeof(embeddings_size)); inp += sizeof(embeddings_size);
  12358. GGML_ASSERT(ctx->embd_size >= embeddings_size);
  12359. if (embeddings_size) {
  12360. memcpy(ctx->embd, inp, embeddings_size * sizeof(float));
  12361. inp += embeddings_size * sizeof(float);
  12362. }
  12363. }
  12364. // set kv cache
  12365. {
  12366. const auto & kv_self = ctx->kv_self;
  12367. const auto & hparams = ctx->model.hparams;
  12368. const uint32_t n_layer = hparams.n_layer;
  12369. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  12370. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  12371. size_t kv_buf_size;
  12372. uint32_t kv_head;
  12373. uint32_t kv_size;
  12374. uint32_t kv_used;
  12375. memcpy(&kv_buf_size, inp, sizeof(kv_buf_size)); inp += sizeof(kv_buf_size);
  12376. memcpy(&kv_head, inp, sizeof(kv_head)); inp += sizeof(kv_head);
  12377. memcpy(&kv_size, inp, sizeof(kv_size)); inp += sizeof(kv_size);
  12378. memcpy(&kv_used, inp, sizeof(kv_used)); inp += sizeof(kv_used);
  12379. if (kv_self.size != kv_size) {
  12380. // the KV cache needs to be big enough to load all the KV cells from the saved state
  12381. GGML_ASSERT(kv_self.size >= kv_head);
  12382. 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",
  12383. __func__, kv_head, kv_size, kv_self.size);
  12384. }
  12385. if (kv_buf_size) {
  12386. const size_t pre_kv_buf_size = inp - src;
  12387. GGML_ASSERT(kv_self.total_size() >= kv_buf_size);
  12388. for (int il = 0; il < (int) n_layer; ++il) {
  12389. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_head);
  12390. ggml_backend_tensor_set(kv_self.k_l[il], inp, 0, k_size);
  12391. inp += k_size;
  12392. if (kv_self.recurrent) {
  12393. // v is contiguous for recurrent models
  12394. // TODO: use other tensors for state models than k and v
  12395. const size_t v_size = ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa*kv_head);
  12396. ggml_backend_tensor_set(kv_self.v_l[il], inp, 0, v_size);
  12397. inp += v_size;
  12398. continue;
  12399. }
  12400. // v is not contiguous, copy row by row
  12401. const size_t v_row_size = ggml_row_size(kv_self.v_l[il]->type, kv_head);
  12402. const size_t v_row_stride = ggml_row_size(kv_self.v_l[il]->type, kv_self.size);
  12403. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  12404. ggml_backend_tensor_set(kv_self.v_l[il], inp, ir*v_row_stride, v_row_size);
  12405. inp += v_row_size;
  12406. }
  12407. }
  12408. GGML_ASSERT(kv_buf_size == inp - src - pre_kv_buf_size);
  12409. }
  12410. llama_kv_cache_clear(ctx);
  12411. ctx->kv_self.head = kv_head;
  12412. ctx->kv_self.used = kv_used;
  12413. for (uint32_t i = 0; i < kv_head; ++i) {
  12414. llama_pos pos;
  12415. size_t seq_id_size;
  12416. memcpy(&pos, inp, sizeof(pos)); inp += sizeof(pos);
  12417. memcpy(&seq_id_size, inp, sizeof(seq_id_size)); inp += sizeof(seq_id_size);
  12418. ctx->kv_self.cells[i].pos = pos;
  12419. llama_seq_id seq_id;
  12420. for (size_t j = 0; j < seq_id_size; ++j) {
  12421. memcpy(&seq_id, inp, sizeof(seq_id)); inp += sizeof(seq_id);
  12422. ctx->kv_self.cells[i].seq_id.insert(seq_id);
  12423. }
  12424. }
  12425. }
  12426. const size_t nread = inp - src;
  12427. const size_t max_size = llama_get_state_size(ctx);
  12428. GGML_ASSERT(nread <= max_size);
  12429. return nread;
  12430. }
  12431. 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) {
  12432. llama_file file(path_session, "rb");
  12433. // sanity checks
  12434. {
  12435. const uint32_t magic = file.read_u32();
  12436. const uint32_t version = file.read_u32();
  12437. if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
  12438. LLAMA_LOG_ERROR("%s : unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
  12439. return false;
  12440. }
  12441. llama_hparams session_hparams;
  12442. file.read_raw(&session_hparams, sizeof(llama_hparams));
  12443. if (session_hparams != ctx->model.hparams) {
  12444. LLAMA_LOG_INFO("%s : model hparams didn't match from session file!\n", __func__);
  12445. return false;
  12446. }
  12447. }
  12448. // load the prompt
  12449. {
  12450. const uint32_t n_token_count = file.read_u32();
  12451. if (n_token_count > n_token_capacity) {
  12452. LLAMA_LOG_ERROR("%s : token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  12453. return false;
  12454. }
  12455. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  12456. *n_token_count_out = n_token_count;
  12457. }
  12458. // restore the context state
  12459. {
  12460. const size_t n_state_size_cur = file.size - file.tell();
  12461. const size_t n_state_size_max = llama_get_state_size(ctx);
  12462. if (n_state_size_cur > n_state_size_max) {
  12463. 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);
  12464. return false;
  12465. }
  12466. std::vector<uint8_t> state_data(n_state_size_max);
  12467. file.read_raw(state_data.data(), n_state_size_cur);
  12468. llama_set_state_data(ctx, state_data.data());
  12469. }
  12470. return true;
  12471. }
  12472. 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) {
  12473. try {
  12474. return llama_load_session_file_internal(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  12475. } catch (const std::exception & err) {
  12476. LLAMA_LOG_ERROR("error loading session file: %s\n", err.what());
  12477. return false;
  12478. }
  12479. }
  12480. bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  12481. llama_file file(path_session, "wb");
  12482. file.write_u32(LLAMA_SESSION_MAGIC);
  12483. file.write_u32(LLAMA_SESSION_VERSION);
  12484. file.write_raw(&ctx->model.hparams, sizeof(llama_hparams));
  12485. // save the prompt
  12486. file.write_u32((uint32_t) n_token_count);
  12487. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  12488. // save the context state using stream saving
  12489. llama_data_file_context data_ctx(&file);
  12490. llama_copy_state_data_internal(ctx, &data_ctx);
  12491. return true;
  12492. }
  12493. void llama_set_n_threads(struct llama_context * ctx, uint32_t n_threads, uint32_t n_threads_batch) {
  12494. ctx->cparams.n_threads = n_threads;
  12495. ctx->cparams.n_threads_batch = n_threads_batch;
  12496. }
  12497. void llama_set_abort_callback(struct llama_context * ctx, bool (*abort_callback)(void * data), void * abort_callback_data) {
  12498. ctx->abort_callback = abort_callback;
  12499. ctx->abort_callback_data = abort_callback_data;
  12500. }
  12501. void llama_set_causal_attn(struct llama_context * ctx, bool causal_attn) {
  12502. ctx->cparams.causal_attn = causal_attn;
  12503. }
  12504. struct llama_batch llama_batch_get_one(
  12505. llama_token * tokens,
  12506. int32_t n_tokens,
  12507. llama_pos pos_0,
  12508. llama_seq_id seq_id) {
  12509. return {
  12510. /*n_tokens =*/ n_tokens,
  12511. /*tokens =*/ tokens,
  12512. /*embd =*/ nullptr,
  12513. /*pos =*/ nullptr,
  12514. /*n_seq_id =*/ nullptr,
  12515. /*seq_id =*/ nullptr,
  12516. /*logits =*/ nullptr,
  12517. /*all_pos_0 =*/ pos_0,
  12518. /*all_pos_1 =*/ 1,
  12519. /*all_seq_id =*/ seq_id,
  12520. };
  12521. }
  12522. struct llama_batch llama_batch_init(int32_t n_tokens_alloc, int32_t embd, int32_t n_seq_max) {
  12523. llama_batch batch = { 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, 0, 0, 0, };
  12524. if (embd) {
  12525. batch.embd = (float *) malloc(sizeof(float) * n_tokens_alloc * embd);
  12526. } else {
  12527. batch.token = (llama_token *) malloc(sizeof(llama_token) * n_tokens_alloc);
  12528. }
  12529. batch.pos = (llama_pos *) malloc(sizeof(llama_pos) * n_tokens_alloc);
  12530. batch.n_seq_id = (int32_t *) malloc(sizeof(int32_t) * n_tokens_alloc);
  12531. batch.seq_id = (llama_seq_id **) malloc(sizeof(llama_seq_id *) * (n_tokens_alloc + 1));
  12532. for (int i = 0; i < n_tokens_alloc; ++i) {
  12533. batch.seq_id[i] = (llama_seq_id *) malloc(sizeof(llama_seq_id) * n_seq_max);
  12534. }
  12535. batch.seq_id[n_tokens_alloc] = nullptr;
  12536. batch.logits = (int8_t *) malloc(sizeof(int8_t) * n_tokens_alloc);
  12537. return batch;
  12538. }
  12539. void llama_batch_free(struct llama_batch batch) {
  12540. if (batch.token) free(batch.token);
  12541. if (batch.embd) free(batch.embd);
  12542. if (batch.pos) free(batch.pos);
  12543. if (batch.n_seq_id) free(batch.n_seq_id);
  12544. if (batch.seq_id) {
  12545. for (int i = 0; batch.seq_id[i] != nullptr; ++i) {
  12546. free(batch.seq_id[i]);
  12547. }
  12548. free(batch.seq_id);
  12549. }
  12550. if (batch.logits) free(batch.logits);
  12551. }
  12552. int32_t llama_decode(
  12553. struct llama_context * ctx,
  12554. struct llama_batch batch) {
  12555. const int ret = llama_decode_internal(*ctx, batch);
  12556. if (ret < 0) {
  12557. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  12558. }
  12559. return ret;
  12560. }
  12561. void llama_synchronize(struct llama_context * ctx) {
  12562. ggml_backend_sched_synchronize(ctx->sched);
  12563. // FIXME: if multiple single tokens are evaluated without a synchronization,
  12564. // the stats will be added to the prompt evaluation stats
  12565. // this should only happen when using batch size 1 to evaluate a batch
  12566. // add the evaluation to the stats
  12567. if (ctx->n_queued_tokens == 1) {
  12568. ctx->t_eval_us += ggml_time_us() - ctx->t_compute_start_us;
  12569. ctx->n_eval++;
  12570. } else if (ctx->n_queued_tokens > 1) {
  12571. ctx->t_p_eval_us += ggml_time_us() - ctx->t_compute_start_us;
  12572. ctx->n_p_eval += ctx->n_queued_tokens;
  12573. }
  12574. // get a more accurate load time, upon first eval
  12575. if (ctx->n_queued_tokens > 0 && !ctx->has_evaluated_once) {
  12576. ctx->t_load_us = ggml_time_us() - ctx->t_start_us;
  12577. ctx->has_evaluated_once = true;
  12578. }
  12579. ctx->n_queued_tokens = 0;
  12580. ctx->t_compute_start_us = 0;
  12581. }
  12582. float * llama_get_logits(struct llama_context * ctx) {
  12583. llama_synchronize(ctx);
  12584. return ctx->logits;
  12585. }
  12586. float * llama_get_logits_ith(struct llama_context * ctx, int32_t i) {
  12587. llama_synchronize(ctx);
  12588. try {
  12589. if (ctx->logits == nullptr) {
  12590. throw std::runtime_error("no logits");
  12591. }
  12592. if ((size_t) i >= ctx->output_ids.size()) {
  12593. throw std::runtime_error(format("out of range [0, %lu)", ctx->output_ids.size()));
  12594. }
  12595. const int32_t j = ctx->output_ids[i];
  12596. if (j < 0) {
  12597. throw std::runtime_error(format("batch.logits[%d] != true", i));
  12598. }
  12599. if ((size_t) j >= ctx->output_size) {
  12600. // This should not happen
  12601. throw std::runtime_error(format("corrupt output buffer (j=%d, output_size=%lu)", j, ctx->output_size));
  12602. }
  12603. return ctx->logits + j*ctx->model.hparams.n_vocab;
  12604. } catch (const std::exception & err) {
  12605. LLAMA_LOG_ERROR("%s: invalid logits id %d, reason: %s\n", __func__, i, err.what());
  12606. #ifndef NDEBUG
  12607. GGML_ASSERT(false);
  12608. #endif
  12609. return nullptr;
  12610. }
  12611. }
  12612. float * llama_get_embeddings(struct llama_context * ctx) {
  12613. llama_synchronize(ctx);
  12614. return ctx->embd;
  12615. }
  12616. float * llama_get_embeddings_ith(struct llama_context * ctx, int32_t i) {
  12617. llama_synchronize(ctx);
  12618. try {
  12619. if (ctx->embd == nullptr) {
  12620. throw std::runtime_error("no embeddings");
  12621. }
  12622. if ((size_t) i >= ctx->output_ids.size()) {
  12623. throw std::runtime_error(format("out of range [0, %lu)", ctx->output_ids.size()));
  12624. }
  12625. const int32_t j = ctx->output_ids[i];
  12626. if (j < 0) {
  12627. throw std::runtime_error(format("batch.logits[%d] != true", i));
  12628. }
  12629. if ((size_t) j >= ctx->output_size) {
  12630. // This should not happen
  12631. throw std::runtime_error(format("corrupt output buffer (j=%d, output_size=%lu)", j, ctx->output_size));
  12632. }
  12633. return ctx->embd + j*ctx->model.hparams.n_embd;
  12634. } catch (const std::exception & err) {
  12635. LLAMA_LOG_ERROR("%s: invalid embeddings id %d, reason: %s\n", __func__, i, err.what());
  12636. #ifndef NDEBUG
  12637. GGML_ASSERT(false);
  12638. #endif
  12639. return nullptr;
  12640. }
  12641. }
  12642. float * llama_get_embeddings_seq(struct llama_context * ctx, llama_seq_id seq_id) {
  12643. llama_synchronize(ctx);
  12644. auto it = ctx->embd_seq.find(seq_id);
  12645. if (it == ctx->embd_seq.end()) {
  12646. return nullptr;
  12647. }
  12648. return it->second.data();
  12649. }
  12650. const char * llama_token_get_text(const struct llama_model * model, llama_token token) {
  12651. GGML_ASSERT(model->vocab.type != LLAMA_VOCAB_TYPE_NONE);
  12652. return model->vocab.id_to_token[token].text.c_str();
  12653. }
  12654. float llama_token_get_score(const struct llama_model * model, llama_token token) {
  12655. GGML_ASSERT(model->vocab.type != LLAMA_VOCAB_TYPE_NONE);
  12656. return model->vocab.id_to_token[token].score;
  12657. }
  12658. llama_token_type llama_token_get_type(const struct llama_model * model, llama_token token) {
  12659. GGML_ASSERT(model->vocab.type != LLAMA_VOCAB_TYPE_NONE);
  12660. return model->vocab.id_to_token[token].type;
  12661. }
  12662. llama_token llama_token_bos(const struct llama_model * model) {
  12663. return model->vocab.special_bos_id;
  12664. }
  12665. llama_token llama_token_eos(const struct llama_model * model) {
  12666. return model->vocab.special_eos_id;
  12667. }
  12668. llama_token llama_token_nl(const struct llama_model * model) {
  12669. return model->vocab.linefeed_id;
  12670. }
  12671. int32_t llama_add_bos_token(const struct llama_model * model) {
  12672. return model->vocab.special_add_bos;
  12673. }
  12674. int32_t llama_add_eos_token(const struct llama_model * model) {
  12675. return model->vocab.special_add_eos;
  12676. }
  12677. llama_token llama_token_prefix(const struct llama_model * model) {
  12678. return model->vocab.special_prefix_id;
  12679. }
  12680. llama_token llama_token_middle(const struct llama_model * model) {
  12681. return model->vocab.special_middle_id;
  12682. }
  12683. llama_token llama_token_suffix(const struct llama_model * model) {
  12684. return model->vocab.special_suffix_id;
  12685. }
  12686. llama_token llama_token_eot(const struct llama_model * model) {
  12687. return model->vocab.special_eot_id;
  12688. }
  12689. int32_t llama_tokenize(
  12690. const struct llama_model * model,
  12691. const char * text,
  12692. int32_t text_len,
  12693. llama_token * tokens,
  12694. int32_t n_tokens_max,
  12695. bool add_bos,
  12696. bool special) {
  12697. auto res = llama_tokenize_internal(model->vocab, std::string(text, text_len), add_bos, special);
  12698. if (n_tokens_max < (int) res.size()) {
  12699. // LLAMA_LOG_ERROR("%s: too many tokens\n", __func__);
  12700. return -((int) res.size());
  12701. }
  12702. for (size_t i = 0; i < res.size(); i++) {
  12703. tokens[i] = res[i];
  12704. }
  12705. return res.size();
  12706. }
  12707. static std::string llama_decode_text(const std::string & text) {
  12708. std::string decoded_text;
  12709. auto unicode_sequences = unicode_cpts_from_utf8(text);
  12710. for (auto & unicode_sequence : unicode_sequences) {
  12711. decoded_text += unicode_utf8_to_byte(unicode_cpt_to_utf8(unicode_sequence));
  12712. }
  12713. return decoded_text;
  12714. }
  12715. // does not write null-terminator to buf
  12716. int32_t llama_token_to_piece(const struct llama_model * model, llama_token token, char * buf, int32_t length) {
  12717. if (0 <= token && token < llama_n_vocab(model)) {
  12718. switch (llama_vocab_get_type(model->vocab)) {
  12719. case LLAMA_VOCAB_TYPE_WPM:
  12720. case LLAMA_VOCAB_TYPE_SPM: {
  12721. // NOTE: we accept all unsupported token types,
  12722. // suppressing them like CONTROL tokens.
  12723. if (llama_is_normal_token(model->vocab, token)) {
  12724. std::string result = model->vocab.id_to_token[token].text;
  12725. llama_unescape_whitespace(result);
  12726. if (length < (int) result.length()) {
  12727. return -(int) result.length();
  12728. }
  12729. memcpy(buf, result.c_str(), result.length());
  12730. return result.length();
  12731. } else if (llama_is_user_defined_token(model->vocab, token)) {
  12732. std::string result = model->vocab.id_to_token[token].text;
  12733. if (length < (int) result.length()) {
  12734. return -(int) result.length();
  12735. }
  12736. memcpy(buf, result.c_str(), result.length());
  12737. return result.length();
  12738. } else if (llama_is_unknown_token(model->vocab, token)) { // NOLINT
  12739. if (length < 3) {
  12740. return -3;
  12741. }
  12742. memcpy(buf, "\xe2\x96\x85", 3);
  12743. return 3;
  12744. } else if (llama_is_control_token(model->vocab, token)) {
  12745. ;
  12746. } else if (llama_is_byte_token(model->vocab, token)) {
  12747. if (length < 1) {
  12748. return -1;
  12749. }
  12750. buf[0] = llama_token_to_byte(model->vocab, token);
  12751. return 1;
  12752. }
  12753. break;
  12754. }
  12755. case LLAMA_VOCAB_TYPE_BPE: {
  12756. // NOTE: we accept all unsupported token types,
  12757. // suppressing them like CONTROL tokens.
  12758. if (llama_is_normal_token(model->vocab, token)) {
  12759. std::string result = model->vocab.id_to_token[token].text;
  12760. result = llama_decode_text(result);
  12761. if (length < (int) result.length()) {
  12762. return -(int) result.length();
  12763. }
  12764. memcpy(buf, result.c_str(), result.length());
  12765. return result.length();
  12766. } else if (llama_is_user_defined_token(model->vocab, token)) {
  12767. std::string result = model->vocab.id_to_token[token].text;
  12768. if (length < (int) result.length()) {
  12769. return -(int) result.length();
  12770. }
  12771. memcpy(buf, result.c_str(), result.length());
  12772. return result.length();
  12773. } else if (llama_is_control_token(model->vocab, token)) {
  12774. ;
  12775. }
  12776. break;
  12777. }
  12778. default:
  12779. GGML_ASSERT(false);
  12780. }
  12781. }
  12782. return 0;
  12783. }
  12784. // trim whitespace from the beginning and end of a string
  12785. static std::string trim(const std::string & str) {
  12786. size_t start = 0;
  12787. size_t end = str.size();
  12788. while (start < end && isspace(str[start])) {
  12789. start += 1;
  12790. }
  12791. while (end > start && isspace(str[end - 1])) {
  12792. end -= 1;
  12793. }
  12794. return str.substr(start, end - start);
  12795. }
  12796. // Simple version of "llama_apply_chat_template" that only works with strings
  12797. // This function uses heuristic checks to determine commonly used template. It is not a jinja parser.
  12798. static int32_t llama_chat_apply_template_internal(
  12799. const std::string & tmpl,
  12800. const std::vector<const llama_chat_message *> & chat,
  12801. std::string & dest, bool add_ass) {
  12802. // Taken from the research: https://github.com/ggerganov/llama.cpp/issues/5527
  12803. std::stringstream ss;
  12804. if (tmpl == "chatml" || tmpl.find("<|im_start|>") != std::string::npos) {
  12805. // chatml template
  12806. for (auto message : chat) {
  12807. ss << "<|im_start|>" << message->role << "\n" << message->content << "<|im_end|>\n";
  12808. }
  12809. if (add_ass) {
  12810. ss << "<|im_start|>assistant\n";
  12811. }
  12812. } else if (tmpl == "llama2" || tmpl.find("[INST]") != std::string::npos) {
  12813. // llama2 template and its variants
  12814. // [variant] support system message
  12815. bool support_system_message = tmpl.find("<<SYS>>") != std::string::npos;
  12816. // [variant] space before + after response
  12817. bool space_around_response = tmpl.find("' ' + eos_token") != std::string::npos;
  12818. // [variant] add BOS inside history
  12819. bool add_bos_inside_history = tmpl.find("bos_token + '[INST]") != std::string::npos;
  12820. // [variant] trim spaces from the input message
  12821. bool strip_message = tmpl.find("content.strip()") != std::string::npos;
  12822. // construct the prompt
  12823. bool is_inside_turn = true; // skip BOS at the beginning
  12824. ss << "[INST] ";
  12825. for (auto message : chat) {
  12826. std::string content = strip_message ? trim(message->content) : message->content;
  12827. std::string role(message->role);
  12828. if (!is_inside_turn) {
  12829. is_inside_turn = true;
  12830. ss << (add_bos_inside_history ? "<s>[INST] " : "[INST] ");
  12831. }
  12832. if (role == "system") {
  12833. if (support_system_message) {
  12834. ss << "<<SYS>>\n" << content << "\n<</SYS>>\n\n";
  12835. } else {
  12836. // if the model does not support system message, we still include it in the first message, but without <<SYS>>
  12837. ss << content << "\n";
  12838. }
  12839. } else if (role == "user") {
  12840. ss << content << " [/INST]";
  12841. } else {
  12842. ss << (space_around_response ? " " : "") << content << (space_around_response ? " " : "") << "</s>";
  12843. is_inside_turn = false;
  12844. }
  12845. }
  12846. // llama2 templates seem to not care about "add_generation_prompt"
  12847. } else if (tmpl == "zephyr" || tmpl.find("<|user|>") != std::string::npos) {
  12848. // zephyr template
  12849. for (auto message : chat) {
  12850. ss << "<|" << message->role << "|>" << "\n" << message->content << "<|endoftext|>\n";
  12851. }
  12852. if (add_ass) {
  12853. ss << "<|assistant|>\n";
  12854. }
  12855. } else if (tmpl == "monarch" || tmpl.find("bos_token + message['role']") != std::string::npos) {
  12856. // mlabonne/AlphaMonarch-7B template (the <s> is included inside history)
  12857. for (auto message : chat) {
  12858. std::string bos = (message == chat.front()) ? "" : "<s>"; // skip BOS for first message
  12859. ss << bos << message->role << "\n" << message->content << "</s>\n";
  12860. }
  12861. if (add_ass) {
  12862. ss << "<s>assistant\n";
  12863. }
  12864. } else if (tmpl == "gemma" || tmpl.find("<start_of_turn>") != std::string::npos) {
  12865. // google/gemma-7b-it
  12866. std::string system_prompt = "";
  12867. for (auto message : chat) {
  12868. std::string role(message->role);
  12869. if (role == "system") {
  12870. // there is no system message for gemma, but we will merge it with user prompt, so nothing is broken
  12871. system_prompt = trim(message->content);
  12872. continue;
  12873. }
  12874. // in gemma, "assistant" is "model"
  12875. role = role == "assistant" ? "model" : message->role;
  12876. ss << "<start_of_turn>" << role << "\n";
  12877. if (!system_prompt.empty() && role != "model") {
  12878. ss << system_prompt << "\n\n";
  12879. system_prompt = "";
  12880. }
  12881. ss << trim(message->content) << "<end_of_turn>\n";
  12882. }
  12883. if (add_ass) {
  12884. ss << "<start_of_turn>model\n";
  12885. }
  12886. } else if (tmpl == "orion" || tmpl.find("'\\n\\nAssistant: ' + eos_token") != std::string::npos) {
  12887. // OrionStarAI/Orion-14B-Chat
  12888. std::string system_prompt = "";
  12889. for (auto message : chat) {
  12890. std::string role(message->role);
  12891. if (role == "system") {
  12892. // there is no system message support, we will merge it with user prompt
  12893. system_prompt = message->content;
  12894. continue;
  12895. } else if (role == "user") {
  12896. ss << "Human: ";
  12897. if (!system_prompt.empty()) {
  12898. ss << system_prompt << "\n\n";
  12899. system_prompt = "";
  12900. }
  12901. ss << message->content << "\n\nAssistant: </s>";
  12902. } else {
  12903. ss << message->content << "</s>";
  12904. }
  12905. }
  12906. } else {
  12907. // template not supported
  12908. return -1;
  12909. }
  12910. dest = ss.str();
  12911. return dest.size();
  12912. }
  12913. LLAMA_API int32_t llama_chat_apply_template(
  12914. const struct llama_model * model,
  12915. const char * tmpl,
  12916. const struct llama_chat_message * chat,
  12917. size_t n_msg,
  12918. bool add_ass,
  12919. char * buf,
  12920. int32_t length) {
  12921. std::string curr_tmpl(tmpl == nullptr ? "" : tmpl);
  12922. if (tmpl == nullptr) {
  12923. GGML_ASSERT(model != nullptr);
  12924. // load template from model
  12925. std::vector<char> model_template(2048, 0); // longest known template is about 1200 bytes
  12926. std::string template_key = "tokenizer.chat_template";
  12927. int32_t res = llama_model_meta_val_str(model, template_key.c_str(), model_template.data(), model_template.size());
  12928. if (res < 0) {
  12929. // worst case: there is no information about template, we will use chatml by default
  12930. curr_tmpl = "chatml"; // see llama_chat_apply_template_internal
  12931. } else {
  12932. curr_tmpl = std::string(model_template.data(), model_template.size());
  12933. }
  12934. }
  12935. // format the chat to string
  12936. std::vector<const llama_chat_message *> chat_vec;
  12937. chat_vec.resize(n_msg);
  12938. for (size_t i = 0; i < n_msg; i++) {
  12939. chat_vec[i] = &chat[i];
  12940. }
  12941. std::string formatted_chat;
  12942. int32_t res = llama_chat_apply_template_internal(curr_tmpl, chat_vec, formatted_chat, add_ass);
  12943. if (res < 0) {
  12944. return res;
  12945. }
  12946. if (buf && length > 0) {
  12947. strncpy(buf, formatted_chat.c_str(), length);
  12948. }
  12949. return res;
  12950. }
  12951. LLAMA_API int llama_split_path(char * split_path, size_t maxlen, const char * path_prefix, int split_no, int split_count) {
  12952. static const char * const SPLIT_PATH_FORMAT = "%s-%05d-of-%05d.gguf";
  12953. if (snprintf(split_path, maxlen, SPLIT_PATH_FORMAT, path_prefix, split_no + 1, split_count)) {
  12954. return strlen(split_path);
  12955. }
  12956. return 0;
  12957. }
  12958. int llama_split_prefix(char * dest, size_t maxlen, const char * split_path, int split_no, int split_count) {
  12959. std::string str_split_path(split_path);
  12960. char postfix[32];
  12961. snprintf(postfix, 32, "-%05d-of-%05d.gguf", split_no + 1, split_count);
  12962. std::string str_postfix(postfix);
  12963. // check if dest ends with postfix
  12964. int size_prefix = str_split_path.size() - str_postfix.size();
  12965. if (size_prefix > 0 && str_split_path.find(str_postfix, size_prefix) != std::string::npos) {
  12966. snprintf(dest, std::min((size_t) size_prefix + 1, maxlen), "%s", split_path);
  12967. return size_prefix;
  12968. }
  12969. return 0;
  12970. }
  12971. struct llama_timings llama_get_timings(struct llama_context * ctx) {
  12972. struct llama_timings result = {
  12973. /*.t_start_ms =*/ 1e-3 * ctx->t_start_us,
  12974. /*.t_end_ms =*/ 1.00 * ggml_time_ms(),
  12975. /*.t_load_ms =*/ 1e-3 * ctx->t_load_us,
  12976. /*.t_sample_ms =*/ 1e-3 * ctx->t_sample_us,
  12977. /*.t_p_eval_ms =*/ 1e-3 * ctx->t_p_eval_us,
  12978. /*.t_eval_ms =*/ 1e-3 * ctx->t_eval_us,
  12979. /*.n_sample =*/ std::max(1, ctx->n_sample),
  12980. /*.n_p_eval =*/ std::max(1, ctx->n_p_eval),
  12981. /*.n_eval =*/ std::max(1, ctx->n_eval),
  12982. };
  12983. return result;
  12984. }
  12985. void llama_print_timings(struct llama_context * ctx) {
  12986. const llama_timings timings = llama_get_timings(ctx);
  12987. LLAMA_LOG_INFO("\n");
  12988. LLAMA_LOG_INFO("%s: load time = %10.2f ms\n", __func__, timings.t_load_ms);
  12989. LLAMA_LOG_INFO("%s: sample time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  12990. __func__, timings.t_sample_ms, timings.n_sample, timings.t_sample_ms / timings.n_sample, 1e3 / timings.t_sample_ms * timings.n_sample);
  12991. LLAMA_LOG_INFO("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  12992. __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);
  12993. LLAMA_LOG_INFO("%s: eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  12994. __func__, timings.t_eval_ms, timings.n_eval, timings.t_eval_ms / timings.n_eval, 1e3 / timings.t_eval_ms * timings.n_eval);
  12995. 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));
  12996. }
  12997. void llama_reset_timings(struct llama_context * ctx) {
  12998. ctx->t_start_us = ggml_time_us();
  12999. ctx->t_sample_us = ctx->n_sample = 0;
  13000. ctx->t_eval_us = ctx->n_eval = 0;
  13001. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  13002. }
  13003. const char * llama_print_system_info(void) {
  13004. static std::string s;
  13005. s = "";
  13006. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  13007. s += "AVX_VNNI = " + std::to_string(ggml_cpu_has_avx_vnni()) + " | ";
  13008. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  13009. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  13010. s += "AVX512_VBMI = " + std::to_string(ggml_cpu_has_avx512_vbmi()) + " | ";
  13011. s += "AVX512_VNNI = " + std::to_string(ggml_cpu_has_avx512_vnni()) + " | ";
  13012. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  13013. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  13014. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  13015. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  13016. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  13017. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  13018. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  13019. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  13020. s += "SSSE3 = " + std::to_string(ggml_cpu_has_ssse3()) + " | ";
  13021. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  13022. s += "MATMUL_INT8 = " + std::to_string(ggml_cpu_has_matmul_int8()) + " | ";
  13023. return s.c_str();
  13024. }
  13025. void llama_dump_timing_info_yaml(FILE * stream, const llama_context * ctx) {
  13026. fprintf(stream, "\n");
  13027. fprintf(stream, "###########\n");
  13028. fprintf(stream, "# Timings #\n");
  13029. fprintf(stream, "###########\n");
  13030. fprintf(stream, "\n");
  13031. fprintf(stream, "mst_eval: %.2f # ms / token during generation\n",
  13032. 1.0e-3 * ctx->t_eval_us / ctx->n_eval);
  13033. fprintf(stream, "mst_p_eval: %.2f # ms / token during prompt processing\n",
  13034. 1.0e-3 * ctx->t_p_eval_us / ctx->n_p_eval);
  13035. fprintf(stream, "mst_sample: %.2f # ms / token during sampling\n",
  13036. 1.0e-3 * ctx->t_sample_us / ctx->n_sample);
  13037. fprintf(stream, "n_eval: %d # number of tokens generated (excluding the first one)\n", ctx->n_eval);
  13038. fprintf(stream, "n_p_eval: %d # number of tokens processed in batches at the beginning\n", ctx->n_p_eval);
  13039. fprintf(stream, "n_sample: %d # number of sampled tokens\n", ctx->n_sample);
  13040. fprintf(stream, "t_eval_us: %" PRId64 " # total microseconds spent generating tokens\n", ctx->t_eval_us);
  13041. fprintf(stream, "t_load_us: %" PRId64 " # total microseconds spent loading the model\n", ctx->t_load_us);
  13042. fprintf(stream, "t_p_eval_us: %" PRId64 " # total microseconds spent prompt processing\n", ctx->t_p_eval_us);
  13043. fprintf(stream, "t_sample_us: %" PRId64 " # total microseconds spent sampling\n", ctx->t_sample_us);
  13044. fprintf(stream, "ts_eval: %.2f # tokens / second during generation\n",
  13045. 1.0e6 * ctx->n_eval / ctx->t_eval_us);
  13046. fprintf(stream, "ts_p_eval: %.2f # tokens / second during prompt processing\n",
  13047. 1.0e6 * ctx->n_p_eval / ctx->t_p_eval_us);
  13048. fprintf(stream, "ts_sample: %.2f # tokens / second during sampling\n",
  13049. 1.0e6 * ctx->n_sample / ctx->t_sample_us);
  13050. }
  13051. // For internal test use
  13052. const std::vector<std::pair<std::string, struct ggml_tensor *>> & llama_internal_get_tensor_map(
  13053. struct llama_context * ctx
  13054. ) {
  13055. return ctx->model.tensors_by_name;
  13056. }
  13057. void llama_log_set(ggml_log_callback log_callback, void * user_data) {
  13058. g_state.log_callback = log_callback ? log_callback : llama_log_callback_default;
  13059. g_state.log_callback_user_data = user_data;
  13060. #ifdef GGML_USE_METAL
  13061. ggml_backend_metal_log_set_callback(g_state.log_callback, g_state.log_callback_user_data);
  13062. #endif
  13063. }
  13064. static void llama_log_internal_v(ggml_log_level level, const char * format, va_list args) {
  13065. va_list args_copy;
  13066. va_copy(args_copy, args);
  13067. char buffer[128];
  13068. int len = vsnprintf(buffer, 128, format, args);
  13069. if (len < 128) {
  13070. g_state.log_callback(level, buffer, g_state.log_callback_user_data);
  13071. } else {
  13072. char* buffer2 = new char[len+1];
  13073. vsnprintf(buffer2, len+1, format, args_copy);
  13074. buffer2[len] = 0;
  13075. g_state.log_callback(level, buffer2, g_state.log_callback_user_data);
  13076. delete[] buffer2;
  13077. }
  13078. va_end(args_copy);
  13079. }
  13080. static void llama_log_internal(ggml_log_level level, const char * format, ...) {
  13081. va_list args;
  13082. va_start(args, format);
  13083. llama_log_internal_v(level, format, args);
  13084. va_end(args);
  13085. }
  13086. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data) {
  13087. (void) level;
  13088. (void) user_data;
  13089. fputs(text, stderr);
  13090. fflush(stderr);
  13091. }