llama.cpp 574 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768
  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_CUBLAS
  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. #include <io.h>
  50. #endif
  51. #include <algorithm>
  52. #include <array>
  53. #include <cassert>
  54. #include <cfloat>
  55. #include <cinttypes>
  56. #include <climits>
  57. #include <cmath>
  58. #include <cstdarg>
  59. #include <cstddef>
  60. #include <cstdint>
  61. #include <cstdio>
  62. #include <cstring>
  63. #include <ctime>
  64. #include <cwctype>
  65. #include <forward_list>
  66. #include <fstream>
  67. #include <functional>
  68. #include <initializer_list>
  69. #include <locale>
  70. #include <map>
  71. #include <memory>
  72. #include <mutex>
  73. #include <numeric>
  74. #include <queue>
  75. #include <random>
  76. #include <regex>
  77. #include <set>
  78. #include <sstream>
  79. #include <thread>
  80. #include <type_traits>
  81. #include <unordered_map>
  82. #if defined(_MSC_VER)
  83. #pragma warning(disable: 4244 4267) // possible loss of data
  84. #endif
  85. #ifdef __GNUC__
  86. #ifdef __MINGW32__
  87. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(gnu_printf, __VA_ARGS__)))
  88. #else
  89. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(printf, __VA_ARGS__)))
  90. #endif
  91. #else
  92. #define LLAMA_ATTRIBUTE_FORMAT(...)
  93. #endif
  94. #define LLAMA_MAX_NODES 8192
  95. #define LLAMA_MAX_EXPERTS 8
  96. //
  97. // logging
  98. //
  99. LLAMA_ATTRIBUTE_FORMAT(2, 3)
  100. static void llama_log_internal (ggml_log_level level, const char* format, ...);
  101. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data);
  102. #define LLAMA_LOG_INFO(...) llama_log_internal(GGML_LOG_LEVEL_INFO , __VA_ARGS__)
  103. #define LLAMA_LOG_WARN(...) llama_log_internal(GGML_LOG_LEVEL_WARN , __VA_ARGS__)
  104. #define LLAMA_LOG_ERROR(...) llama_log_internal(GGML_LOG_LEVEL_ERROR, __VA_ARGS__)
  105. //
  106. // helpers
  107. //
  108. static size_t utf8_len(char src) {
  109. const size_t lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4 };
  110. uint8_t highbits = static_cast<uint8_t>(src) >> 4;
  111. return lookup[highbits];
  112. }
  113. static void replace_all(std::string & s, const std::string & search, const std::string & replace) {
  114. std::string result;
  115. for (size_t pos = 0; ; pos += search.length()) {
  116. auto new_pos = s.find(search, pos);
  117. if (new_pos == std::string::npos) {
  118. result += s.substr(pos, s.size() - pos);
  119. break;
  120. }
  121. result += s.substr(pos, new_pos - pos) + replace;
  122. pos = new_pos;
  123. }
  124. s = std::move(result);
  125. }
  126. static bool is_float_close(float a, float b, float abs_tol) {
  127. // Check for non-negative tolerance
  128. if (abs_tol < 0.0) {
  129. throw std::invalid_argument("Tolerance must be non-negative");
  130. }
  131. // Exact equality check
  132. if (a == b) {
  133. return true;
  134. }
  135. // Check for infinities
  136. if (std::isinf(a) || std::isinf(b)) {
  137. return false;
  138. }
  139. // Regular comparison using the provided absolute tolerance
  140. return std::fabs(b - a) <= abs_tol;
  141. }
  142. static void zeros(std::ofstream & file, size_t n) {
  143. char zero = 0;
  144. for (size_t i = 0; i < n; ++i) {
  145. file.write(&zero, 1);
  146. }
  147. }
  148. LLAMA_ATTRIBUTE_FORMAT(1, 2)
  149. static std::string format(const char * fmt, ...) {
  150. va_list ap;
  151. va_list ap2;
  152. va_start(ap, fmt);
  153. va_copy(ap2, ap);
  154. int size = vsnprintf(NULL, 0, fmt, ap);
  155. GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
  156. std::vector<char> buf(size + 1);
  157. int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
  158. GGML_ASSERT(size2 == size);
  159. va_end(ap2);
  160. va_end(ap);
  161. return std::string(buf.data(), size);
  162. }
  163. //
  164. // gguf constants (sync with gguf.py)
  165. //
  166. enum llm_arch {
  167. LLM_ARCH_LLAMA,
  168. LLM_ARCH_FALCON,
  169. LLM_ARCH_BAICHUAN,
  170. LLM_ARCH_GPT2,
  171. LLM_ARCH_GPTJ,
  172. LLM_ARCH_GPTNEOX,
  173. LLM_ARCH_MPT,
  174. LLM_ARCH_STARCODER,
  175. LLM_ARCH_PERSIMMON,
  176. LLM_ARCH_REFACT,
  177. LLM_ARCH_BERT,
  178. LLM_ARCH_NOMIC_BERT,
  179. LLM_ARCH_BLOOM,
  180. LLM_ARCH_STABLELM,
  181. LLM_ARCH_QWEN,
  182. LLM_ARCH_QWEN2,
  183. LLM_ARCH_PHI2,
  184. LLM_ARCH_PLAMO,
  185. LLM_ARCH_CODESHELL,
  186. LLM_ARCH_ORION,
  187. LLM_ARCH_INTERNLM2,
  188. LLM_ARCH_MINICPM,
  189. LLM_ARCH_GEMMA,
  190. LLM_ARCH_STARCODER2,
  191. LLM_ARCH_MAMBA,
  192. LLM_ARCH_COMMAND_R,
  193. LLM_ARCH_UNKNOWN,
  194. };
  195. static const std::map<llm_arch, const char *> LLM_ARCH_NAMES = {
  196. { LLM_ARCH_LLAMA, "llama" },
  197. { LLM_ARCH_FALCON, "falcon" },
  198. { LLM_ARCH_GPT2, "gpt2" },
  199. { LLM_ARCH_GPTJ, "gptj" },
  200. { LLM_ARCH_GPTNEOX, "gptneox" },
  201. { LLM_ARCH_MPT, "mpt" },
  202. { LLM_ARCH_BAICHUAN, "baichuan" },
  203. { LLM_ARCH_STARCODER, "starcoder" },
  204. { LLM_ARCH_PERSIMMON, "persimmon" },
  205. { LLM_ARCH_REFACT, "refact" },
  206. { LLM_ARCH_BERT, "bert" },
  207. { LLM_ARCH_NOMIC_BERT, "nomic-bert" },
  208. { LLM_ARCH_BLOOM, "bloom" },
  209. { LLM_ARCH_STABLELM, "stablelm" },
  210. { LLM_ARCH_QWEN, "qwen" },
  211. { LLM_ARCH_QWEN2, "qwen2" },
  212. { LLM_ARCH_PHI2, "phi2" },
  213. { LLM_ARCH_PLAMO, "plamo" },
  214. { LLM_ARCH_CODESHELL, "codeshell" },
  215. { LLM_ARCH_ORION, "orion" },
  216. { LLM_ARCH_INTERNLM2, "internlm2" },
  217. { LLM_ARCH_MINICPM, "minicpm" },
  218. { LLM_ARCH_GEMMA, "gemma" },
  219. { LLM_ARCH_STARCODER2, "starcoder2" },
  220. { LLM_ARCH_MAMBA, "mamba" },
  221. { LLM_ARCH_COMMAND_R, "command-r" },
  222. { LLM_ARCH_UNKNOWN, "(unknown)" },
  223. };
  224. enum llm_kv {
  225. LLM_KV_GENERAL_ARCHITECTURE,
  226. LLM_KV_GENERAL_QUANTIZATION_VERSION,
  227. LLM_KV_GENERAL_ALIGNMENT,
  228. LLM_KV_GENERAL_NAME,
  229. LLM_KV_GENERAL_AUTHOR,
  230. LLM_KV_GENERAL_URL,
  231. LLM_KV_GENERAL_DESCRIPTION,
  232. LLM_KV_GENERAL_LICENSE,
  233. LLM_KV_GENERAL_SOURCE_URL,
  234. LLM_KV_GENERAL_SOURCE_HF_REPO,
  235. LLM_KV_VOCAB_SIZE,
  236. LLM_KV_CONTEXT_LENGTH,
  237. LLM_KV_EMBEDDING_LENGTH,
  238. LLM_KV_BLOCK_COUNT,
  239. LLM_KV_FEED_FORWARD_LENGTH,
  240. LLM_KV_USE_PARALLEL_RESIDUAL,
  241. LLM_KV_TENSOR_DATA_LAYOUT,
  242. LLM_KV_EXPERT_COUNT,
  243. LLM_KV_EXPERT_USED_COUNT,
  244. LLM_KV_POOLING_TYPE,
  245. LLM_KV_LOGIT_SCALE,
  246. LLM_KV_ATTENTION_HEAD_COUNT,
  247. LLM_KV_ATTENTION_HEAD_COUNT_KV,
  248. LLM_KV_ATTENTION_MAX_ALIBI_BIAS,
  249. LLM_KV_ATTENTION_CLAMP_KQV,
  250. LLM_KV_ATTENTION_KEY_LENGTH,
  251. LLM_KV_ATTENTION_VALUE_LENGTH,
  252. LLM_KV_ATTENTION_LAYERNORM_EPS,
  253. LLM_KV_ATTENTION_LAYERNORM_RMS_EPS,
  254. LLM_KV_ATTENTION_CAUSAL,
  255. LLM_KV_ROPE_DIMENSION_COUNT,
  256. LLM_KV_ROPE_FREQ_BASE,
  257. LLM_KV_ROPE_SCALE_LINEAR,
  258. LLM_KV_ROPE_SCALING_TYPE,
  259. LLM_KV_ROPE_SCALING_FACTOR,
  260. LLM_KV_ROPE_SCALING_ORIG_CTX_LEN,
  261. LLM_KV_ROPE_SCALING_FINETUNED,
  262. LLM_KV_SSM_INNER_SIZE,
  263. LLM_KV_SSM_CONV_KERNEL,
  264. LLM_KV_SSM_STATE_SIZE,
  265. LLM_KV_SSM_TIME_STEP_RANK,
  266. LLM_KV_TOKENIZER_MODEL,
  267. LLM_KV_TOKENIZER_LIST,
  268. LLM_KV_TOKENIZER_TOKEN_TYPE,
  269. LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT,
  270. LLM_KV_TOKENIZER_SCORES,
  271. LLM_KV_TOKENIZER_MERGES,
  272. LLM_KV_TOKENIZER_BOS_ID,
  273. LLM_KV_TOKENIZER_EOS_ID,
  274. LLM_KV_TOKENIZER_UNK_ID,
  275. LLM_KV_TOKENIZER_SEP_ID,
  276. LLM_KV_TOKENIZER_PAD_ID,
  277. LLM_KV_TOKENIZER_ADD_BOS,
  278. LLM_KV_TOKENIZER_ADD_EOS,
  279. LLM_KV_TOKENIZER_ADD_PREFIX,
  280. LLM_KV_TOKENIZER_HF_JSON,
  281. LLM_KV_TOKENIZER_RWKV,
  282. };
  283. static const std::map<llm_kv, const char *> LLM_KV_NAMES = {
  284. { LLM_KV_GENERAL_ARCHITECTURE, "general.architecture" },
  285. { LLM_KV_GENERAL_QUANTIZATION_VERSION, "general.quantization_version" },
  286. { LLM_KV_GENERAL_ALIGNMENT, "general.alignment" },
  287. { LLM_KV_GENERAL_NAME, "general.name" },
  288. { LLM_KV_GENERAL_AUTHOR, "general.author" },
  289. { LLM_KV_GENERAL_URL, "general.url" },
  290. { LLM_KV_GENERAL_DESCRIPTION, "general.description" },
  291. { LLM_KV_GENERAL_LICENSE, "general.license" },
  292. { LLM_KV_GENERAL_SOURCE_URL, "general.source.url" },
  293. { LLM_KV_GENERAL_SOURCE_HF_REPO, "general.source.huggingface.repository" },
  294. { LLM_KV_VOCAB_SIZE, "%s.vocab_size" },
  295. { LLM_KV_CONTEXT_LENGTH, "%s.context_length" },
  296. { LLM_KV_EMBEDDING_LENGTH, "%s.embedding_length" },
  297. { LLM_KV_BLOCK_COUNT, "%s.block_count" },
  298. { LLM_KV_FEED_FORWARD_LENGTH, "%s.feed_forward_length" },
  299. { LLM_KV_USE_PARALLEL_RESIDUAL, "%s.use_parallel_residual" },
  300. { LLM_KV_TENSOR_DATA_LAYOUT, "%s.tensor_data_layout" },
  301. { LLM_KV_EXPERT_COUNT, "%s.expert_count" },
  302. { LLM_KV_EXPERT_USED_COUNT, "%s.expert_used_count" },
  303. { LLM_KV_POOLING_TYPE , "%s.pooling_type" },
  304. { LLM_KV_LOGIT_SCALE, "%s.logit_scale" },
  305. { LLM_KV_ATTENTION_HEAD_COUNT, "%s.attention.head_count" },
  306. { LLM_KV_ATTENTION_HEAD_COUNT_KV, "%s.attention.head_count_kv" },
  307. { LLM_KV_ATTENTION_MAX_ALIBI_BIAS, "%s.attention.max_alibi_bias" },
  308. { LLM_KV_ATTENTION_CLAMP_KQV, "%s.attention.clamp_kqv" },
  309. { LLM_KV_ATTENTION_KEY_LENGTH, "%s.attention.key_length" },
  310. { LLM_KV_ATTENTION_VALUE_LENGTH, "%s.attention.value_length" },
  311. { LLM_KV_ATTENTION_LAYERNORM_EPS, "%s.attention.layer_norm_epsilon" },
  312. { LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, "%s.attention.layer_norm_rms_epsilon" },
  313. { LLM_KV_ATTENTION_CAUSAL, "%s.attention.causal" },
  314. { LLM_KV_ROPE_DIMENSION_COUNT, "%s.rope.dimension_count" },
  315. { LLM_KV_ROPE_FREQ_BASE, "%s.rope.freq_base" },
  316. { LLM_KV_ROPE_SCALE_LINEAR, "%s.rope.scale_linear" },
  317. { LLM_KV_ROPE_SCALING_TYPE, "%s.rope.scaling.type" },
  318. { LLM_KV_ROPE_SCALING_FACTOR, "%s.rope.scaling.factor" },
  319. { LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, "%s.rope.scaling.original_context_length" },
  320. { LLM_KV_ROPE_SCALING_FINETUNED, "%s.rope.scaling.finetuned" },
  321. { LLM_KV_SSM_CONV_KERNEL, "%s.ssm.conv_kernel" },
  322. { LLM_KV_SSM_INNER_SIZE, "%s.ssm.inner_size" },
  323. { LLM_KV_SSM_STATE_SIZE, "%s.ssm.state_size" },
  324. { LLM_KV_SSM_TIME_STEP_RANK, "%s.ssm.time_step_rank" },
  325. { LLM_KV_TOKENIZER_MODEL, "tokenizer.ggml.model" },
  326. { LLM_KV_TOKENIZER_LIST, "tokenizer.ggml.tokens" },
  327. { LLM_KV_TOKENIZER_TOKEN_TYPE, "tokenizer.ggml.token_type" },
  328. { LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, "tokenizer.ggml.token_type_count" },
  329. { LLM_KV_TOKENIZER_SCORES, "tokenizer.ggml.scores" },
  330. { LLM_KV_TOKENIZER_MERGES, "tokenizer.ggml.merges" },
  331. { LLM_KV_TOKENIZER_BOS_ID, "tokenizer.ggml.bos_token_id" },
  332. { LLM_KV_TOKENIZER_EOS_ID, "tokenizer.ggml.eos_token_id" },
  333. { LLM_KV_TOKENIZER_UNK_ID, "tokenizer.ggml.unknown_token_id" },
  334. { LLM_KV_TOKENIZER_SEP_ID, "tokenizer.ggml.seperator_token_id" },
  335. { LLM_KV_TOKENIZER_PAD_ID, "tokenizer.ggml.padding_token_id" },
  336. { LLM_KV_TOKENIZER_ADD_BOS, "tokenizer.ggml.add_bos_token" },
  337. { LLM_KV_TOKENIZER_ADD_EOS, "tokenizer.ggml.add_eos_token" },
  338. { LLM_KV_TOKENIZER_ADD_PREFIX, "tokenizer.ggml.add_space_prefix" },
  339. { LLM_KV_TOKENIZER_HF_JSON, "tokenizer.huggingface.json" },
  340. { LLM_KV_TOKENIZER_RWKV, "tokenizer.rwkv.world" },
  341. };
  342. struct LLM_KV {
  343. LLM_KV(llm_arch arch) : arch(arch) {}
  344. llm_arch arch;
  345. std::string operator()(llm_kv kv) const {
  346. return ::format(LLM_KV_NAMES.at(kv), LLM_ARCH_NAMES.at(arch));
  347. }
  348. };
  349. enum llm_tensor {
  350. LLM_TENSOR_TOKEN_EMBD,
  351. LLM_TENSOR_TOKEN_EMBD_NORM,
  352. LLM_TENSOR_TOKEN_TYPES,
  353. LLM_TENSOR_POS_EMBD,
  354. LLM_TENSOR_OUTPUT,
  355. LLM_TENSOR_OUTPUT_NORM,
  356. LLM_TENSOR_ROPE_FREQS,
  357. LLM_TENSOR_ATTN_Q,
  358. LLM_TENSOR_ATTN_K,
  359. LLM_TENSOR_ATTN_V,
  360. LLM_TENSOR_ATTN_QKV,
  361. LLM_TENSOR_ATTN_OUT,
  362. LLM_TENSOR_ATTN_NORM,
  363. LLM_TENSOR_ATTN_NORM_2,
  364. LLM_TENSOR_ATTN_OUT_NORM,
  365. LLM_TENSOR_ATTN_ROT_EMBD,
  366. LLM_TENSOR_FFN_GATE_INP,
  367. LLM_TENSOR_FFN_NORM,
  368. LLM_TENSOR_FFN_GATE,
  369. LLM_TENSOR_FFN_DOWN,
  370. LLM_TENSOR_FFN_UP,
  371. LLM_TENSOR_FFN_ACT,
  372. LLM_TENSOR_FFN_DOWN_EXP,
  373. LLM_TENSOR_FFN_GATE_EXP,
  374. LLM_TENSOR_FFN_UP_EXP,
  375. LLM_TENSOR_ATTN_Q_NORM,
  376. LLM_TENSOR_ATTN_K_NORM,
  377. LLM_TENSOR_LAYER_OUT_NORM,
  378. LLM_TENSOR_SSM_IN,
  379. LLM_TENSOR_SSM_CONV1D,
  380. LLM_TENSOR_SSM_X,
  381. LLM_TENSOR_SSM_DT,
  382. LLM_TENSOR_SSM_A,
  383. LLM_TENSOR_SSM_D,
  384. LLM_TENSOR_SSM_OUT,
  385. };
  386. static const std::map<llm_arch, std::map<llm_tensor, std::string>> LLM_TENSOR_NAMES = {
  387. {
  388. LLM_ARCH_LLAMA,
  389. {
  390. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  391. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  392. { LLM_TENSOR_OUTPUT, "output" },
  393. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  394. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  395. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  396. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  397. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  398. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  399. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  400. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  401. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  402. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  403. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  404. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  405. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  406. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  407. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  408. },
  409. },
  410. {
  411. LLM_ARCH_BAICHUAN,
  412. {
  413. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  414. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  415. { LLM_TENSOR_OUTPUT, "output" },
  416. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  417. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  418. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  419. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  420. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  421. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  422. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  423. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  424. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  425. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  426. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  427. },
  428. },
  429. {
  430. LLM_ARCH_FALCON,
  431. {
  432. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  433. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  434. { LLM_TENSOR_OUTPUT, "output" },
  435. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  436. { LLM_TENSOR_ATTN_NORM_2, "blk.%d.attn_norm_2" },
  437. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  438. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  439. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  440. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  441. },
  442. },
  443. {
  444. LLM_ARCH_GPT2,
  445. {
  446. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  447. { LLM_TENSOR_POS_EMBD, "position_embd" },
  448. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  449. { LLM_TENSOR_OUTPUT, "output" },
  450. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  451. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  452. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  453. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  454. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  455. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  456. },
  457. },
  458. {
  459. LLM_ARCH_GPTJ,
  460. {
  461. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  462. },
  463. },
  464. {
  465. LLM_ARCH_GPTNEOX,
  466. {
  467. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  468. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  469. { LLM_TENSOR_OUTPUT, "output" },
  470. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  471. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  472. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  473. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  474. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  475. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  476. },
  477. },
  478. {
  479. LLM_ARCH_PERSIMMON,
  480. {
  481. { LLM_TENSOR_TOKEN_EMBD, "token_embd"},
  482. { LLM_TENSOR_OUTPUT_NORM, "output_norm"},
  483. { LLM_TENSOR_OUTPUT, "output"},
  484. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm"},
  485. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv"},
  486. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output"},
  487. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm"},
  488. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm"},
  489. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm"},
  490. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down"},
  491. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up"},
  492. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd"},
  493. },
  494. },
  495. {
  496. LLM_ARCH_MPT,
  497. {
  498. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  499. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  500. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  501. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  502. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  503. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  504. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  505. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  506. { LLM_TENSOR_FFN_ACT, "blk.%d.ffn.act" },
  507. },
  508. },
  509. {
  510. LLM_ARCH_STARCODER,
  511. {
  512. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  513. { LLM_TENSOR_POS_EMBD, "position_embd" },
  514. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  515. { LLM_TENSOR_OUTPUT, "output" },
  516. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  517. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  518. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  519. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  520. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  521. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  522. },
  523. },
  524. {
  525. LLM_ARCH_REFACT,
  526. {
  527. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  528. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  529. { LLM_TENSOR_OUTPUT, "output" },
  530. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  531. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  532. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  533. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  534. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  535. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  536. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  537. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  538. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  539. },
  540. },
  541. {
  542. LLM_ARCH_BERT,
  543. {
  544. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  545. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  546. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  547. { LLM_TENSOR_POS_EMBD, "position_embd" },
  548. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  549. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  550. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  551. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  552. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  553. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  554. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  555. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  556. },
  557. },
  558. {
  559. LLM_ARCH_NOMIC_BERT,
  560. {
  561. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  562. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  563. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  564. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  565. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  566. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  567. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  568. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  569. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  570. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  571. },
  572. },
  573. {
  574. LLM_ARCH_BLOOM,
  575. {
  576. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  577. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  578. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  579. { LLM_TENSOR_OUTPUT, "output" },
  580. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  581. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  582. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  583. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  584. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  585. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  586. },
  587. },
  588. {
  589. LLM_ARCH_STABLELM,
  590. {
  591. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  592. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  593. { LLM_TENSOR_OUTPUT, "output" },
  594. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  595. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  596. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  597. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  598. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  599. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  600. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  601. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  602. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  603. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  604. },
  605. },
  606. {
  607. LLM_ARCH_QWEN,
  608. {
  609. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  610. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  611. { LLM_TENSOR_OUTPUT, "output" },
  612. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  613. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  614. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  615. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  616. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  617. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  618. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  619. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  620. },
  621. },
  622. {
  623. LLM_ARCH_QWEN2,
  624. {
  625. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  626. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  627. { LLM_TENSOR_OUTPUT, "output" },
  628. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  629. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  630. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  631. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  632. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  633. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  634. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  635. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  636. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  637. },
  638. },
  639. {
  640. LLM_ARCH_PHI2,
  641. {
  642. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  643. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  644. { LLM_TENSOR_OUTPUT, "output" },
  645. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  646. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  647. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  648. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  649. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  650. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  651. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  652. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  653. },
  654. },
  655. {
  656. LLM_ARCH_PLAMO,
  657. {
  658. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  659. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  660. { LLM_TENSOR_OUTPUT, "output" },
  661. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  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_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  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_CODESHELL,
  675. {
  676. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  677. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  678. { LLM_TENSOR_OUTPUT, "output" },
  679. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  680. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  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_QKV, "blk.%d.attn_qkv" },
  685. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  686. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  687. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  688. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  689. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  690. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  691. },
  692. },
  693. {
  694. LLM_ARCH_ORION,
  695. {
  696. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  697. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  698. { LLM_TENSOR_OUTPUT, "output" },
  699. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  700. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  701. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  702. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  703. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  704. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  705. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  706. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  707. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  708. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  709. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  710. },
  711. },
  712. {
  713. LLM_ARCH_INTERNLM2,
  714. {
  715. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  716. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  717. { LLM_TENSOR_OUTPUT, "output" },
  718. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  719. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  720. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  721. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  722. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  723. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  724. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  725. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  726. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  727. },
  728. },
  729. {
  730. LLM_ARCH_MINICPM,
  731. {
  732. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  733. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  734. { LLM_TENSOR_OUTPUT, "output" },
  735. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  736. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  737. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  738. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  739. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  740. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  741. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  742. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  743. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  744. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  745. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  746. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  747. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  748. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  749. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  750. },
  751. },
  752. {
  753. LLM_ARCH_GEMMA,
  754. {
  755. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  756. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  757. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  758. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  759. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  760. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  761. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  762. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  763. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  764. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  765. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  766. },
  767. },
  768. {
  769. LLM_ARCH_STARCODER2,
  770. {
  771. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  772. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  773. { LLM_TENSOR_OUTPUT, "output" },
  774. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  775. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  776. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  777. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  778. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  779. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  780. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  781. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  782. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  783. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  784. },
  785. },
  786. {
  787. LLM_ARCH_MAMBA,
  788. {
  789. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  790. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  791. { LLM_TENSOR_OUTPUT, "output" },
  792. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  793. { LLM_TENSOR_SSM_IN, "blk.%d.ssm_in" },
  794. { LLM_TENSOR_SSM_CONV1D, "blk.%d.ssm_conv1d" },
  795. { LLM_TENSOR_SSM_X, "blk.%d.ssm_x" },
  796. { LLM_TENSOR_SSM_DT, "blk.%d.ssm_dt" },
  797. { LLM_TENSOR_SSM_A, "blk.%d.ssm_a" },
  798. { LLM_TENSOR_SSM_D, "blk.%d.ssm_d" },
  799. { LLM_TENSOR_SSM_OUT, "blk.%d.ssm_out" },
  800. },
  801. },
  802. {
  803. LLM_ARCH_COMMAND_R,
  804. {
  805. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  806. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  807. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  808. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  809. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  810. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  811. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  812. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  813. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  814. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  815. },
  816. },
  817. {
  818. LLM_ARCH_UNKNOWN,
  819. {
  820. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  821. },
  822. },
  823. };
  824. static llm_arch llm_arch_from_string(const std::string & name) {
  825. for (const auto & kv : LLM_ARCH_NAMES) { // NOLINT
  826. if (kv.second == name) {
  827. return kv.first;
  828. }
  829. }
  830. return LLM_ARCH_UNKNOWN;
  831. }
  832. // helper to handle gguf constants
  833. // usage:
  834. //
  835. // const auto tn = LLM_TN(LLM_ARCH_LLAMA);
  836. //
  837. // std::string name = tn(LLM_TENSOR_OUTPUT); -> "output"
  838. // std::string name = tn(LLM_TENSOR_TOKEN_EMBD, "bias"); -> "token_embd.bias"
  839. // std::string name = tn(LLM_TENSOR_ATTN_NORM, "weight", 3); -> "blk.3.attn_norm.weight"
  840. //
  841. struct LLM_TN {
  842. LLM_TN(llm_arch arch) : arch(arch) {}
  843. llm_arch arch;
  844. std::string operator()(llm_tensor tensor) const {
  845. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  846. return "__missing__";
  847. }
  848. return LLM_TENSOR_NAMES.at(arch).at(tensor);
  849. }
  850. std::string operator()(llm_tensor tensor, const std::string & suffix) const {
  851. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  852. return "__missing__";
  853. }
  854. return LLM_TENSOR_NAMES.at(arch).at(tensor) + "." + suffix;
  855. }
  856. std::string operator()(llm_tensor tensor, int bid) const {
  857. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  858. return "__missing__";
  859. }
  860. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid);
  861. }
  862. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid) const {
  863. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  864. return "__missing__";
  865. }
  866. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid) + "." + suffix;
  867. }
  868. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid, int xid) const {
  869. if (LLM_TENSOR_NAMES.at(arch).find(tensor) == LLM_TENSOR_NAMES.at(arch).end()) {
  870. return "__missing__";
  871. }
  872. return ::format(LLM_TENSOR_NAMES.at(arch).at(tensor).c_str(), bid, xid) + "." + suffix;
  873. }
  874. };
  875. //
  876. // gguf helpers
  877. //
  878. static const std::map<llama_rope_scaling_type, const char *> LLAMA_ROPE_SCALING_TYPES = {
  879. { LLAMA_ROPE_SCALING_TYPE_NONE, "none" },
  880. { LLAMA_ROPE_SCALING_TYPE_LINEAR, "linear" },
  881. { LLAMA_ROPE_SCALING_TYPE_YARN, "yarn" },
  882. };
  883. static llama_rope_scaling_type llama_rope_scaling_type_from_string(const std::string & name) {
  884. for (const auto & kv : LLAMA_ROPE_SCALING_TYPES) {
  885. if (kv.second == name) {
  886. return (llama_rope_scaling_type) kv.first;
  887. }
  888. }
  889. return LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED;
  890. }
  891. static std::string gguf_data_to_str(enum gguf_type type, const void * data, int i) {
  892. switch (type) {
  893. case GGUF_TYPE_UINT8: return std::to_string(((const uint8_t *)data)[i]);
  894. case GGUF_TYPE_INT8: return std::to_string(((const int8_t *)data)[i]);
  895. case GGUF_TYPE_UINT16: return std::to_string(((const uint16_t *)data)[i]);
  896. case GGUF_TYPE_INT16: return std::to_string(((const int16_t *)data)[i]);
  897. case GGUF_TYPE_UINT32: return std::to_string(((const uint32_t *)data)[i]);
  898. case GGUF_TYPE_INT32: return std::to_string(((const int32_t *)data)[i]);
  899. case GGUF_TYPE_UINT64: return std::to_string(((const uint64_t *)data)[i]);
  900. case GGUF_TYPE_INT64: return std::to_string(((const int64_t *)data)[i]);
  901. case GGUF_TYPE_FLOAT32: return std::to_string(((const float *)data)[i]);
  902. case GGUF_TYPE_FLOAT64: return std::to_string(((const double *)data)[i]);
  903. case GGUF_TYPE_BOOL: return ((const bool *)data)[i] ? "true" : "false";
  904. default: return format("unknown type %d", type);
  905. }
  906. }
  907. static std::string gguf_kv_to_str(const struct gguf_context * ctx_gguf, int i) {
  908. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  909. switch (type) {
  910. case GGUF_TYPE_STRING:
  911. return gguf_get_val_str(ctx_gguf, i);
  912. case GGUF_TYPE_ARRAY:
  913. {
  914. const enum gguf_type arr_type = gguf_get_arr_type(ctx_gguf, i);
  915. int arr_n = gguf_get_arr_n(ctx_gguf, i);
  916. const void * data = gguf_get_arr_data(ctx_gguf, i);
  917. std::stringstream ss;
  918. ss << "[";
  919. for (int j = 0; j < arr_n; j++) {
  920. if (arr_type == GGUF_TYPE_STRING) {
  921. std::string val = gguf_get_arr_str(ctx_gguf, i, j);
  922. // escape quotes
  923. replace_all(val, "\\", "\\\\");
  924. replace_all(val, "\"", "\\\"");
  925. ss << '"' << val << '"';
  926. } else if (arr_type == GGUF_TYPE_ARRAY) {
  927. ss << "???";
  928. } else {
  929. ss << gguf_data_to_str(arr_type, data, j);
  930. }
  931. if (j < arr_n - 1) {
  932. ss << ", ";
  933. }
  934. }
  935. ss << "]";
  936. return ss.str();
  937. }
  938. default:
  939. return gguf_data_to_str(type, gguf_get_val_data(ctx_gguf, i), 0);
  940. }
  941. }
  942. //
  943. // llama helpers
  944. //
  945. #if defined(_WIN32)
  946. static std::string llama_format_win_err(DWORD err) {
  947. LPSTR buf;
  948. size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  949. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, NULL);
  950. if (!size) {
  951. return "FormatMessageA failed";
  952. }
  953. std::string ret(buf, size);
  954. LocalFree(buf);
  955. return ret;
  956. }
  957. #endif
  958. template <typename T>
  959. struct no_init {
  960. T value;
  961. no_init() { /* do nothing */ }
  962. };
  963. struct llama_file {
  964. // use FILE * so we don't have to re-open the file to mmap
  965. FILE * fp;
  966. size_t size;
  967. llama_file(const char * fname, const char * mode) {
  968. fp = std::fopen(fname, mode);
  969. if (fp == NULL) {
  970. throw std::runtime_error(format("failed to open %s: %s", fname, strerror(errno)));
  971. }
  972. seek(0, SEEK_END);
  973. size = tell();
  974. seek(0, SEEK_SET);
  975. }
  976. size_t tell() const {
  977. #ifdef _WIN32
  978. __int64 ret = _ftelli64(fp);
  979. #else
  980. long ret = std::ftell(fp);
  981. #endif
  982. GGML_ASSERT(ret != -1); // this really shouldn't fail
  983. return (size_t) ret;
  984. }
  985. void seek(size_t offset, int whence) const {
  986. #ifdef _WIN32
  987. int ret = _fseeki64(fp, (__int64) offset, whence);
  988. #else
  989. int ret = std::fseek(fp, (long) offset, whence);
  990. #endif
  991. GGML_ASSERT(ret == 0); // same
  992. }
  993. void read_raw(void * ptr, size_t len) const {
  994. if (len == 0) {
  995. return;
  996. }
  997. errno = 0;
  998. std::size_t ret = std::fread(ptr, len, 1, fp);
  999. if (ferror(fp)) {
  1000. throw std::runtime_error(format("read error: %s", strerror(errno)));
  1001. }
  1002. if (ret != 1) {
  1003. throw std::runtime_error("unexpectedly reached end of file");
  1004. }
  1005. }
  1006. uint32_t read_u32() const {
  1007. uint32_t ret;
  1008. read_raw(&ret, sizeof(ret));
  1009. return ret;
  1010. }
  1011. void write_raw(const void * ptr, size_t len) const {
  1012. if (len == 0) {
  1013. return;
  1014. }
  1015. errno = 0;
  1016. size_t ret = std::fwrite(ptr, len, 1, fp);
  1017. if (ret != 1) {
  1018. throw std::runtime_error(format("write error: %s", strerror(errno)));
  1019. }
  1020. }
  1021. void write_u32(std::uint32_t val) const {
  1022. write_raw(&val, sizeof(val));
  1023. }
  1024. ~llama_file() {
  1025. if (fp) {
  1026. std::fclose(fp);
  1027. }
  1028. }
  1029. };
  1030. struct llama_mmap {
  1031. void * addr;
  1032. size_t size;
  1033. llama_mmap(const llama_mmap &) = delete;
  1034. #ifdef _POSIX_MAPPED_FILES
  1035. static constexpr bool SUPPORTED = true;
  1036. // list of mapped fragments (first_offset, last_offset)
  1037. std::vector<std::pair<size_t, size_t>> mapped_fragments;
  1038. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1 /* -1 = max value */, bool numa = false) {
  1039. size = file->size;
  1040. int fd = fileno(file->fp);
  1041. int flags = MAP_SHARED;
  1042. // prefetch/readahead impairs performance on NUMA systems
  1043. if (numa) { prefetch = 0; }
  1044. #ifdef __linux__
  1045. // advise the kernel to read the file sequentially (increases readahead)
  1046. if (posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL)) {
  1047. LLAMA_LOG_WARN("warning: posix_fadvise(.., POSIX_FADV_SEQUENTIAL) failed: %s\n",
  1048. strerror(errno));
  1049. }
  1050. if (prefetch) { flags |= MAP_POPULATE; }
  1051. #endif
  1052. addr = mmap(NULL, file->size, PROT_READ, flags, fd, 0);
  1053. if (addr == MAP_FAILED) { // NOLINT
  1054. throw std::runtime_error(format("mmap failed: %s", strerror(errno)));
  1055. }
  1056. if (prefetch > 0) {
  1057. // advise the kernel to preload the mapped memory
  1058. if (posix_madvise(addr, std::min(file->size, prefetch), POSIX_MADV_WILLNEED)) {
  1059. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_WILLNEED) failed: %s\n",
  1060. strerror(errno));
  1061. }
  1062. }
  1063. if (numa) {
  1064. // advise the kernel not to use readahead
  1065. // (because the next page might not belong on the same node)
  1066. if (posix_madvise(addr, file->size, POSIX_MADV_RANDOM)) {
  1067. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_RANDOM) failed: %s\n",
  1068. strerror(errno));
  1069. }
  1070. }
  1071. // initialize list of mapped_fragments
  1072. mapped_fragments.emplace_back(0, file->size);
  1073. }
  1074. static void align_range(size_t * first, size_t * last, size_t page_size) {
  1075. // align first to the next page
  1076. size_t offset_in_page = *first & (page_size - 1);
  1077. size_t offset_to_page = offset_in_page == 0 ? 0 : page_size - offset_in_page;
  1078. *first += offset_to_page;
  1079. // align last to the previous page
  1080. *last = *last & ~(page_size - 1);
  1081. if (*last <= *first) {
  1082. *last = *first;
  1083. }
  1084. }
  1085. // partially unmap the file in the range [first, last)
  1086. void unmap_fragment(size_t first, size_t last) {
  1087. // note: this function must not be called multiple times with overlapping ranges
  1088. // otherwise, there is a risk of invalidating addresses that have been repurposed for other mappings
  1089. int page_size = sysconf(_SC_PAGESIZE);
  1090. align_range(&first, &last, page_size);
  1091. size_t len = last - first;
  1092. if (len == 0) {
  1093. return;
  1094. }
  1095. GGML_ASSERT(first % page_size == 0);
  1096. GGML_ASSERT(last % page_size == 0);
  1097. GGML_ASSERT(last > first);
  1098. void * next_page_start = (uint8_t *) addr + first;
  1099. // unmap the range
  1100. if (munmap(next_page_start, len)) {
  1101. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  1102. }
  1103. // update the list of mapped fragments to avoid unmapping the same range again in the destructor
  1104. std::vector<std::pair<size_t, size_t>> new_mapped_fragments;
  1105. for (const auto & frag : mapped_fragments) {
  1106. if (frag.first < first && frag.second > last) {
  1107. // the range is in the middle of the fragment, split it
  1108. new_mapped_fragments.emplace_back(frag.first, first);
  1109. new_mapped_fragments.emplace_back(last, frag.second);
  1110. } else if (frag.first < first && frag.second > first) {
  1111. // the range starts in the middle of the fragment
  1112. new_mapped_fragments.emplace_back(frag.first, first);
  1113. } else if (frag.first < last && frag.second > last) {
  1114. // the range ends in the middle of the fragment
  1115. new_mapped_fragments.emplace_back(last, frag.second);
  1116. } else if (frag.first >= first && frag.second <= last) {
  1117. // the range covers the entire fragment
  1118. } else {
  1119. // the range is outside the fragment
  1120. new_mapped_fragments.push_back(frag);
  1121. }
  1122. }
  1123. mapped_fragments = std::move(new_mapped_fragments);
  1124. }
  1125. ~llama_mmap() {
  1126. for (const auto & frag : mapped_fragments) {
  1127. if (munmap((char *) addr + frag.first, frag.second - frag.first)) {
  1128. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  1129. }
  1130. }
  1131. }
  1132. #elif defined(_WIN32)
  1133. static constexpr bool SUPPORTED = true;
  1134. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1, bool numa = false) {
  1135. GGML_UNUSED(numa);
  1136. size = file->size;
  1137. HANDLE hFile = (HANDLE) _get_osfhandle(_fileno(file->fp));
  1138. HANDLE hMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
  1139. if (hMapping == NULL) {
  1140. DWORD error = GetLastError();
  1141. throw std::runtime_error(format("CreateFileMappingA failed: %s", llama_format_win_err(error).c_str()));
  1142. }
  1143. addr = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
  1144. DWORD error = GetLastError();
  1145. CloseHandle(hMapping);
  1146. if (addr == NULL) {
  1147. throw std::runtime_error(format("MapViewOfFile failed: %s", llama_format_win_err(error).c_str()));
  1148. }
  1149. if (prefetch > 0) {
  1150. #if _WIN32_WINNT >= 0x602
  1151. // PrefetchVirtualMemory is only present on Windows 8 and above, so we dynamically load it
  1152. BOOL (WINAPI *pPrefetchVirtualMemory) (HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG);
  1153. HMODULE hKernel32 = GetModuleHandleW(L"kernel32.dll");
  1154. // may fail on pre-Windows 8 systems
  1155. pPrefetchVirtualMemory = reinterpret_cast<decltype(pPrefetchVirtualMemory)> (GetProcAddress(hKernel32, "PrefetchVirtualMemory"));
  1156. if (pPrefetchVirtualMemory) {
  1157. // advise the kernel to preload the mapped memory
  1158. WIN32_MEMORY_RANGE_ENTRY range;
  1159. range.VirtualAddress = addr;
  1160. range.NumberOfBytes = (SIZE_T) std::min(size, prefetch);
  1161. if (!pPrefetchVirtualMemory(GetCurrentProcess(), 1, &range, 0)) {
  1162. LLAMA_LOG_WARN("warning: PrefetchVirtualMemory failed: %s\n",
  1163. llama_format_win_err(GetLastError()).c_str());
  1164. }
  1165. }
  1166. #else
  1167. throw std::runtime_error("PrefetchVirtualMemory unavailable");
  1168. #endif
  1169. }
  1170. }
  1171. void unmap_fragment(size_t first, size_t last) {
  1172. // not supported
  1173. GGML_UNUSED(first);
  1174. GGML_UNUSED(last);
  1175. }
  1176. ~llama_mmap() {
  1177. if (!UnmapViewOfFile(addr)) {
  1178. LLAMA_LOG_WARN("warning: UnmapViewOfFile failed: %s\n",
  1179. llama_format_win_err(GetLastError()).c_str());
  1180. }
  1181. }
  1182. #else
  1183. static constexpr bool SUPPORTED = false;
  1184. llama_mmap(struct llama_file * file, size_t prefetch = -1, bool numa = false) {
  1185. GGML_UNUSED(file);
  1186. GGML_UNUSED(prefetch);
  1187. GGML_UNUSED(numa);
  1188. throw std::runtime_error("mmap not supported");
  1189. }
  1190. void unmap_fragment(size_t first, size_t last) {
  1191. GGML_UNUSED(first);
  1192. GGML_UNUSED(last);
  1193. throw std::runtime_error("mmap not supported");
  1194. }
  1195. #endif
  1196. };
  1197. // Represents some region of memory being locked using mlock or VirtualLock;
  1198. // will automatically unlock on destruction.
  1199. struct llama_mlock {
  1200. void * addr = NULL;
  1201. size_t size = 0;
  1202. bool failed_already = false;
  1203. llama_mlock() {}
  1204. llama_mlock(const llama_mlock &) = delete;
  1205. ~llama_mlock() {
  1206. if (size) {
  1207. raw_unlock(addr, size);
  1208. }
  1209. }
  1210. void init(void * ptr) {
  1211. GGML_ASSERT(addr == NULL && size == 0); // NOLINT
  1212. addr = ptr;
  1213. }
  1214. void grow_to(size_t target_size) {
  1215. GGML_ASSERT(addr);
  1216. if (failed_already) {
  1217. return;
  1218. }
  1219. size_t granularity = lock_granularity();
  1220. target_size = (target_size + granularity - 1) & ~(granularity - 1);
  1221. if (target_size > size) {
  1222. if (raw_lock((uint8_t *) addr + size, target_size - size)) {
  1223. size = target_size;
  1224. } else {
  1225. failed_already = true;
  1226. }
  1227. }
  1228. }
  1229. #ifdef _POSIX_MEMLOCK_RANGE
  1230. static constexpr bool SUPPORTED = true;
  1231. static size_t lock_granularity() {
  1232. return (size_t) sysconf(_SC_PAGESIZE);
  1233. }
  1234. #ifdef __APPLE__
  1235. #define MLOCK_SUGGESTION \
  1236. "Try increasing the sysctl values 'vm.user_wire_limit' and 'vm.global_user_wire_limit' and/or " \
  1237. "decreasing 'vm.global_no_user_wire_amount'. Also try increasing RLIMIT_MEMLOCK (ulimit -l).\n"
  1238. #else
  1239. #define MLOCK_SUGGESTION \
  1240. "Try increasing RLIMIT_MEMLOCK ('ulimit -l' as root).\n"
  1241. #endif
  1242. bool raw_lock(const void * addr, size_t size) const {
  1243. if (!mlock(addr, size)) {
  1244. return true;
  1245. }
  1246. char* errmsg = std::strerror(errno);
  1247. bool suggest = (errno == ENOMEM);
  1248. // Check if the resource limit is fine after all
  1249. struct rlimit lock_limit;
  1250. if (suggest && getrlimit(RLIMIT_MEMLOCK, &lock_limit)) {
  1251. suggest = false;
  1252. }
  1253. if (suggest && (lock_limit.rlim_max > lock_limit.rlim_cur + size)) {
  1254. suggest = false;
  1255. }
  1256. LLAMA_LOG_WARN("warning: failed to mlock %zu-byte buffer (after previously locking %zu bytes): %s\n%s",
  1257. size, this->size, errmsg, suggest ? MLOCK_SUGGESTION : "");
  1258. return false;
  1259. }
  1260. #undef MLOCK_SUGGESTION
  1261. static void raw_unlock(void * addr, size_t size) {
  1262. if (munlock(addr, size)) {
  1263. LLAMA_LOG_WARN("warning: failed to munlock buffer: %s\n", std::strerror(errno));
  1264. }
  1265. }
  1266. #elif defined(_WIN32)
  1267. static constexpr bool SUPPORTED = true;
  1268. static size_t lock_granularity() {
  1269. SYSTEM_INFO si;
  1270. GetSystemInfo(&si);
  1271. return (size_t) si.dwPageSize;
  1272. }
  1273. bool raw_lock(void * ptr, size_t len) const {
  1274. for (int tries = 1; ; tries++) {
  1275. if (VirtualLock(ptr, len)) {
  1276. return true;
  1277. }
  1278. if (tries == 2) {
  1279. LLAMA_LOG_WARN("warning: failed to VirtualLock %zu-byte buffer (after previously locking %zu bytes): %s\n",
  1280. len, size, llama_format_win_err(GetLastError()).c_str());
  1281. return false;
  1282. }
  1283. // It failed but this was only the first try; increase the working
  1284. // set size and try again.
  1285. SIZE_T min_ws_size, max_ws_size;
  1286. if (!GetProcessWorkingSetSize(GetCurrentProcess(), &min_ws_size, &max_ws_size)) {
  1287. LLAMA_LOG_WARN("warning: GetProcessWorkingSetSize failed: %s\n",
  1288. llama_format_win_err(GetLastError()).c_str());
  1289. return false;
  1290. }
  1291. // Per MSDN: "The maximum number of pages that a process can lock
  1292. // is equal to the number of pages in its minimum working set minus
  1293. // a small overhead."
  1294. // Hopefully a megabyte is enough overhead:
  1295. size_t increment = len + 1048576;
  1296. // The minimum must be <= the maximum, so we need to increase both:
  1297. min_ws_size += increment;
  1298. max_ws_size += increment;
  1299. if (!SetProcessWorkingSetSize(GetCurrentProcess(), min_ws_size, max_ws_size)) {
  1300. LLAMA_LOG_WARN("warning: SetProcessWorkingSetSize failed: %s\n",
  1301. llama_format_win_err(GetLastError()).c_str());
  1302. return false;
  1303. }
  1304. }
  1305. }
  1306. static void raw_unlock(void * ptr, size_t len) {
  1307. if (!VirtualUnlock(ptr, len)) {
  1308. LLAMA_LOG_WARN("warning: failed to VirtualUnlock buffer: %s\n",
  1309. llama_format_win_err(GetLastError()).c_str());
  1310. }
  1311. }
  1312. #else
  1313. static constexpr bool SUPPORTED = false;
  1314. static size_t lock_granularity() {
  1315. return (size_t) 65536;
  1316. }
  1317. bool raw_lock(const void * addr, size_t len) const {
  1318. LLAMA_LOG_WARN("warning: mlock not supported on this system\n");
  1319. return false;
  1320. }
  1321. static void raw_unlock(const void * addr, size_t len) {}
  1322. #endif
  1323. };
  1324. static std::string llama_token_to_piece(const struct llama_context * ctx, llama_token token) {
  1325. std::vector<char> result(8, 0);
  1326. const int n_tokens = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1327. if (n_tokens < 0) {
  1328. result.resize(-n_tokens);
  1329. int check = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1330. GGML_ASSERT(check == -n_tokens);
  1331. }
  1332. else {
  1333. result.resize(n_tokens);
  1334. }
  1335. return std::string(result.data(), result.size());
  1336. }
  1337. static ggml_backend_buffer_type_t llama_default_buffer_type_cpu(bool host_buffer) {
  1338. ggml_backend_buffer_type_t buft = nullptr;
  1339. #if defined(GGML_USE_CUBLAS)
  1340. // host buffers should only be used when data is expected to be copied to/from the GPU
  1341. if (host_buffer) {
  1342. buft = ggml_backend_cuda_host_buffer_type();
  1343. }
  1344. #elif defined(GGML_USE_SYCL)
  1345. if (host_buffer) {
  1346. buft = ggml_backend_sycl_host_buffer_type();
  1347. }
  1348. #elif defined(GGML_USE_CPU_HBM)
  1349. buft = ggml_backend_cpu_hbm_buffer_type();
  1350. #elif defined(GGML_USE_VULKAN)
  1351. if (host_buffer) {
  1352. buft = ggml_backend_vk_host_buffer_type();
  1353. }
  1354. #endif
  1355. if (buft == nullptr) {
  1356. buft = ggml_backend_cpu_buffer_type();
  1357. }
  1358. return buft;
  1359. GGML_UNUSED(host_buffer);
  1360. }
  1361. static ggml_backend_buffer_type_t llama_default_buffer_type_offload(int gpu) {
  1362. ggml_backend_buffer_type_t buft = nullptr;
  1363. #ifdef GGML_USE_METAL
  1364. buft = ggml_backend_metal_buffer_type();
  1365. #elif defined(GGML_USE_CUBLAS)
  1366. buft = ggml_backend_cuda_buffer_type(gpu);
  1367. #elif defined(GGML_USE_VULKAN)
  1368. buft = ggml_backend_vk_buffer_type(gpu);
  1369. #elif defined(GGML_USE_SYCL)
  1370. buft = ggml_backend_sycl_buffer_type(gpu);
  1371. #elif defined(GGML_USE_CLBLAST)
  1372. buft = ggml_backend_opencl_buffer_type();
  1373. #elif defined(GGML_USE_KOMPUTE)
  1374. buft = ggml_backend_kompute_buffer_type(gpu);
  1375. if (buft == nullptr) {
  1376. LLAMA_LOG_WARN("%s: cannot use GPU %d, check `vulkaninfo --summary`\n", __func__, gpu);
  1377. }
  1378. #endif
  1379. if (buft == nullptr) {
  1380. buft = llama_default_buffer_type_cpu(true);
  1381. }
  1382. return buft;
  1383. GGML_UNUSED(gpu);
  1384. }
  1385. static ggml_backend_buffer_type_t llama_default_buffer_type_split(int fallback_gpu, const float * tensor_split) {
  1386. ggml_backend_buffer_type_t buft = nullptr;
  1387. #ifdef GGML_USE_CUBLAS
  1388. if (ggml_backend_cuda_get_device_count() > 1) {
  1389. buft = ggml_backend_cuda_split_buffer_type(tensor_split);
  1390. }
  1391. #endif
  1392. #ifdef GGML_USE_SYCL
  1393. if (ggml_backend_sycl_get_device_count() > 1) {
  1394. buft = ggml_backend_sycl_split_buffer_type(tensor_split);
  1395. }
  1396. #endif
  1397. if (buft == nullptr) {
  1398. buft = llama_default_buffer_type_offload(fallback_gpu);
  1399. }
  1400. return buft;
  1401. GGML_UNUSED(tensor_split);
  1402. }
  1403. static size_t llama_get_device_count() {
  1404. #if defined(GGML_USE_CUBLAS)
  1405. return ggml_backend_cuda_get_device_count();
  1406. #elif defined(GGML_USE_SYCL)
  1407. return ggml_backend_sycl_get_device_count();
  1408. #elif defined(GGML_USE_VULKAN)
  1409. return ggml_backend_vk_get_device_count();
  1410. #else
  1411. return 1;
  1412. #endif
  1413. }
  1414. static size_t llama_get_device_memory(int device) {
  1415. #if defined(GGML_USE_CUBLAS)
  1416. size_t total;
  1417. size_t free;
  1418. ggml_backend_cuda_get_device_memory(device, &total, &free);
  1419. return free;
  1420. #elif defined(GGML_USE_SYCL)
  1421. size_t total;
  1422. size_t free;
  1423. ggml_backend_sycl_get_device_memory(device, &total, &free);
  1424. return free;
  1425. #elif defined(GGML_USE_VULKAN)
  1426. size_t total;
  1427. size_t free;
  1428. ggml_backend_vk_get_device_memory(device, &total, &free);
  1429. return free;
  1430. #else
  1431. return 1;
  1432. GGML_UNUSED(device);
  1433. #endif
  1434. }
  1435. //
  1436. // globals
  1437. //
  1438. struct llama_state {
  1439. llama_state() {
  1440. #ifdef GGML_USE_METAL
  1441. ggml_backend_metal_log_set_callback(log_callback, log_callback_user_data);
  1442. #endif
  1443. }
  1444. // We save the log callback globally
  1445. ggml_log_callback log_callback = llama_log_callback_default;
  1446. void * log_callback_user_data = nullptr;
  1447. };
  1448. static llama_state g_state;
  1449. // available llama models
  1450. enum e_model {
  1451. MODEL_UNKNOWN,
  1452. MODEL_17M,
  1453. MODEL_22M,
  1454. MODEL_33M,
  1455. MODEL_109M,
  1456. MODEL_137M,
  1457. MODEL_335M,
  1458. MODEL_0_5B,
  1459. MODEL_1B,
  1460. MODEL_2B,
  1461. MODEL_3B,
  1462. MODEL_4B,
  1463. MODEL_7B,
  1464. MODEL_8B,
  1465. MODEL_13B,
  1466. MODEL_14B,
  1467. MODEL_15B,
  1468. MODEL_20B,
  1469. MODEL_30B,
  1470. MODEL_34B,
  1471. MODEL_35B,
  1472. MODEL_40B,
  1473. MODEL_65B,
  1474. MODEL_70B,
  1475. MODEL_SMALL,
  1476. MODEL_MEDIUM,
  1477. MODEL_LARGE,
  1478. MODEL_XL,
  1479. };
  1480. static const size_t kiB = 1024;
  1481. static const size_t MiB = 1024*kiB;
  1482. static const size_t GiB = 1024*MiB;
  1483. struct llama_hparams {
  1484. bool vocab_only;
  1485. bool rope_finetuned;
  1486. uint32_t n_vocab;
  1487. uint32_t n_ctx_train; // context size the model was trained on
  1488. uint32_t n_embd;
  1489. uint32_t n_head;
  1490. uint32_t n_head_kv;
  1491. uint32_t n_layer;
  1492. uint32_t n_rot;
  1493. 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
  1494. uint32_t n_embd_head_v; // dimension of values (d_v) aka n_embd_head
  1495. uint32_t n_ff;
  1496. uint32_t n_expert = 0;
  1497. uint32_t n_expert_used = 0;
  1498. uint32_t n_vocab_type = 0; // for BERT-style token types
  1499. float f_norm_eps;
  1500. float f_norm_rms_eps;
  1501. float rope_freq_base_train;
  1502. float rope_freq_scale_train;
  1503. uint32_t n_yarn_orig_ctx;
  1504. // for State Space Models
  1505. uint32_t ssm_d_conv = 0;
  1506. uint32_t ssm_d_inner = 0;
  1507. uint32_t ssm_d_state = 0;
  1508. uint32_t ssm_dt_rank = 0;
  1509. float f_clamp_kqv = 0.0f;
  1510. float f_max_alibi_bias = 0.0f;
  1511. float f_logit_scale = 0.0f;
  1512. bool causal_attn = true;
  1513. bool need_kq_pos = false;
  1514. enum llama_pooling_type pooling_type = LLAMA_POOLING_TYPE_NONE;
  1515. enum llama_rope_type rope_type = LLAMA_ROPE_TYPE_NONE;
  1516. enum llama_rope_scaling_type rope_scaling_type_train = LLAMA_ROPE_SCALING_TYPE_NONE;
  1517. bool operator!=(const llama_hparams & other) const {
  1518. if (this->vocab_only != other.vocab_only) return true;
  1519. if (this->n_vocab != other.n_vocab) return true;
  1520. if (this->n_ctx_train != other.n_ctx_train) return true;
  1521. if (this->n_embd != other.n_embd) return true;
  1522. if (this->n_head != other.n_head) return true;
  1523. if (this->n_head_kv != other.n_head_kv) return true;
  1524. if (this->n_layer != other.n_layer) return true;
  1525. if (this->n_rot != other.n_rot) return true;
  1526. if (this->n_embd_head_k != other.n_embd_head_k) return true;
  1527. if (this->n_embd_head_v != other.n_embd_head_v) return true;
  1528. if (this->n_ff != other.n_ff) return true;
  1529. if (this->n_expert != other.n_expert) return true;
  1530. if (this->n_expert_used != other.n_expert_used) return true;
  1531. if (this->rope_finetuned != other.rope_finetuned) return true;
  1532. if (this->n_yarn_orig_ctx != other.n_yarn_orig_ctx) return true;
  1533. if (this->ssm_d_conv != other.ssm_d_conv) return true;
  1534. if (this->ssm_d_inner != other.ssm_d_inner) return true;
  1535. if (this->ssm_d_state != other.ssm_d_state) return true;
  1536. if (this->ssm_dt_rank != other.ssm_dt_rank) return true;
  1537. const float EPSILON = 1e-9f;
  1538. if (!is_float_close(this->f_norm_eps, other.f_norm_eps, EPSILON)) return true;
  1539. if (!is_float_close(this->f_norm_rms_eps, other.f_norm_rms_eps, EPSILON)) return true;
  1540. if (!is_float_close(this->rope_freq_base_train, other.rope_freq_base_train, EPSILON)) return true;
  1541. if (!is_float_close(this->rope_freq_scale_train, other.rope_freq_scale_train, EPSILON)) return true;
  1542. return false;
  1543. }
  1544. uint32_t n_gqa() const {
  1545. if (n_head_kv == 0) {
  1546. return 0;
  1547. }
  1548. return n_head/n_head_kv;
  1549. }
  1550. uint32_t n_embd_k_gqa() const { // dimension of key embeddings across all k-v heads
  1551. return n_embd_head_k * n_head_kv;
  1552. }
  1553. uint32_t n_embd_v_gqa() const { // dimension of value embeddings across all k-v heads
  1554. return n_embd_head_v * n_head_kv;
  1555. }
  1556. uint32_t n_embd_k_s() const { // dimension of the rolling state embeddings
  1557. // corresponds to Mamba's conv_states size
  1558. // TODO: maybe support other convolution strides than 1
  1559. // NOTE: since the first column of the conv_state is shifted out each time, it's not actually needed
  1560. return (ssm_d_conv > 0 ? ssm_d_conv - 1 : 0) * ssm_d_inner;
  1561. }
  1562. uint32_t n_embd_v_s() const { // dimension of the recurrent state embeddings
  1563. // corresponds to Mamba's ssm_states size
  1564. return ssm_d_state * ssm_d_inner;
  1565. }
  1566. };
  1567. struct llama_cparams {
  1568. uint32_t n_ctx; // context size used during inference
  1569. uint32_t n_batch;
  1570. uint32_t n_ubatch;
  1571. uint32_t n_threads; // number of threads to use for generation
  1572. uint32_t n_threads_batch; // number of threads to use for batch processing
  1573. float rope_freq_base;
  1574. float rope_freq_scale;
  1575. uint32_t n_yarn_orig_ctx;
  1576. // These hyperparameters are not exposed in GGUF, because all
  1577. // existing YaRN models use the same values for them.
  1578. float yarn_ext_factor;
  1579. float yarn_attn_factor;
  1580. float yarn_beta_fast;
  1581. float yarn_beta_slow;
  1582. float defrag_thold;
  1583. bool embeddings;
  1584. bool causal_attn;
  1585. bool offload_kqv;
  1586. enum llama_pooling_type pooling_type;
  1587. ggml_backend_sched_eval_callback cb_eval;
  1588. void * cb_eval_user_data;
  1589. };
  1590. struct llama_layer {
  1591. // normalization
  1592. struct ggml_tensor * attn_norm;
  1593. struct ggml_tensor * attn_norm_b;
  1594. struct ggml_tensor * attn_norm_2;
  1595. struct ggml_tensor * attn_norm_2_b;
  1596. struct ggml_tensor * attn_q_norm;
  1597. struct ggml_tensor * attn_q_norm_b;
  1598. struct ggml_tensor * attn_k_norm;
  1599. struct ggml_tensor * attn_k_norm_b;
  1600. struct ggml_tensor * attn_out_norm;
  1601. struct ggml_tensor * attn_out_norm_b;
  1602. // attention
  1603. struct ggml_tensor * wq;
  1604. struct ggml_tensor * wk;
  1605. struct ggml_tensor * wv;
  1606. struct ggml_tensor * wo;
  1607. struct ggml_tensor * wqkv;
  1608. // attention bias
  1609. struct ggml_tensor * bq;
  1610. struct ggml_tensor * bk;
  1611. struct ggml_tensor * bv;
  1612. struct ggml_tensor * bo;
  1613. struct ggml_tensor * bqkv;
  1614. // normalization
  1615. struct ggml_tensor * ffn_norm;
  1616. struct ggml_tensor * ffn_norm_b;
  1617. struct ggml_tensor * layer_out_norm;
  1618. struct ggml_tensor * layer_out_norm_b;
  1619. // ff
  1620. struct ggml_tensor * ffn_gate; // w1
  1621. struct ggml_tensor * ffn_down; // w2
  1622. struct ggml_tensor * ffn_up; // w3
  1623. // ff MoE
  1624. struct ggml_tensor * ffn_gate_inp;
  1625. struct ggml_tensor * ffn_gate_exp[LLAMA_MAX_EXPERTS];
  1626. struct ggml_tensor * ffn_down_exp[LLAMA_MAX_EXPERTS];
  1627. struct ggml_tensor * ffn_up_exp [LLAMA_MAX_EXPERTS];
  1628. // ff bias
  1629. struct ggml_tensor * ffn_down_b; // b2
  1630. struct ggml_tensor * ffn_up_b; // b3
  1631. struct ggml_tensor * ffn_act;
  1632. // mamba proj
  1633. struct ggml_tensor * ssm_in;
  1634. struct ggml_tensor * ssm_x;
  1635. struct ggml_tensor * ssm_dt;
  1636. struct ggml_tensor * ssm_out;
  1637. // mamba
  1638. struct ggml_tensor * ssm_conv1d;
  1639. struct ggml_tensor * ssm_a;
  1640. struct ggml_tensor * ssm_d;
  1641. // mamba bias
  1642. struct ggml_tensor * ssm_conv1d_b;
  1643. struct ggml_tensor * ssm_dt_b;
  1644. };
  1645. struct llama_kv_cell {
  1646. llama_pos pos = -1;
  1647. llama_pos delta = 0;
  1648. int32_t src = 0; // used by recurrent state models to copy states
  1649. std::set<llama_seq_id> seq_id;
  1650. bool has_seq_id(const llama_seq_id & id) const {
  1651. return seq_id.find(id) != seq_id.end();
  1652. }
  1653. bool is_empty() const {
  1654. return seq_id.empty();
  1655. }
  1656. bool is_same_seq(const llama_kv_cell & other) const {
  1657. return seq_id == other.seq_id;
  1658. }
  1659. };
  1660. // ring-buffer of cached KV data
  1661. struct llama_kv_cache {
  1662. bool has_shift = false;
  1663. bool do_defrag = false;
  1664. bool do_copy = false;
  1665. // with recurrent state models, a cell can hold the state for more than one past token
  1666. bool recurrent = false;
  1667. // Note: The value of head isn't only used to optimize searching
  1668. // for a free KV slot. llama_decode_internal also uses it, so it
  1669. // cannot be freely changed after a slot has been allocated.
  1670. uint32_t head = 0;
  1671. uint32_t size = 0;
  1672. uint32_t used = 0; // used cells (i.e. at least one seq_id)
  1673. // computed before each graph build
  1674. uint32_t n = 0;
  1675. ggml_type type_k = GGML_TYPE_F16;
  1676. ggml_type type_v = GGML_TYPE_F16;
  1677. std::vector<llama_kv_cell> cells;
  1678. std::vector<struct ggml_tensor *> k_l; // per layer
  1679. std::vector<struct ggml_tensor *> v_l;
  1680. std::vector<struct ggml_context *> ctxs;
  1681. std::vector<ggml_backend_buffer_t> bufs;
  1682. size_t total_size() const {
  1683. size_t size = 0;
  1684. for (ggml_backend_buffer_t buf : bufs) {
  1685. size += ggml_backend_buffer_get_size(buf);
  1686. }
  1687. return size;
  1688. }
  1689. ~llama_kv_cache() {
  1690. for (struct ggml_context * ctx : ctxs) {
  1691. ggml_free(ctx);
  1692. }
  1693. for (ggml_backend_buffer_t buf : bufs) {
  1694. ggml_backend_buffer_free(buf);
  1695. }
  1696. }
  1697. };
  1698. struct llama_control_vector {
  1699. std::vector<struct ggml_tensor *> tensors; // per layer
  1700. std::vector<struct ggml_context *> ctxs;
  1701. std::vector<ggml_backend_buffer_t> bufs;
  1702. int32_t layer_start = -1;
  1703. int32_t layer_end = -1;
  1704. ggml_tensor * tensor_for(int il) const {
  1705. if (il < 0 || il < layer_start || il > layer_end || (size_t) il >= tensors.size()) {
  1706. return nullptr;
  1707. }
  1708. return tensors[il];
  1709. }
  1710. ~llama_control_vector() {
  1711. for (struct ggml_context * ctx : ctxs) {
  1712. ggml_free(ctx);
  1713. }
  1714. for (ggml_backend_buffer_t buf : bufs) {
  1715. ggml_backend_buffer_free(buf);
  1716. }
  1717. }
  1718. };
  1719. struct llama_vocab {
  1720. using id = int32_t;
  1721. using token = std::string;
  1722. using ttype = llama_token_type;
  1723. struct token_data {
  1724. token text;
  1725. float score;
  1726. ttype type;
  1727. };
  1728. enum llama_vocab_type type = LLAMA_VOCAB_TYPE_SPM;
  1729. std::unordered_map<token, id> token_to_id;
  1730. std::vector<token_data> id_to_token;
  1731. std::unordered_map<token, id> special_tokens_cache;
  1732. std::map<std::pair<std::string, std::string>, int> bpe_ranks;
  1733. // default LLaMA special tokens
  1734. id special_bos_id = 1;
  1735. id special_eos_id = 2;
  1736. id special_unk_id = 0;
  1737. id special_sep_id = -1;
  1738. id special_pad_id = -1;
  1739. int special_add_bos = -1; // -1 unknown, 1 add, 0 don't add.
  1740. int special_add_eos = -1; // -1 unknown, 1 add, 0 don't add.
  1741. id linefeed_id = 13;
  1742. id special_prefix_id = 32007;
  1743. id special_middle_id = 32009;
  1744. id special_suffix_id = 32008;
  1745. id special_eot_id = 32010;
  1746. bool add_space_prefix = true;
  1747. int find_bpe_rank(const std::string & token_left, const std::string & token_right) const {
  1748. GGML_ASSERT(token_left.find(' ') == std::string::npos);
  1749. GGML_ASSERT(token_left.find('\n') == std::string::npos);
  1750. GGML_ASSERT(token_right.find(' ') == std::string::npos);
  1751. GGML_ASSERT(token_right.find('\n') == std::string::npos);
  1752. auto it = bpe_ranks.find(std::make_pair(token_left, token_right));
  1753. if (it == bpe_ranks.end()) {
  1754. return -1;
  1755. }
  1756. return it->second;
  1757. }
  1758. };
  1759. struct llama_model {
  1760. e_model type = MODEL_UNKNOWN;
  1761. llm_arch arch = LLM_ARCH_UNKNOWN;
  1762. llama_ftype ftype = LLAMA_FTYPE_ALL_F32;
  1763. std::string name = "n/a";
  1764. llama_hparams hparams = {};
  1765. llama_vocab vocab;
  1766. struct ggml_tensor * tok_embd;
  1767. struct ggml_tensor * type_embd;
  1768. struct ggml_tensor * pos_embd;
  1769. struct ggml_tensor * tok_norm;
  1770. struct ggml_tensor * tok_norm_b;
  1771. struct ggml_tensor * output_norm;
  1772. struct ggml_tensor * output_norm_b;
  1773. struct ggml_tensor * output;
  1774. struct ggml_tensor * output_b;
  1775. std::vector<llama_layer> layers;
  1776. llama_split_mode split_mode;
  1777. int main_gpu;
  1778. int n_gpu_layers;
  1779. // gguf metadata
  1780. std::unordered_map<std::string, std::string> gguf_kv;
  1781. // layer -> buffer type mapping
  1782. struct layer_buft {
  1783. layer_buft() : buft_matrix(nullptr), buft(nullptr) {}
  1784. layer_buft(ggml_backend_buffer_type_t matrix) : buft_matrix(matrix), buft(matrix) {}
  1785. layer_buft(ggml_backend_buffer_type_t matrix, ggml_backend_buffer_type_t other) : buft_matrix(matrix), buft(other) {}
  1786. ggml_backend_buffer_type_t buft_matrix; // matrices only - used by split buffers and backends that support only matrix multiplication
  1787. ggml_backend_buffer_type_t buft; // everything else
  1788. };
  1789. layer_buft buft_input;
  1790. layer_buft buft_output;
  1791. std::vector<layer_buft> buft_layer;
  1792. // contexts where the model tensors metadata is stored
  1793. std::vector<struct ggml_context *> ctxs;
  1794. // the model memory buffers for the tensor data
  1795. std::vector<ggml_backend_buffer_t> bufs;
  1796. // model memory mapped file
  1797. std::unique_ptr<llama_mmap> mapping;
  1798. // objects representing data potentially being locked in memory
  1799. std::vector<std::unique_ptr<llama_mlock>> mlock_bufs;
  1800. llama_mlock mlock_mmap;
  1801. // for quantize-stats only
  1802. std::vector<std::pair<std::string, struct ggml_tensor *>> tensors_by_name;
  1803. int64_t t_load_us = 0;
  1804. int64_t t_start_us = 0;
  1805. ~llama_model() {
  1806. for (struct ggml_context * ctx : ctxs) {
  1807. ggml_free(ctx);
  1808. }
  1809. for (ggml_backend_buffer_t buf : bufs) {
  1810. ggml_backend_buffer_free(buf);
  1811. }
  1812. }
  1813. };
  1814. struct llama_context {
  1815. llama_context(const llama_model & model) : model(model), t_start_us(model.t_start_us), t_load_us(model.t_load_us) {}
  1816. ~llama_context() {
  1817. ggml_backend_sched_free(sched);
  1818. for (ggml_backend_t backend : backends) {
  1819. ggml_backend_free(backend);
  1820. }
  1821. #ifdef GGML_USE_VULKAN
  1822. ggml_vk_free_cpu_assist();
  1823. #endif
  1824. ggml_backend_buffer_free(buf_output);
  1825. }
  1826. llama_cparams cparams;
  1827. std::vector<ggml_backend_t> backends;
  1828. #ifdef GGML_USE_METAL
  1829. ggml_backend_t backend_metal = nullptr;
  1830. #endif
  1831. ggml_backend_t backend_cpu = nullptr;
  1832. const llama_model & model;
  1833. // key + value cache for the self attention
  1834. struct llama_kv_cache kv_self;
  1835. std::mt19937 rng;
  1836. bool has_evaluated_once = false;
  1837. int64_t t_start_us;
  1838. int64_t t_load_us;
  1839. int64_t t_sample_us = 0;
  1840. int64_t t_p_eval_us = 0;
  1841. int64_t t_eval_us = 0;
  1842. int64_t t_compute_start_us = 0;
  1843. int64_t n_queued_tokens = 0;
  1844. int32_t n_sample = 0; // number of tokens sampled
  1845. int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1)
  1846. int32_t n_eval = 0; // number of eval calls
  1847. // host buffer for the model output (logits and embeddings)
  1848. ggml_backend_buffer_t buf_output = nullptr;
  1849. // decode output (2-dimensional array: [n_tokens][n_vocab])
  1850. size_t logits_size = 0;
  1851. float * logits = nullptr;
  1852. #ifndef NDEBUG
  1853. // guard against access to unset logits
  1854. std::vector<bool> logits_valid;
  1855. #endif
  1856. bool logits_all = false;
  1857. // embeddings output (2-dimensional array: [n_tokens][n_embd])
  1858. // populated only when pooling_type == LLAMA_POOLING_TYPE_NONE
  1859. size_t embd_size = 0;
  1860. float * embd = nullptr;
  1861. // sequence embeddings output (map of [n_embd] vectors)
  1862. // populated only when pooling_type != LLAMA_POOLING_TYPE_NONE
  1863. std::map<llama_seq_id, std::vector<float>> embd_seq;
  1864. // memory buffers used to evaluate the model
  1865. std::vector<uint8_t> buf_compute_meta;
  1866. ggml_backend_sched_t sched = nullptr;
  1867. ggml_abort_callback abort_callback = nullptr;
  1868. void * abort_callback_data = nullptr;
  1869. // input tensors
  1870. struct ggml_tensor * inp_tokens; // I32 [n_batch]
  1871. struct ggml_tensor * inp_embd; // F32 [n_embd, n_batch]
  1872. struct ggml_tensor * inp_pos; // I32 [n_batch]
  1873. struct ggml_tensor * inp_KQ_mask; // F32 [kv_size, n_batch]
  1874. struct ggml_tensor * inp_KQ_pos; // F32 [kv_size]
  1875. struct ggml_tensor * inp_K_shift; // I32 [kv_size]
  1876. struct ggml_tensor * inp_mean; // F32 [n_batch, n_batch]
  1877. struct ggml_tensor * inp_cls; // I32 [n_batch]
  1878. struct ggml_tensor * inp_s_copy; // I32 [kv_size]
  1879. struct ggml_tensor * inp_s_mask; // F32 [1, kv_size]
  1880. struct ggml_tensor * inp_s_seq; // I32 [kv_size, n_batch]
  1881. // control vectors
  1882. struct llama_control_vector cvec;
  1883. #ifdef GGML_USE_MPI
  1884. ggml_mpi_context * ctx_mpi = NULL;
  1885. #endif
  1886. };
  1887. //
  1888. // kv cache helpers
  1889. //
  1890. static bool llama_kv_cache_init(
  1891. struct llama_kv_cache & cache,
  1892. const llama_model & model,
  1893. ggml_type type_k,
  1894. ggml_type type_v,
  1895. uint32_t kv_size,
  1896. bool offload) {
  1897. const struct llama_hparams & hparams = model.hparams;
  1898. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  1899. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  1900. const int64_t n_layer = hparams.n_layer;
  1901. cache.has_shift = false;
  1902. // TODO: find a nicer way to add other recurrent model architectures
  1903. cache.recurrent = model.arch == LLM_ARCH_MAMBA;
  1904. // TODO: support mixed reccurent Transformer architectues
  1905. // NOTE: (!a || b) is a logical implication (a -> b)
  1906. GGML_ASSERT(!cache.recurrent || n_embd_k_gqa == hparams.n_embd_k_s());
  1907. GGML_ASSERT(!cache.recurrent || n_embd_v_gqa == hparams.n_embd_v_s());
  1908. GGML_ASSERT( cache.recurrent || n_embd_k_gqa == hparams.n_embd_k_gqa());
  1909. GGML_ASSERT( cache.recurrent || n_embd_v_gqa == hparams.n_embd_v_gqa());
  1910. cache.head = 0;
  1911. cache.size = kv_size;
  1912. cache.used = 0;
  1913. cache.type_k = type_k;
  1914. cache.type_v = type_v;
  1915. cache.cells.clear();
  1916. cache.cells.resize(kv_size);
  1917. if (cache.recurrent) {
  1918. // init state copy sources
  1919. for (uint32_t i = 0; i < cache.size; ++i) {
  1920. cache.cells[i].src = i;
  1921. }
  1922. }
  1923. #ifdef GGML_USE_CLBLAST
  1924. offload = false;
  1925. #endif
  1926. // count used buffer types
  1927. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  1928. if (offload) {
  1929. for (int64_t i = 0; i < n_layer; ++i) {
  1930. buft_layer_count[model.buft_layer[i].buft]++;
  1931. }
  1932. } else {
  1933. buft_layer_count[llama_default_buffer_type_cpu(true)] = n_layer;
  1934. }
  1935. // create a context for each buffer type
  1936. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  1937. for (auto & it : buft_layer_count) {
  1938. int n_layers = it.second;
  1939. struct ggml_init_params params = {
  1940. /*.mem_size =*/ 2u*n_layers*ggml_tensor_overhead(),
  1941. /*.mem_buffer =*/ NULL,
  1942. /*.no_alloc =*/ true,
  1943. };
  1944. ggml_context * ctx = ggml_init(params);
  1945. if (!ctx) {
  1946. LLAMA_LOG_ERROR("%s: failed to allocate context for kv cache\n", __func__);
  1947. return false;
  1948. }
  1949. ctx_map[it.first] = ctx;
  1950. cache.ctxs.push_back(ctx);
  1951. }
  1952. cache.k_l.reserve(n_layer);
  1953. cache.v_l.reserve(n_layer);
  1954. for (int i = 0; i < (int) n_layer; i++) {
  1955. struct ggml_context * ctx = offload ? ctx_map.at(model.buft_layer[i].buft) : cache.ctxs.front();
  1956. ggml_tensor * k = ggml_new_tensor_1d(ctx, type_k, n_embd_k_gqa*kv_size);
  1957. ggml_tensor * v = ggml_new_tensor_1d(ctx, type_v, n_embd_v_gqa*kv_size);
  1958. ggml_format_name(k, "cache_k_l%d", i);
  1959. ggml_format_name(v, "cache_v_l%d", i);
  1960. cache.k_l.push_back(k);
  1961. cache.v_l.push_back(v);
  1962. }
  1963. // allocate tensors and initialize the buffers to avoid NaNs in the padding
  1964. for (auto it : ctx_map) {
  1965. ggml_backend_buffer_type_t buft = it.first;
  1966. ggml_context * ctx = it.second;
  1967. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  1968. if (!buf) {
  1969. LLAMA_LOG_ERROR("%s: failed to allocate buffer for kv cache\n", __func__);
  1970. return false;
  1971. }
  1972. ggml_backend_buffer_clear(buf, 0);
  1973. 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);
  1974. cache.bufs.push_back(buf);
  1975. }
  1976. return true;
  1977. }
  1978. // find an empty slot of size "n_tokens" in the cache
  1979. // updates the cache head
  1980. // Note: On success, it's important that cache.head points
  1981. // to the first cell of the slot.
  1982. static bool llama_kv_cache_find_slot(
  1983. struct llama_kv_cache & cache,
  1984. const struct llama_batch & batch) {
  1985. const uint32_t n_ctx = cache.size;
  1986. const uint32_t n_tokens = batch.n_tokens;
  1987. if (cache.recurrent) {
  1988. // For recurrent state architectures (like Mamba),
  1989. // each KV cache cell can store the state for a whole sequence.
  1990. llama_seq_id min = cache.size - 1;
  1991. llama_seq_id max = 0;
  1992. for (uint32_t i = 0; i < n_tokens; ++i) {
  1993. for (int32_t j = 0; j < batch.n_seq_id[i]; ++j) {
  1994. llama_seq_id seq_id = batch.seq_id[i][j];
  1995. // make sure it's a valid seq_id
  1996. if ((uint32_t) seq_id < cache.size) {
  1997. if (seq_id > max) {
  1998. max = seq_id;
  1999. }
  2000. if (seq_id < min) {
  2001. min = seq_id;
  2002. }
  2003. // Assuming the tokens are in-order
  2004. if (batch.pos[i] != cache.cells[seq_id].pos + 1) {
  2005. // What should happen when the pos backtracks or skips a value?
  2006. // Clearing the state mid-batch would require special-casing which isn't done.
  2007. LLAMA_LOG_WARN("%s: non-consecutive token position %d after %d for sequence %d\n",
  2008. __func__, batch.pos[i], cache.cells[seq_id].pos, seq_id);
  2009. }
  2010. if (cache.cells[seq_id].pos < 0 && 0 <= batch.pos[i]) {
  2011. cache.used += 1;
  2012. }
  2013. cache.cells[seq_id].pos = batch.pos[i];
  2014. // NOTE: seq_ids are not inserted here; they are handled when the input tensors are set
  2015. } else {
  2016. // too big seq_id
  2017. // TODO: would it be possible to resize the KV cache size instead?
  2018. LLAMA_LOG_ERROR("%s: seq_id=%d >= kv_size=%d Try using a bigger --parallel value\n", __func__, seq_id, cache.size);
  2019. return false;
  2020. }
  2021. }
  2022. }
  2023. // allow getting the range of used cells, from head to head + n
  2024. cache.head = min;
  2025. cache.n = max - min + 1;
  2026. // sanity check
  2027. return max >= min;
  2028. }
  2029. // otherwise, one cell per token.
  2030. if (n_tokens > n_ctx) {
  2031. LLAMA_LOG_ERROR("%s: n_tokens=%d > n_ctx=%d\n", __func__, n_tokens, n_ctx);
  2032. return false;
  2033. }
  2034. uint32_t n_tested = 0;
  2035. while (true) {
  2036. if (cache.head + n_tokens > n_ctx) {
  2037. n_tested += n_ctx - cache.head;
  2038. cache.head = 0;
  2039. continue;
  2040. }
  2041. bool found = true;
  2042. for (uint32_t i = 0; i < n_tokens; i++) {
  2043. if (cache.cells[cache.head + i].pos >= 0) {
  2044. found = false;
  2045. cache.head += i + 1;
  2046. n_tested += i + 1;
  2047. break;
  2048. }
  2049. }
  2050. if (found) {
  2051. break;
  2052. }
  2053. if (n_tested >= n_ctx) {
  2054. //LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens);
  2055. return false;
  2056. }
  2057. }
  2058. for (uint32_t i = 0; i < n_tokens; i++) {
  2059. cache.cells[cache.head + i].pos = batch.pos[i];
  2060. for (int32_t j = 0; j < batch.n_seq_id[i]; j++) {
  2061. cache.cells[cache.head + i].seq_id.insert(batch.seq_id[i][j]);
  2062. }
  2063. }
  2064. cache.used += n_tokens;
  2065. return true;
  2066. }
  2067. // find how many cells are currently in use
  2068. static uint32_t llama_kv_cache_cell_max(const struct llama_kv_cache & cache) {
  2069. for (uint32_t i = cache.size; i > 0; --i) {
  2070. const llama_kv_cell & cell = cache.cells[i - 1];
  2071. if (cell.pos >= 0 && !cell.is_empty()) {
  2072. return i;
  2073. }
  2074. }
  2075. return 0;
  2076. }
  2077. static void llama_kv_cache_clear(struct llama_kv_cache & cache) {
  2078. for (int32_t i = 0; i < (int32_t) cache.size; ++i) {
  2079. cache.cells[i].pos = -1;
  2080. cache.cells[i].seq_id.clear();
  2081. }
  2082. cache.head = 0;
  2083. cache.used = 0;
  2084. }
  2085. static bool llama_kv_cache_seq_rm(
  2086. struct llama_kv_cache & cache,
  2087. llama_seq_id seq_id,
  2088. llama_pos p0,
  2089. llama_pos p1) {
  2090. uint32_t new_head = cache.size;
  2091. if (p0 < 0) p0 = 0;
  2092. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2093. // models like Mamba can't have a state partially erased
  2094. if (cache.recurrent) {
  2095. if (seq_id >= (int64_t) cache.size) {
  2096. // could be fatal
  2097. return false;
  2098. }
  2099. if (0 <= seq_id) {
  2100. // partial intersection is invalid
  2101. if ((0 < p0 && p0 <= cache.cells[seq_id].pos) || (0 < p1 && p1 <= cache.cells[seq_id].pos)) {
  2102. return false;
  2103. }
  2104. } else {
  2105. // seq_id is negative, then the range should include everything or nothing
  2106. if (p0 != p1 && (p0 != 0 || p1 != std::numeric_limits<llama_pos>::max())) {
  2107. return false;
  2108. }
  2109. }
  2110. }
  2111. for (uint32_t i = 0; i < cache.size; ++i) {
  2112. if (cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2113. if (seq_id < 0) {
  2114. cache.cells[i].seq_id.clear();
  2115. } else if (cache.cells[i].has_seq_id(seq_id)) {
  2116. cache.cells[i].seq_id.erase(seq_id);
  2117. } else {
  2118. continue;
  2119. }
  2120. if (cache.cells[i].is_empty()) {
  2121. // keep count of the number of used cells
  2122. if (cache.cells[i].pos >= 0) cache.used--;
  2123. cache.cells[i].pos = -1;
  2124. if (new_head == cache.size) new_head = i;
  2125. }
  2126. }
  2127. }
  2128. // If we freed up a slot, set head to it so searching can start there.
  2129. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  2130. return true;
  2131. }
  2132. static void llama_kv_cache_seq_cp(
  2133. struct llama_kv_cache & cache,
  2134. llama_seq_id seq_id_src,
  2135. llama_seq_id seq_id_dst,
  2136. llama_pos p0,
  2137. llama_pos p1) {
  2138. if (p0 < 0) p0 = 0;
  2139. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2140. if (cache.recurrent) {
  2141. if ((uint32_t) seq_id_dst < cache.size && (uint32_t) seq_id_src < cache.size) {
  2142. seq_id_src = cache.cells[seq_id_src].src;
  2143. GGML_ASSERT((uint32_t) seq_id_src < cache.size);
  2144. // intent to "copy from"
  2145. // supports copy chains thanks to taking the source of the source
  2146. cache.cells[seq_id_dst].src = seq_id_src;
  2147. // preserve the "keep or clear" status of the copied sequence
  2148. if (cache.cells[seq_id_src].has_seq_id(seq_id_src)) {
  2149. cache.cells[seq_id_dst].seq_id.insert(seq_id_dst);
  2150. } else {
  2151. cache.cells[seq_id_dst].seq_id.erase(seq_id_dst);
  2152. }
  2153. cache.do_copy = true;
  2154. cache.cells[seq_id_dst].pos = cache.cells[seq_id_src].pos;
  2155. }
  2156. return;
  2157. }
  2158. // otherwise, this is the KV cache of a Transformer-like model
  2159. cache.head = 0;
  2160. for (uint32_t i = 0; i < cache.size; ++i) {
  2161. if (cache.cells[i].has_seq_id(seq_id_src) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2162. cache.cells[i].seq_id.insert(seq_id_dst);
  2163. }
  2164. }
  2165. }
  2166. static void llama_kv_cache_seq_keep(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  2167. uint32_t new_head = cache.size;
  2168. for (uint32_t i = 0; i < cache.size; ++i) {
  2169. if (!cache.cells[i].has_seq_id(seq_id)) {
  2170. if (cache.cells[i].pos >= 0) cache.used--;
  2171. cache.cells[i].pos = -1;
  2172. cache.cells[i].seq_id.clear();
  2173. if (new_head == cache.size) new_head = i;
  2174. } else {
  2175. cache.cells[i].seq_id.clear();
  2176. cache.cells[i].seq_id.insert(seq_id);
  2177. }
  2178. }
  2179. // If we freed up a slot, set head to it so searching can start there.
  2180. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  2181. }
  2182. static void llama_kv_cache_seq_add(
  2183. struct llama_kv_cache & cache,
  2184. llama_seq_id seq_id,
  2185. llama_pos p0,
  2186. llama_pos p1,
  2187. llama_pos delta) {
  2188. uint32_t new_head = cache.size;
  2189. if (p0 < 0) p0 = 0;
  2190. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2191. if (cache.recurrent) {
  2192. // for Mamba-like models, only the pos needs to be shifted
  2193. if (0 <= seq_id && seq_id < (int64_t) cache.size) {
  2194. llama_kv_cell & cell = cache.cells[seq_id];
  2195. if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
  2196. cell.pos += delta;
  2197. }
  2198. }
  2199. return;
  2200. }
  2201. for (uint32_t i = 0; i < cache.size; ++i) {
  2202. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2203. cache.has_shift = true;
  2204. cache.cells[i].pos += delta;
  2205. cache.cells[i].delta += delta;
  2206. if (cache.cells[i].pos < 0) {
  2207. if (!cache.cells[i].is_empty()) {
  2208. cache.used--;
  2209. }
  2210. cache.cells[i].pos = -1;
  2211. cache.cells[i].seq_id.clear();
  2212. if (new_head == cache.size) {
  2213. new_head = i;
  2214. }
  2215. }
  2216. }
  2217. }
  2218. // If we freed up a slot, set head to it so searching can start there.
  2219. // Otherwise we just start the next search from the beginning.
  2220. cache.head = new_head != cache.size ? new_head : 0;
  2221. }
  2222. static void llama_kv_cache_seq_div(
  2223. struct llama_kv_cache & cache,
  2224. llama_seq_id seq_id,
  2225. llama_pos p0,
  2226. llama_pos p1,
  2227. int d) {
  2228. if (p0 < 0) p0 = 0;
  2229. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  2230. if (cache.recurrent) {
  2231. // for Mamba-like models, only the pos needs to be changed
  2232. if (0 <= seq_id && seq_id < (int64_t) cache.size) {
  2233. llama_kv_cell & cell = cache.cells[seq_id];
  2234. if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
  2235. cell.pos /= d;
  2236. }
  2237. }
  2238. return;
  2239. }
  2240. for (uint32_t i = 0; i < cache.size; ++i) {
  2241. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  2242. cache.has_shift = true;
  2243. {
  2244. llama_pos p_old = cache.cells[i].pos;
  2245. cache.cells[i].pos /= d;
  2246. cache.cells[i].delta += cache.cells[i].pos - p_old;
  2247. }
  2248. }
  2249. }
  2250. }
  2251. static llama_pos llama_kv_cache_seq_pos_max(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  2252. llama_pos result = 0;
  2253. for (uint32_t i = 0; i < cache.size; ++i) {
  2254. if (cache.cells[i].has_seq_id(seq_id)) {
  2255. result = std::max(result, cache.cells[i].pos);
  2256. }
  2257. }
  2258. return result;
  2259. }
  2260. static void llama_kv_cache_defrag(struct llama_kv_cache & cache) {
  2261. cache.do_defrag = true;
  2262. }
  2263. //
  2264. // model loading and saving
  2265. //
  2266. enum llama_fver {
  2267. GGUF_FILE_VERSION_V1 = 1,
  2268. GGUF_FILE_VERSION_V2 = 2,
  2269. GGUF_FILE_VERSION_V3 = 3,
  2270. };
  2271. static const char * llama_file_version_name(llama_fver version) {
  2272. switch (version) {
  2273. case GGUF_FILE_VERSION_V1: return "GGUF V1 (support until nov 2023)";
  2274. case GGUF_FILE_VERSION_V2: return "GGUF V2";
  2275. case GGUF_FILE_VERSION_V3: return "GGUF V3 (latest)";
  2276. }
  2277. return "unknown";
  2278. }
  2279. static std::string llama_format_tensor_shape(const std::vector<int64_t> & ne) {
  2280. char buf[256];
  2281. snprintf(buf, sizeof(buf), "%5" PRId64, ne.at(0));
  2282. for (size_t i = 1; i < ne.size(); i++) {
  2283. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, ne.at(i));
  2284. }
  2285. return buf;
  2286. }
  2287. static std::string llama_format_tensor_shape(const struct ggml_tensor * t) {
  2288. char buf[256];
  2289. snprintf(buf, sizeof(buf), "%5" PRId64, t->ne[0]);
  2290. for (int i = 1; i < GGML_MAX_DIMS; i++) {
  2291. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, t->ne[i]);
  2292. }
  2293. return buf;
  2294. }
  2295. namespace GGUFMeta {
  2296. template <typename T, gguf_type gt_, T (*gfun)(const gguf_context *, const int)>
  2297. struct GKV_Base_Type {
  2298. static constexpr gguf_type gt = gt_;
  2299. static T getter(const gguf_context * ctx, const int kid) {
  2300. return gfun(ctx, kid);
  2301. }
  2302. };
  2303. template<typename T> struct GKV_Base;
  2304. template<> struct GKV_Base<bool >: GKV_Base_Type<bool, GGUF_TYPE_BOOL, gguf_get_val_bool> {};
  2305. template<> struct GKV_Base<uint8_t >: GKV_Base_Type<uint8_t, GGUF_TYPE_UINT8, gguf_get_val_u8 > {};
  2306. template<> struct GKV_Base<uint16_t >: GKV_Base_Type<uint16_t, GGUF_TYPE_UINT16, gguf_get_val_u16 > {};
  2307. template<> struct GKV_Base<uint32_t >: GKV_Base_Type<uint32_t, GGUF_TYPE_UINT32, gguf_get_val_u32 > {};
  2308. template<> struct GKV_Base<uint64_t >: GKV_Base_Type<uint64_t, GGUF_TYPE_UINT64, gguf_get_val_u64 > {};
  2309. template<> struct GKV_Base<int8_t >: GKV_Base_Type<int8_t, GGUF_TYPE_INT8, gguf_get_val_i8 > {};
  2310. template<> struct GKV_Base<int16_t >: GKV_Base_Type<int16_t, GGUF_TYPE_INT16, gguf_get_val_i16 > {};
  2311. template<> struct GKV_Base<int32_t >: GKV_Base_Type<int32_t, GGUF_TYPE_INT32, gguf_get_val_i32 > {};
  2312. template<> struct GKV_Base<int64_t >: GKV_Base_Type<int64_t, GGUF_TYPE_INT64, gguf_get_val_i64 > {};
  2313. template<> struct GKV_Base<float >: GKV_Base_Type<float, GGUF_TYPE_FLOAT32, gguf_get_val_f32 > {};
  2314. template<> struct GKV_Base<double >: GKV_Base_Type<double, GGUF_TYPE_FLOAT64, gguf_get_val_f64 > {};
  2315. template<> struct GKV_Base<const char *>: GKV_Base_Type<const char *, GGUF_TYPE_STRING, gguf_get_val_str > {};
  2316. template<> struct GKV_Base<std::string> {
  2317. static constexpr gguf_type gt = GGUF_TYPE_STRING;
  2318. static std::string getter(const gguf_context * ctx, const int kid) {
  2319. return gguf_get_val_str(ctx, kid);
  2320. }
  2321. };
  2322. struct ArrayInfo {
  2323. const gguf_type gt;
  2324. const size_t length;
  2325. const void * data;
  2326. };
  2327. template<> struct GKV_Base<ArrayInfo> {
  2328. public:
  2329. static constexpr gguf_type gt = GGUF_TYPE_ARRAY;
  2330. static ArrayInfo getter(const gguf_context *ctx, const int k) {
  2331. return ArrayInfo {
  2332. gguf_get_arr_type(ctx, k),
  2333. size_t(gguf_get_arr_n(ctx, k)),
  2334. gguf_get_arr_data(ctx, k),
  2335. };
  2336. }
  2337. };
  2338. template<typename T>
  2339. class GKV : public GKV_Base<T> {
  2340. GKV() = delete;
  2341. public:
  2342. static T get_kv(const gguf_context * ctx, const int k) {
  2343. const enum gguf_type kt = gguf_get_kv_type(ctx, k);
  2344. if (kt != GKV::gt) {
  2345. throw std::runtime_error(format("key %s has wrong type %s but expected type %s",
  2346. gguf_get_key(ctx, k), gguf_type_name(kt), gguf_type_name(GKV::gt)));
  2347. }
  2348. return GKV::getter(ctx, k);
  2349. }
  2350. static const char * override_type_to_str(const llama_model_kv_override_type ty) {
  2351. switch (ty) {
  2352. case LLAMA_KV_OVERRIDE_TYPE_BOOL: return "bool";
  2353. case LLAMA_KV_OVERRIDE_TYPE_INT: return "int";
  2354. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: return "float";
  2355. }
  2356. return "unknown";
  2357. }
  2358. static bool validate_override(const llama_model_kv_override_type expected_type, const struct llama_model_kv_override * ovrd) {
  2359. if (!ovrd) { return false; }
  2360. if (ovrd->tag == expected_type) {
  2361. LLAMA_LOG_INFO("%s: Using metadata override (%5s) '%s' = ",
  2362. __func__, override_type_to_str(ovrd->tag), ovrd->key);
  2363. switch (ovrd->tag) {
  2364. case LLAMA_KV_OVERRIDE_TYPE_BOOL: {
  2365. LLAMA_LOG_INFO("%s\n", ovrd->bool_value ? "true" : "false");
  2366. } break;
  2367. case LLAMA_KV_OVERRIDE_TYPE_INT: {
  2368. LLAMA_LOG_INFO("%" PRId64 "\n", ovrd->int_value);
  2369. } break;
  2370. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: {
  2371. LLAMA_LOG_INFO("%.6f\n", ovrd->float_value);
  2372. } break;
  2373. default:
  2374. // Shouldn't be possible to end up here, but just in case...
  2375. throw std::runtime_error(
  2376. format("Unsupported attempt to override %s type for metadata key %s\n",
  2377. override_type_to_str(ovrd->tag), ovrd->key));
  2378. }
  2379. return true;
  2380. }
  2381. LLAMA_LOG_WARN("%s: Warning: Bad metadata override type for key '%s', expected %s but got %s\n",
  2382. __func__, ovrd->key, override_type_to_str(expected_type), override_type_to_str(ovrd->tag));
  2383. return false;
  2384. }
  2385. template<typename OT>
  2386. static typename std::enable_if<std::is_same<OT, bool>::value, bool>::type
  2387. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  2388. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_BOOL, ovrd)) {
  2389. target = ovrd->bool_value;
  2390. return true;
  2391. }
  2392. return false;
  2393. }
  2394. template<typename OT>
  2395. static typename std::enable_if<!std::is_same<OT, bool>::value && std::is_integral<OT>::value, bool>::type
  2396. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  2397. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_INT, ovrd)) {
  2398. target = ovrd->int_value;
  2399. return true;
  2400. }
  2401. return false;
  2402. }
  2403. template<typename OT>
  2404. static typename std::enable_if<std::is_floating_point<OT>::value, bool>::type
  2405. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  2406. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_FLOAT, ovrd)) {
  2407. target = ovrd->float_value;
  2408. return true;
  2409. }
  2410. return false;
  2411. }
  2412. template<typename OT>
  2413. static typename std::enable_if<std::is_same<OT, std::string>::value, bool>::type
  2414. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  2415. (void)target;
  2416. (void)ovrd;
  2417. if (!ovrd) { return false; }
  2418. // Currently, we should never end up here so it would be a bug if we do.
  2419. throw std::runtime_error(format("Unsupported attempt to override string type for metadata key %s\n",
  2420. ovrd ? ovrd->key : "NULL"));
  2421. }
  2422. static bool set(const gguf_context * ctx, const int k, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  2423. if (try_override<T>(target, ovrd)) {
  2424. return true;
  2425. }
  2426. if (k < 0) { return false; }
  2427. target = get_kv(ctx, k);
  2428. return true;
  2429. }
  2430. static bool set(const gguf_context * ctx, const char * key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  2431. return set(ctx, gguf_find_key(ctx, key), target, ovrd);
  2432. }
  2433. static bool set(const gguf_context * ctx, const std::string & key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  2434. return set(ctx, key.c_str(), target, ovrd);
  2435. }
  2436. };
  2437. }
  2438. struct llama_model_loader {
  2439. int n_kv = 0;
  2440. int n_tensors = 0;
  2441. int n_created = 0;
  2442. int64_t n_elements = 0;
  2443. size_t n_bytes = 0;
  2444. bool use_mmap = false;
  2445. llama_file file;
  2446. llama_ftype ftype;
  2447. llama_fver fver;
  2448. std::unique_ptr<llama_mmap> mapping;
  2449. std::unordered_map<std::string, struct llama_model_kv_override> kv_overrides;
  2450. struct gguf_context * ctx_gguf = NULL;
  2451. struct ggml_context * ctx_meta = NULL;
  2452. std::string arch_name;
  2453. LLM_KV llm_kv = LLM_KV(LLM_ARCH_UNKNOWN);
  2454. llama_model_loader(const std::string & fname, bool use_mmap, const struct llama_model_kv_override * param_overrides_p) : file(fname.c_str(), "rb") {
  2455. int trace = 0;
  2456. if (getenv("LLAMA_TRACE")) {
  2457. trace = atoi(getenv("LLAMA_TRACE"));
  2458. }
  2459. struct gguf_init_params params = {
  2460. /*.no_alloc = */ true,
  2461. /*.ctx = */ &ctx_meta,
  2462. };
  2463. if (param_overrides_p != nullptr) {
  2464. for (const struct llama_model_kv_override *p = param_overrides_p; p->key[0] != 0; p++) {
  2465. kv_overrides.insert({std::string(p->key), *p});
  2466. }
  2467. }
  2468. ctx_gguf = gguf_init_from_file(fname.c_str(), params);
  2469. if (!ctx_gguf) {
  2470. throw std::runtime_error(format("%s: failed to load model from %s\n", __func__, fname.c_str()));
  2471. }
  2472. get_key(llm_kv(LLM_KV_GENERAL_ARCHITECTURE), arch_name, false);
  2473. llm_kv = LLM_KV(llm_arch_from_string(arch_name));
  2474. n_kv = gguf_get_n_kv(ctx_gguf);
  2475. n_tensors = gguf_get_n_tensors(ctx_gguf);
  2476. fver = (enum llama_fver ) gguf_get_version(ctx_gguf);
  2477. for (int i = 0; i < n_tensors; i++) {
  2478. const char * name = gguf_get_tensor_name(ctx_gguf, i);
  2479. struct ggml_tensor * t = ggml_get_tensor(ctx_meta, name);
  2480. n_elements += ggml_nelements(t);
  2481. n_bytes += ggml_nbytes(t);
  2482. }
  2483. LLAMA_LOG_INFO("%s: loaded meta data with %d key-value pairs and %d tensors from %s (version %s)\n",
  2484. __func__, n_kv, n_tensors, fname.c_str(), llama_file_version_name(fver));
  2485. // determine file type based on the number of tensors for each quantization and print meta data
  2486. // TODO: make optional
  2487. {
  2488. std::map<enum ggml_type, uint32_t> n_type;
  2489. uint32_t n_type_max = 0;
  2490. enum ggml_type type_max = GGML_TYPE_F32;
  2491. for (int i = 0; i < n_tensors; i++) {
  2492. enum ggml_type type = gguf_get_tensor_type(ctx_gguf, i);
  2493. n_type[type]++;
  2494. if (n_type_max < n_type[type]) {
  2495. n_type_max = n_type[type];
  2496. type_max = type;
  2497. }
  2498. if (trace > 0) {
  2499. struct ggml_tensor * meta = ggml_get_tensor(ctx_meta, gguf_get_tensor_name(ctx_gguf, i));
  2500. LLAMA_LOG_INFO("%s: - tensor %4d: %32s %-8s [ %s ]\n", __func__, i, ggml_get_name(meta), ggml_type_name(type), llama_format_tensor_shape(meta).c_str());
  2501. }
  2502. }
  2503. switch (type_max) {
  2504. case GGML_TYPE_F32: ftype = LLAMA_FTYPE_ALL_F32; break;
  2505. case GGML_TYPE_F16: ftype = LLAMA_FTYPE_MOSTLY_F16; break;
  2506. case GGML_TYPE_Q4_0: ftype = LLAMA_FTYPE_MOSTLY_Q4_0; break;
  2507. case GGML_TYPE_Q4_1: ftype = LLAMA_FTYPE_MOSTLY_Q4_1; break;
  2508. case GGML_TYPE_Q5_0: ftype = LLAMA_FTYPE_MOSTLY_Q5_0; break;
  2509. case GGML_TYPE_Q5_1: ftype = LLAMA_FTYPE_MOSTLY_Q5_1; break;
  2510. case GGML_TYPE_Q8_0: ftype = LLAMA_FTYPE_MOSTLY_Q8_0; break;
  2511. case GGML_TYPE_Q2_K: ftype = LLAMA_FTYPE_MOSTLY_Q2_K; break;
  2512. case GGML_TYPE_Q3_K: ftype = LLAMA_FTYPE_MOSTLY_Q3_K_M; break;
  2513. case GGML_TYPE_Q4_K: ftype = LLAMA_FTYPE_MOSTLY_Q4_K_M; break;
  2514. case GGML_TYPE_Q5_K: ftype = LLAMA_FTYPE_MOSTLY_Q5_K_M; break;
  2515. case GGML_TYPE_Q6_K: ftype = LLAMA_FTYPE_MOSTLY_Q6_K; break;
  2516. case GGML_TYPE_IQ2_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XXS; break;
  2517. case GGML_TYPE_IQ2_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XS; break;
  2518. case GGML_TYPE_IQ2_S: ftype = LLAMA_FTYPE_MOSTLY_IQ2_S; break;
  2519. case GGML_TYPE_IQ3_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ3_XXS; break;
  2520. case GGML_TYPE_IQ1_S: ftype = LLAMA_FTYPE_MOSTLY_IQ1_S; break;
  2521. case GGML_TYPE_IQ4_NL: ftype = LLAMA_FTYPE_MOSTLY_IQ4_NL; break;
  2522. case GGML_TYPE_IQ4_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ4_XS; break;
  2523. case GGML_TYPE_IQ3_S: ftype = LLAMA_FTYPE_MOSTLY_IQ3_S; break;
  2524. default:
  2525. {
  2526. LLAMA_LOG_WARN("%s: unknown type %s\n", __func__, ggml_type_name(type_max));
  2527. ftype = LLAMA_FTYPE_ALL_F32;
  2528. } break;
  2529. }
  2530. // this is a way to mark that we have "guessed" the file type
  2531. ftype = (llama_ftype) (ftype | LLAMA_FTYPE_GUESSED);
  2532. {
  2533. const int kid = gguf_find_key(ctx_gguf, "general.file_type");
  2534. if (kid >= 0) {
  2535. ftype = (llama_ftype) gguf_get_val_u32(ctx_gguf, kid);
  2536. }
  2537. }
  2538. LLAMA_LOG_INFO("%s: Dumping metadata keys/values. Note: KV overrides do not apply in this output.\n", __func__);
  2539. for (int i = 0; i < n_kv; i++) {
  2540. const char * name = gguf_get_key(ctx_gguf, i);
  2541. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  2542. const std::string type_name =
  2543. type == GGUF_TYPE_ARRAY
  2544. ? format("%s[%s,%d]", gguf_type_name(type), gguf_type_name(gguf_get_arr_type(ctx_gguf, i)), gguf_get_arr_n(ctx_gguf, i))
  2545. : gguf_type_name(type);
  2546. std::string value = gguf_kv_to_str(ctx_gguf, i);
  2547. const size_t MAX_VALUE_LEN = 40;
  2548. if (value.size() > MAX_VALUE_LEN) {
  2549. value = format("%s...", value.substr(0, MAX_VALUE_LEN - 3).c_str());
  2550. }
  2551. replace_all(value, "\n", "\\n");
  2552. LLAMA_LOG_INFO("%s: - kv %3d: %42s %-16s = %s\n", __func__, i, name, type_name.c_str(), value.c_str());
  2553. }
  2554. // print type counts
  2555. for (auto & kv : n_type) {
  2556. if (kv.second == 0) {
  2557. continue;
  2558. }
  2559. LLAMA_LOG_INFO("%s: - type %4s: %4d tensors\n", __func__, ggml_type_name(kv.first), kv.second);
  2560. }
  2561. }
  2562. if (!llama_mmap::SUPPORTED) {
  2563. LLAMA_LOG_WARN("%s: mmap is not supported on this platform\n", __func__);
  2564. use_mmap = false;
  2565. }
  2566. this->use_mmap = use_mmap;
  2567. }
  2568. ~llama_model_loader() {
  2569. if (ctx_gguf) {
  2570. gguf_free(ctx_gguf);
  2571. }
  2572. if (ctx_meta) {
  2573. ggml_free(ctx_meta);
  2574. }
  2575. }
  2576. template<typename T>
  2577. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2578. get_arr_n(const std::string & key, T & result, const bool required = true) {
  2579. const int kid = gguf_find_key(ctx_gguf, key.c_str());
  2580. if (kid < 0) {
  2581. if (required) {
  2582. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2583. }
  2584. return false;
  2585. }
  2586. struct GGUFMeta::ArrayInfo arr_info =
  2587. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(ctx_gguf, kid);
  2588. result = arr_info.length;
  2589. return true;
  2590. }
  2591. template<typename T>
  2592. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2593. get_arr_n(const enum llm_kv kid, T & result, const bool required = true) {
  2594. return get_arr_n(llm_kv(kid), result, required);
  2595. }
  2596. template<typename T>
  2597. bool get_key(const std::string & key, T & result, const bool required = true) {
  2598. auto it = kv_overrides.find(key);
  2599. const struct llama_model_kv_override * override =
  2600. it != kv_overrides.end() ? &it->second : nullptr;
  2601. const bool found = GGUFMeta::GKV<T>::set(ctx_gguf, key, result, override);
  2602. if (required && !found) {
  2603. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2604. }
  2605. return found;
  2606. }
  2607. template<typename T>
  2608. bool get_key(const enum llm_kv kid, T & result, const bool required = true) {
  2609. return get_key(llm_kv(kid), result, required);
  2610. }
  2611. std::string get_arch_name() const {
  2612. return arch_name;
  2613. }
  2614. enum llm_arch get_arch() const {
  2615. return llm_kv.arch;
  2616. }
  2617. const char * get_tensor_name(int i) const {
  2618. return gguf_get_tensor_name(ctx_gguf, i);
  2619. }
  2620. struct ggml_tensor * get_tensor_meta(const char * name) const {
  2621. return ggml_get_tensor(ctx_meta, name);
  2622. }
  2623. struct ggml_tensor * get_tensor_meta(int i) const {
  2624. return get_tensor_meta(get_tensor_name(i));
  2625. }
  2626. struct ggml_tensor * create_tensor_for(struct ggml_context * ctx, struct ggml_tensor * meta) {
  2627. struct ggml_tensor * tensor = ggml_dup_tensor(ctx, meta);
  2628. ggml_set_name(tensor, ggml_get_name(meta));
  2629. n_created++;
  2630. return tensor;
  2631. }
  2632. struct ggml_tensor * create_tensor(struct ggml_context * ctx, const std::string & name, const std::vector<int64_t> & ne, bool required = true) {
  2633. struct ggml_tensor * cur = ggml_get_tensor(ctx_meta, name.c_str());
  2634. if (cur == NULL) {
  2635. if (!required) {
  2636. return NULL;
  2637. }
  2638. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
  2639. }
  2640. {
  2641. bool is_ok = true;
  2642. for (size_t i = 0; i < ne.size(); ++i) {
  2643. if (ne[i] != cur->ne[i]) {
  2644. is_ok = false;
  2645. break;
  2646. }
  2647. }
  2648. if (!is_ok) {
  2649. throw std::runtime_error(
  2650. format("%s: tensor '%s' has wrong shape; expected %s, got %s",
  2651. __func__, name.c_str(),
  2652. llama_format_tensor_shape(ne).c_str(),
  2653. llama_format_tensor_shape(cur).c_str()));
  2654. }
  2655. }
  2656. return create_tensor_for(ctx, cur);
  2657. }
  2658. void done_getting_tensors() const {
  2659. if (n_created != n_tensors) {
  2660. throw std::runtime_error(format("%s: wrong number of tensors; expected %d, got %d", __func__, n_tensors, n_created));
  2661. }
  2662. }
  2663. size_t file_offset(const char * name) const {
  2664. const int idx = gguf_find_tensor(ctx_gguf, name);
  2665. if (idx < 0) {
  2666. throw std::runtime_error(format("%s: tensor '%s' not found in the file", __func__, name));
  2667. }
  2668. return gguf_get_data_offset(ctx_gguf) + gguf_get_tensor_offset(ctx_gguf, idx);
  2669. }
  2670. void init_mapping(bool prefetch = true, llama_mlock * lmlock = nullptr) {
  2671. // prefetch the whole file - all the data is needed anyway
  2672. if (use_mmap) {
  2673. mapping.reset(new llama_mmap(&file, prefetch ? -1 : 0, ggml_is_numa()));
  2674. }
  2675. // compute the total size of all tensors for progress reporting
  2676. for (int i = 0; i < gguf_get_n_tensors(ctx_gguf); i++) {
  2677. struct ggml_tensor * cur = ggml_get_tensor(ctx_meta, gguf_get_tensor_name(ctx_gguf, i));
  2678. size_data += ggml_nbytes(cur);
  2679. }
  2680. if (use_mmap && mapping) {
  2681. if (lmlock) {
  2682. lmlock->init(mapping->addr);
  2683. }
  2684. mmap_used_first = mapping->size;
  2685. }
  2686. }
  2687. void get_mapping_range(size_t * first, size_t * last, ggml_context * ctx) const {
  2688. GGML_ASSERT(mapping);
  2689. *first = mapping->size;
  2690. *last = 0;
  2691. for (ggml_tensor * tensor = ggml_get_first_tensor(ctx); tensor; tensor = ggml_get_next_tensor(ctx, tensor)) {
  2692. const size_t offs = file_offset(ggml_get_name(tensor));
  2693. *first = std::min(*first, offs);
  2694. *last = std::max(*last, offs + ggml_nbytes(tensor));
  2695. }
  2696. }
  2697. // for backwards compatibility, does not support ggml-backend
  2698. void load_data_for(struct ggml_tensor * cur) const {
  2699. const size_t offs = file_offset(ggml_get_name(cur));
  2700. if (use_mmap && mapping) {
  2701. if (cur->data == nullptr) {
  2702. cur->data = (uint8_t *)mapping->addr + offs;
  2703. } else {
  2704. memcpy(cur->data, (uint8_t *)mapping->addr + offs, ggml_nbytes(cur));
  2705. }
  2706. } else {
  2707. GGML_ASSERT(cur->data != nullptr);
  2708. file.seek(offs, SEEK_SET);
  2709. file.read_raw(cur->data, ggml_nbytes(cur));
  2710. }
  2711. }
  2712. size_t size_done = 0;
  2713. size_t size_data = 0;
  2714. size_t mmap_used_first = -1;
  2715. size_t mmap_used_last = 0;
  2716. // Returns false if cancelled by progress_callback
  2717. bool load_all_data(struct ggml_context * ctx, llama_progress_callback progress_callback, void * progress_callback_user_data, ggml_backend_buffer_t buf_mmap, llama_mlock * lmlock) {
  2718. GGML_ASSERT(size_data != 0 && "call init_mapping() first");
  2719. std::vector<no_init<uint8_t>> read_buf;
  2720. for (struct ggml_tensor * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  2721. if (progress_callback) {
  2722. if (!progress_callback((float) size_done / size_data, progress_callback_user_data)) {
  2723. return false;
  2724. }
  2725. }
  2726. const size_t offs = file_offset(ggml_get_name(cur));
  2727. if (use_mmap && mapping) {
  2728. if (buf_mmap && cur->data == nullptr) {
  2729. ggml_backend_tensor_alloc(buf_mmap, cur, (uint8_t *) mapping->addr + offs);
  2730. if (lmlock) {
  2731. lmlock->grow_to(offs + ggml_nbytes(cur));
  2732. }
  2733. mmap_used_first = std::min(mmap_used_first, offs);
  2734. mmap_used_last = std::max(mmap_used_last, offs + ggml_nbytes(cur));
  2735. } else {
  2736. ggml_backend_tensor_set(cur, (uint8_t *) mapping->addr + offs, 0, ggml_nbytes(cur));
  2737. }
  2738. } else {
  2739. if (ggml_backend_buffer_is_host(cur->buffer)) {
  2740. file.seek(offs, SEEK_SET);
  2741. file.read_raw(cur->data, ggml_nbytes(cur));
  2742. } else {
  2743. read_buf.resize(ggml_nbytes(cur));
  2744. file.seek(offs, SEEK_SET);
  2745. file.read_raw(read_buf.data(), ggml_nbytes(cur));
  2746. ggml_backend_tensor_set(cur, read_buf.data(), 0, ggml_nbytes(cur));
  2747. }
  2748. }
  2749. size_done += ggml_nbytes(cur);
  2750. }
  2751. // check if this is the last call and do final cleanup
  2752. if (size_done >= size_data) {
  2753. // unmap offloaded tensors and metadata
  2754. if (use_mmap && mapping) {
  2755. mapping->unmap_fragment(0, mmap_used_first);
  2756. if (mmap_used_last != 0) {
  2757. mapping->unmap_fragment(mmap_used_last, mapping->size);
  2758. }
  2759. }
  2760. if (progress_callback) {
  2761. // Even though the model is done loading, we still honor
  2762. // cancellation since we need to free allocations.
  2763. return progress_callback(1.0f, progress_callback_user_data);
  2764. }
  2765. }
  2766. return true;
  2767. }
  2768. };
  2769. template<>
  2770. bool llama_model_loader::get_key(const enum llm_kv kid, enum llama_pooling_type & result, const bool required) {
  2771. uint32_t tmp;
  2772. const bool found = get_key(kid, tmp, required);
  2773. if (found) {
  2774. result = (enum llama_pooling_type) tmp;
  2775. } else {
  2776. result = LLAMA_POOLING_TYPE_UNSPECIFIED;
  2777. }
  2778. return found;
  2779. }
  2780. //
  2781. // load LLaMA models
  2782. //
  2783. static const char * llama_model_arch_name(llm_arch arch) {
  2784. auto it = LLM_ARCH_NAMES.find(arch);
  2785. if (it == LLM_ARCH_NAMES.end()) {
  2786. return "unknown";
  2787. }
  2788. return it->second;
  2789. }
  2790. static std::string llama_model_ftype_name(llama_ftype ftype) {
  2791. if (ftype & LLAMA_FTYPE_GUESSED) {
  2792. return llama_model_ftype_name((enum llama_ftype) (ftype & ~LLAMA_FTYPE_GUESSED)) + " (guessed)";
  2793. }
  2794. switch (ftype) {
  2795. case LLAMA_FTYPE_ALL_F32: return "all F32";
  2796. case LLAMA_FTYPE_MOSTLY_F16: return "F16";
  2797. case LLAMA_FTYPE_MOSTLY_Q4_0: return "Q4_0";
  2798. case LLAMA_FTYPE_MOSTLY_Q4_1: return "Q4_1";
  2799. case LLAMA_FTYPE_MOSTLY_Q4_1_SOME_F16:
  2800. return "Q4_1, some F16";
  2801. case LLAMA_FTYPE_MOSTLY_Q5_0: return "Q5_0";
  2802. case LLAMA_FTYPE_MOSTLY_Q5_1: return "Q5_1";
  2803. case LLAMA_FTYPE_MOSTLY_Q8_0: return "Q8_0";
  2804. // K-quants
  2805. case LLAMA_FTYPE_MOSTLY_Q2_K: return "Q2_K - Medium";
  2806. case LLAMA_FTYPE_MOSTLY_Q2_K_S: return "Q2_K - Small";
  2807. case LLAMA_FTYPE_MOSTLY_Q3_K_S: return "Q3_K - Small";
  2808. case LLAMA_FTYPE_MOSTLY_Q3_K_M: return "Q3_K - Medium";
  2809. case LLAMA_FTYPE_MOSTLY_Q3_K_L: return "Q3_K - Large";
  2810. case LLAMA_FTYPE_MOSTLY_Q4_K_S: return "Q4_K - Small";
  2811. case LLAMA_FTYPE_MOSTLY_Q4_K_M: return "Q4_K - Medium";
  2812. case LLAMA_FTYPE_MOSTLY_Q5_K_S: return "Q5_K - Small";
  2813. case LLAMA_FTYPE_MOSTLY_Q5_K_M: return "Q5_K - Medium";
  2814. case LLAMA_FTYPE_MOSTLY_Q6_K: return "Q6_K";
  2815. case LLAMA_FTYPE_MOSTLY_IQ2_XXS:return "IQ2_XXS - 2.0625 bpw";
  2816. case LLAMA_FTYPE_MOSTLY_IQ2_XS: return "IQ2_XS - 2.3125 bpw";
  2817. case LLAMA_FTYPE_MOSTLY_IQ2_S: return "IQ2_S - 2.5 bpw";
  2818. case LLAMA_FTYPE_MOSTLY_IQ2_M: return "IQ2_M - 2.7 bpw";
  2819. case LLAMA_FTYPE_MOSTLY_IQ3_XS: return "IQ3_XS - 3.3 bpw";
  2820. case LLAMA_FTYPE_MOSTLY_IQ3_XXS:return "IQ3_XXS - 3.0625 bpw";
  2821. case LLAMA_FTYPE_MOSTLY_IQ1_S :return "IQ1_S - 1.5625 bpw";
  2822. case LLAMA_FTYPE_MOSTLY_IQ4_NL: return "IQ4_NL - 4.5 bpw";
  2823. case LLAMA_FTYPE_MOSTLY_IQ4_XS: return "IQ4_XS - 4.25 bpw";
  2824. case LLAMA_FTYPE_MOSTLY_IQ3_S: return "IQ3_S - 3.4375 bpw";
  2825. case LLAMA_FTYPE_MOSTLY_IQ3_M: return "IQ3_S mix - 3.66 bpw";
  2826. default: return "unknown, may not work";
  2827. }
  2828. }
  2829. static const char * llama_model_type_name(e_model type) {
  2830. switch (type) {
  2831. case MODEL_22M: return "22M";
  2832. case MODEL_33M: return "33M";
  2833. case MODEL_109M: return "109M";
  2834. case MODEL_137M: return "137M";
  2835. case MODEL_0_5B: return "0.5B";
  2836. case MODEL_1B: return "1B";
  2837. case MODEL_2B: return "2B";
  2838. case MODEL_3B: return "3B";
  2839. case MODEL_7B: return "7B";
  2840. case MODEL_8B: return "8B";
  2841. case MODEL_13B: return "13B";
  2842. case MODEL_14B: return "14B";
  2843. case MODEL_15B: return "15B";
  2844. case MODEL_20B: return "20B";
  2845. case MODEL_30B: return "30B";
  2846. case MODEL_34B: return "34B";
  2847. case MODEL_35B: return "35B";
  2848. case MODEL_40B: return "40B";
  2849. case MODEL_65B: return "65B";
  2850. case MODEL_70B: return "70B";
  2851. case MODEL_SMALL: return "0.1B";
  2852. case MODEL_MEDIUM: return "0.4B";
  2853. case MODEL_LARGE: return "0.8B";
  2854. case MODEL_XL: return "1.5B";
  2855. default: return "?B";
  2856. }
  2857. }
  2858. static const char * llama_model_vocab_type_name(enum llama_vocab_type type){
  2859. switch (type) {
  2860. case LLAMA_VOCAB_TYPE_NONE: return "no vocab";
  2861. case LLAMA_VOCAB_TYPE_SPM: return "SPM";
  2862. case LLAMA_VOCAB_TYPE_BPE: return "BPE";
  2863. case LLAMA_VOCAB_TYPE_WPM: return "WPM";
  2864. default: return "unknown";
  2865. }
  2866. }
  2867. static void llm_load_arch(llama_model_loader & ml, llama_model & model) {
  2868. model.arch = ml.get_arch();
  2869. if (model.arch == LLM_ARCH_UNKNOWN) {
  2870. throw std::runtime_error("unknown model architecture: '" + ml.get_arch_name() + "'");
  2871. }
  2872. }
  2873. static void llm_load_hparams(
  2874. llama_model_loader & ml,
  2875. llama_model & model) {
  2876. auto & hparams = model.hparams;
  2877. const gguf_context * ctx = ml.ctx_gguf;
  2878. // get metadata as string
  2879. for (int i = 0; i < gguf_get_n_kv(ctx); i++) {
  2880. enum gguf_type type = gguf_get_kv_type(ctx, i);
  2881. if (type == GGUF_TYPE_ARRAY) {
  2882. continue;
  2883. }
  2884. const char * name = gguf_get_key(ctx, i);
  2885. const std::string value = gguf_kv_to_str(ctx, i);
  2886. model.gguf_kv.emplace(name, value);
  2887. }
  2888. // get general kv
  2889. ml.get_key(LLM_KV_GENERAL_NAME, model.name, false);
  2890. // get hparams kv
  2891. ml.get_key(LLM_KV_VOCAB_SIZE, hparams.n_vocab, false) || ml.get_arr_n(LLM_KV_TOKENIZER_LIST, hparams.n_vocab);
  2892. ml.get_key(LLM_KV_CONTEXT_LENGTH, hparams.n_ctx_train);
  2893. ml.get_key(LLM_KV_EMBEDDING_LENGTH, hparams.n_embd);
  2894. ml.get_key(LLM_KV_FEED_FORWARD_LENGTH, hparams.n_ff);
  2895. ml.get_key(LLM_KV_ATTENTION_HEAD_COUNT, hparams.n_head);
  2896. ml.get_key(LLM_KV_BLOCK_COUNT, hparams.n_layer);
  2897. ml.get_key(LLM_KV_EXPERT_COUNT, hparams.n_expert, false);
  2898. ml.get_key(LLM_KV_EXPERT_USED_COUNT, hparams.n_expert_used, false);
  2899. GGML_ASSERT(hparams.n_expert <= LLAMA_MAX_EXPERTS);
  2900. GGML_ASSERT(hparams.n_expert_used <= hparams.n_expert);
  2901. if (hparams.n_expert > 0) {
  2902. GGML_ASSERT(hparams.n_expert_used > 0);
  2903. } else {
  2904. GGML_ASSERT(hparams.n_expert_used == 0);
  2905. }
  2906. // n_head_kv is optional, default to n_head
  2907. hparams.n_head_kv = hparams.n_head;
  2908. ml.get_key(LLM_KV_ATTENTION_HEAD_COUNT_KV, hparams.n_head_kv, false);
  2909. bool rope_finetuned = false;
  2910. ml.get_key(LLM_KV_ROPE_SCALING_FINETUNED, rope_finetuned, false);
  2911. hparams.rope_finetuned = rope_finetuned;
  2912. hparams.n_yarn_orig_ctx = hparams.n_ctx_train;
  2913. ml.get_key(LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, hparams.n_yarn_orig_ctx, false);
  2914. // rope_freq_base (optional)
  2915. hparams.rope_freq_base_train = 10000.0f;
  2916. ml.get_key(LLM_KV_ROPE_FREQ_BASE, hparams.rope_freq_base_train, false);
  2917. std::string rope_scaling("linear");
  2918. ml.get_key(LLM_KV_ROPE_SCALING_TYPE, rope_scaling, false);
  2919. hparams.rope_scaling_type_train = llama_rope_scaling_type_from_string(rope_scaling);
  2920. GGML_ASSERT(hparams.rope_scaling_type_train != LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED);
  2921. // rope_freq_scale (inverse of the kv) is optional
  2922. float ropescale = 0.0f;
  2923. if (!ml.get_key(LLM_KV_ROPE_SCALING_FACTOR, ropescale, false)) {
  2924. // try the old key name
  2925. ml.get_key(LLM_KV_ROPE_SCALE_LINEAR, ropescale, false);
  2926. }
  2927. hparams.rope_freq_scale_train = ropescale == 0.0f ? 1.0f : 1.0f/ropescale;
  2928. // sanity check for n_rot (optional)
  2929. {
  2930. hparams.n_rot = (hparams.n_head == 0) ? 0 : hparams.n_embd / hparams.n_head;
  2931. ml.get_key(LLM_KV_ROPE_DIMENSION_COUNT, hparams.n_rot, false);
  2932. if (model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON) {
  2933. if (hparams.n_rot != hparams.n_embd / hparams.n_head) {
  2934. throw std::runtime_error(format("invalid n_rot: %u, expected %u", hparams.n_rot, hparams.n_embd / hparams.n_head));
  2935. }
  2936. }
  2937. // gpt-neox n_rot = rotary_pct * (n_embd / n_head)
  2938. // gpt-j n_rot = rotary_dim
  2939. }
  2940. hparams.n_embd_head_k = (hparams.n_head == 0) ? 0 : hparams.n_embd / hparams.n_head;
  2941. ml.get_key(LLM_KV_ATTENTION_KEY_LENGTH, hparams.n_embd_head_k, false);
  2942. hparams.n_embd_head_v = (hparams.n_head == 0) ? 0 : hparams.n_embd / hparams.n_head;
  2943. ml.get_key(LLM_KV_ATTENTION_VALUE_LENGTH, hparams.n_embd_head_v, false);
  2944. // arch-specific KVs
  2945. switch (model.arch) {
  2946. case LLM_ARCH_LLAMA:
  2947. {
  2948. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2949. switch (hparams.n_layer) {
  2950. case 22: model.type = e_model::MODEL_1B; break;
  2951. case 26: model.type = e_model::MODEL_3B; break;
  2952. case 32: model.type = e_model::MODEL_7B; break;
  2953. case 40: model.type = e_model::MODEL_13B; break;
  2954. case 48: model.type = e_model::MODEL_34B; break;
  2955. case 60: model.type = e_model::MODEL_30B; break;
  2956. case 80: model.type = hparams.n_head == hparams.n_head_kv ? e_model::MODEL_65B : e_model::MODEL_70B; break;
  2957. default: model.type = e_model::MODEL_UNKNOWN;
  2958. }
  2959. } break;
  2960. case LLM_ARCH_MINICPM:
  2961. {
  2962. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2963. switch (hparams.n_layer) {
  2964. case 40: model.type = e_model::MODEL_2B; break;
  2965. default: model.type = e_model::MODEL_UNKNOWN;
  2966. }
  2967. } break;
  2968. case LLM_ARCH_FALCON:
  2969. {
  2970. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2971. switch (hparams.n_layer) {
  2972. case 32: model.type = e_model::MODEL_7B; break;
  2973. case 60: model.type = e_model::MODEL_40B; break;
  2974. default: model.type = e_model::MODEL_UNKNOWN;
  2975. }
  2976. } break;
  2977. case LLM_ARCH_BAICHUAN:
  2978. {
  2979. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2980. switch (hparams.n_layer) {
  2981. case 32: model.type = e_model::MODEL_7B; break;
  2982. case 40: model.type = e_model::MODEL_13B; break;
  2983. default: model.type = e_model::MODEL_UNKNOWN;
  2984. }
  2985. if (model.type == e_model::MODEL_13B) {
  2986. // TODO: become GGUF KV parameter
  2987. hparams.f_max_alibi_bias = 8.0f;
  2988. }
  2989. } break;
  2990. case LLM_ARCH_STARCODER:
  2991. {
  2992. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2993. switch (hparams.n_layer) {
  2994. case 24: model.type = e_model::MODEL_1B; break;
  2995. case 36: model.type = e_model::MODEL_3B; break;
  2996. case 42: model.type = e_model::MODEL_7B; break;
  2997. case 40: model.type = e_model::MODEL_15B; break;
  2998. default: model.type = e_model::MODEL_UNKNOWN;
  2999. }
  3000. } break;
  3001. case LLM_ARCH_PERSIMMON:
  3002. {
  3003. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3004. switch (hparams.n_layer) {
  3005. case 36: model.type = e_model::MODEL_8B; break;
  3006. default: model.type = e_model::MODEL_UNKNOWN;
  3007. }
  3008. } break;
  3009. case LLM_ARCH_REFACT:
  3010. {
  3011. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3012. switch (hparams.n_layer) {
  3013. case 32: model.type = e_model::MODEL_1B; break;
  3014. default: model.type = e_model::MODEL_UNKNOWN;
  3015. }
  3016. // TODO: become GGUF KV parameter
  3017. hparams.f_max_alibi_bias = 8.0f;
  3018. } break;
  3019. case LLM_ARCH_BERT:
  3020. {
  3021. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3022. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  3023. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  3024. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type, false);
  3025. switch (hparams.n_layer) {
  3026. case 3:
  3027. model.type = e_model::MODEL_17M; break; // bge-micro
  3028. case 6:
  3029. model.type = e_model::MODEL_22M; break; // MiniLM-L6
  3030. case 12:
  3031. switch (hparams.n_embd) {
  3032. case 384: model.type = e_model::MODEL_33M; break; // MiniLM-L12, bge-small
  3033. case 768: model.type = e_model::MODEL_109M; break; // bge-base
  3034. } break;
  3035. case 24:
  3036. model.type = e_model::MODEL_335M; break; // bge-large
  3037. }
  3038. } break;
  3039. case LLM_ARCH_NOMIC_BERT:
  3040. {
  3041. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3042. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  3043. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  3044. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type);
  3045. if (hparams.n_layer == 12 && hparams.n_embd == 768) {
  3046. model.type = e_model::MODEL_137M;
  3047. }
  3048. } break;
  3049. case LLM_ARCH_BLOOM:
  3050. {
  3051. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3052. switch (hparams.n_layer) {
  3053. case 24: model.type = e_model::MODEL_1B; break;
  3054. case 30:
  3055. switch (hparams.n_embd) {
  3056. case 2560: model.type = e_model::MODEL_3B; break;
  3057. case 4096: model.type = e_model::MODEL_7B; break;
  3058. } break;
  3059. }
  3060. // TODO: become GGUF KV parameter
  3061. hparams.f_max_alibi_bias = 8.0f;
  3062. } break;
  3063. case LLM_ARCH_MPT:
  3064. {
  3065. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3066. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv, false);
  3067. ml.get_key(LLM_KV_ATTENTION_MAX_ALIBI_BIAS, hparams.f_max_alibi_bias);
  3068. switch (hparams.n_layer) {
  3069. case 32: model.type = e_model::MODEL_7B; break;
  3070. case 48: model.type = e_model::MODEL_30B; break;
  3071. default: model.type = e_model::MODEL_UNKNOWN;
  3072. }
  3073. } break;
  3074. case LLM_ARCH_STABLELM:
  3075. {
  3076. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3077. switch (hparams.n_layer) {
  3078. case 24: model.type = e_model::MODEL_1B; break;
  3079. case 32: model.type = e_model::MODEL_3B; break;
  3080. default: model.type = e_model::MODEL_UNKNOWN;
  3081. }
  3082. } break;
  3083. case LLM_ARCH_QWEN:
  3084. {
  3085. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3086. switch (hparams.n_layer) {
  3087. case 32: model.type = e_model::MODEL_7B; break;
  3088. case 40: model.type = e_model::MODEL_13B; break;
  3089. default: model.type = e_model::MODEL_UNKNOWN;
  3090. }
  3091. } break;
  3092. case LLM_ARCH_QWEN2:
  3093. {
  3094. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3095. switch (hparams.n_layer) {
  3096. case 24: model.type = hparams.n_embd == 1024 ? e_model::MODEL_0_5B : e_model::MODEL_1B; break;
  3097. case 32: model.type = e_model::MODEL_7B; break;
  3098. case 40: model.type = hparams.n_head == 20 ? e_model::MODEL_4B : e_model::MODEL_13B; break;
  3099. case 80: model.type = e_model::MODEL_70B; break;
  3100. default: model.type = e_model::MODEL_UNKNOWN;
  3101. }
  3102. } break;
  3103. case LLM_ARCH_PHI2:
  3104. {
  3105. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3106. switch (hparams.n_layer) {
  3107. case 24: model.type = e_model::MODEL_1B; break;
  3108. case 32: model.type = e_model::MODEL_3B; break;
  3109. default: model.type = e_model::MODEL_UNKNOWN;
  3110. }
  3111. } break;
  3112. case LLM_ARCH_PLAMO:
  3113. {
  3114. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3115. switch (hparams.n_layer) {
  3116. case 40: model.type = e_model::MODEL_13B; break;
  3117. default: model.type = e_model::MODEL_UNKNOWN;
  3118. }
  3119. } break;
  3120. case LLM_ARCH_GPT2:
  3121. {
  3122. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3123. switch (hparams.n_layer) {
  3124. case 12: model.type = e_model::MODEL_SMALL; break;
  3125. case 24: model.type = e_model::MODEL_MEDIUM; break;
  3126. case 36: model.type = e_model::MODEL_LARGE; break;
  3127. case 48: model.type = e_model::MODEL_XL; break;
  3128. default: model.type = e_model::MODEL_UNKNOWN;
  3129. }
  3130. } break;
  3131. case LLM_ARCH_CODESHELL:
  3132. {
  3133. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3134. switch (hparams.n_layer) {
  3135. case 42: model.type = e_model::MODEL_SMALL; break;
  3136. default: model.type = e_model::MODEL_UNKNOWN;
  3137. }
  3138. } break;
  3139. case LLM_ARCH_ORION:
  3140. {
  3141. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3142. switch (hparams.n_layer) {
  3143. case 40: model.type = e_model::MODEL_14B; break;
  3144. default: model.type = e_model::MODEL_UNKNOWN;
  3145. }
  3146. } break;
  3147. case LLM_ARCH_INTERNLM2:
  3148. {
  3149. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3150. switch (hparams.n_layer) {
  3151. case 32: model.type = e_model::MODEL_7B; break;
  3152. case 48: model.type = e_model::MODEL_20B; break;
  3153. default: model.type = e_model::MODEL_UNKNOWN;
  3154. }
  3155. } break;
  3156. case LLM_ARCH_GEMMA:
  3157. {
  3158. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3159. switch (hparams.n_layer) {
  3160. case 18: model.type = e_model::MODEL_2B; break;
  3161. case 28: model.type = e_model::MODEL_7B; break;
  3162. default: model.type = e_model::MODEL_UNKNOWN;
  3163. }
  3164. } break;
  3165. case LLM_ARCH_STARCODER2:
  3166. {
  3167. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3168. switch (hparams.n_layer) {
  3169. case 30: model.type = e_model::MODEL_3B; break;
  3170. case 32: model.type = e_model::MODEL_7B; break;
  3171. case 40: model.type = e_model::MODEL_15B; break;
  3172. default: model.type = e_model::MODEL_UNKNOWN;
  3173. }
  3174. } break;
  3175. case LLM_ARCH_MAMBA:
  3176. {
  3177. ml.get_key(LLM_KV_SSM_CONV_KERNEL, hparams.ssm_d_conv);
  3178. ml.get_key(LLM_KV_SSM_INNER_SIZE, hparams.ssm_d_inner);
  3179. ml.get_key(LLM_KV_SSM_STATE_SIZE, hparams.ssm_d_state);
  3180. ml.get_key(LLM_KV_SSM_TIME_STEP_RANK, hparams.ssm_dt_rank);
  3181. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  3182. switch (hparams.n_layer) {
  3183. case 24:
  3184. switch (hparams.n_embd) {
  3185. case 768: model.type = e_model::MODEL_SMALL; break;
  3186. default: model.type = e_model::MODEL_UNKNOWN;
  3187. } break;
  3188. case 48:
  3189. switch (hparams.n_embd) {
  3190. case 1024: model.type = e_model::MODEL_MEDIUM; break;
  3191. case 1536: model.type = e_model::MODEL_LARGE; break;
  3192. case 2048: model.type = e_model::MODEL_XL; break;
  3193. default: model.type = e_model::MODEL_UNKNOWN;
  3194. } break;
  3195. case 64:
  3196. switch (hparams.n_embd) {
  3197. case 2560: model.type = e_model::MODEL_3B; break;
  3198. default: model.type = e_model::MODEL_UNKNOWN;
  3199. } break;
  3200. default: model.type = e_model::MODEL_UNKNOWN;
  3201. }
  3202. } break;
  3203. case LLM_ARCH_COMMAND_R:
  3204. {
  3205. ml.get_key(LLM_KV_LOGIT_SCALE, hparams.f_logit_scale);
  3206. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  3207. switch (hparams.n_layer) {
  3208. case 40: model.type = e_model::MODEL_35B; break;
  3209. default: model.type = e_model::MODEL_UNKNOWN;
  3210. }
  3211. } break;
  3212. default: (void)0;
  3213. }
  3214. model.ftype = ml.ftype;
  3215. if (hparams.f_max_alibi_bias > 0.0f) {
  3216. hparams.need_kq_pos = true;
  3217. }
  3218. hparams.rope_type = llama_rope_type(&model);
  3219. }
  3220. // TODO: This should probably be in llama.h
  3221. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special = false);
  3222. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch);
  3223. static void llm_load_vocab(
  3224. llama_model_loader & ml,
  3225. llama_model & model) {
  3226. auto & vocab = model.vocab;
  3227. struct gguf_context * ctx = ml.ctx_gguf;
  3228. const auto kv = LLM_KV(model.arch);
  3229. // determine vocab type
  3230. {
  3231. std::string tokenizer_name;
  3232. ml.get_key(LLM_KV_TOKENIZER_MODEL, tokenizer_name);
  3233. if (tokenizer_name == "no_vocab") {
  3234. vocab.type = LLAMA_VOCAB_TYPE_NONE;
  3235. // default special tokens
  3236. vocab.special_bos_id = -1;
  3237. vocab.special_eos_id = -1;
  3238. vocab.special_unk_id = -1;
  3239. vocab.special_sep_id = -1;
  3240. vocab.special_pad_id = -1;
  3241. vocab.linefeed_id = -1;
  3242. return;
  3243. } else if (tokenizer_name == "llama") {
  3244. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  3245. // default special tokens
  3246. vocab.special_bos_id = 1;
  3247. vocab.special_eos_id = 2;
  3248. vocab.special_unk_id = 0;
  3249. vocab.special_sep_id = -1;
  3250. vocab.special_pad_id = -1;
  3251. const int add_space_prefix_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_ADD_PREFIX).c_str());
  3252. if (add_space_prefix_keyidx != -1) {
  3253. vocab.add_space_prefix = gguf_get_val_bool(ctx, add_space_prefix_keyidx);
  3254. } // The default value of add_space_prefix is true.
  3255. } else if (tokenizer_name == "gpt2") {
  3256. vocab.type = LLAMA_VOCAB_TYPE_BPE;
  3257. // read bpe merges and populate bpe ranks
  3258. const int merges_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_MERGES).c_str());
  3259. if (merges_keyidx == -1) {
  3260. throw std::runtime_error("cannot find tokenizer merges in model file\n");
  3261. }
  3262. const int n_merges = gguf_get_arr_n(ctx, merges_keyidx);
  3263. for (int i = 0; i < n_merges; i++) {
  3264. const std::string word = gguf_get_arr_str(ctx, merges_keyidx, i);
  3265. GGML_ASSERT(unicode_cpts_from_utf8(word).size() > 0);
  3266. std::string first;
  3267. std::string second;
  3268. const size_t pos = word.find(' ', 1);
  3269. if (pos != std::string::npos) {
  3270. first = word.substr(0, pos);
  3271. second = word.substr(pos + 1);
  3272. }
  3273. vocab.bpe_ranks.emplace(std::make_pair(first, second), i);
  3274. }
  3275. // default special tokens
  3276. vocab.special_bos_id = 11;
  3277. vocab.special_eos_id = 11;
  3278. vocab.special_unk_id = -1;
  3279. vocab.special_sep_id = -1;
  3280. vocab.special_pad_id = -1;
  3281. } else if (tokenizer_name == "bert") {
  3282. vocab.type = LLAMA_VOCAB_TYPE_WPM;
  3283. // default special tokens
  3284. vocab.special_bos_id = 101;
  3285. vocab.special_eos_id = 102;
  3286. vocab.special_unk_id = 100;
  3287. vocab.special_sep_id = -1;
  3288. vocab.special_pad_id = -1;
  3289. vocab.add_space_prefix = false;
  3290. } else {
  3291. LLAMA_LOG_WARN("%s: unknown tokenizer: '%s'", __func__, tokenizer_name.c_str());
  3292. LLAMA_LOG_WARN("%s: using default tokenizer: 'llama'", __func__);
  3293. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  3294. }
  3295. }
  3296. const int token_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_LIST).c_str());
  3297. if (token_idx == -1) {
  3298. throw std::runtime_error("cannot find tokenizer vocab in model file\n");
  3299. }
  3300. const float * scores = nullptr;
  3301. const int score_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_SCORES).c_str());
  3302. if (score_idx != -1) {
  3303. scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
  3304. }
  3305. const int * toktypes = nullptr;
  3306. const int toktype_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE).c_str());
  3307. if (toktype_idx != -1) {
  3308. toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
  3309. }
  3310. const uint32_t n_vocab = gguf_get_arr_n(ctx, token_idx);
  3311. vocab.id_to_token.resize(n_vocab);
  3312. for (uint32_t i = 0; i < n_vocab; i++) {
  3313. std::string word = gguf_get_arr_str(ctx, token_idx, i);
  3314. GGML_ASSERT(unicode_cpts_from_utf8(word).size() > 0);
  3315. vocab.token_to_id[word] = i;
  3316. auto & token_data = vocab.id_to_token[i];
  3317. token_data.text = std::move(word);
  3318. token_data.score = scores ? scores[i] : 0.0f;
  3319. token_data.type = toktypes ? (llama_token_type) toktypes[i] : LLAMA_TOKEN_TYPE_NORMAL;
  3320. }
  3321. GGML_ASSERT(vocab.id_to_token.size() == vocab.token_to_id.size());
  3322. // determine the newline token: LLaMA "<0x0A>" == 10 == '\n', Falcon 193 == '\n'
  3323. if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  3324. try {
  3325. vocab.linefeed_id = llama_byte_to_token(vocab, '\n');
  3326. } catch (const std::exception & e) {
  3327. LLAMA_LOG_WARN("%s: SPM vocabulary, but newline token not found: %s! Using special_pad_id instead.", __func__, e.what());
  3328. vocab.linefeed_id = vocab.special_pad_id;
  3329. }
  3330. } else if (vocab.type == LLAMA_VOCAB_TYPE_WPM) {
  3331. vocab.linefeed_id = vocab.special_pad_id;
  3332. } else {
  3333. const std::vector<int> ids = llama_tokenize_internal(vocab, "\u010A", false);
  3334. GGML_ASSERT(!ids.empty() && "model vocab missing newline token");
  3335. vocab.linefeed_id = ids[0];
  3336. }
  3337. // special tokens
  3338. {
  3339. const std::vector<std::pair<enum llm_kv, int32_t &>> special_token_types = {
  3340. { LLM_KV_TOKENIZER_BOS_ID, vocab.special_bos_id },
  3341. { LLM_KV_TOKENIZER_EOS_ID, vocab.special_eos_id },
  3342. { LLM_KV_TOKENIZER_UNK_ID, vocab.special_unk_id },
  3343. { LLM_KV_TOKENIZER_SEP_ID, vocab.special_sep_id },
  3344. { LLM_KV_TOKENIZER_PAD_ID, vocab.special_pad_id },
  3345. };
  3346. for (const auto & it : special_token_types) {
  3347. const std::string & key = kv(std::get<0>(it));
  3348. int32_t & id = std::get<1>(it);
  3349. uint32_t new_id;
  3350. if (!ml.get_key(std::get<0>(it), new_id, false)) {
  3351. continue;
  3352. }
  3353. if (new_id >= vocab.id_to_token.size()) {
  3354. LLAMA_LOG_WARN("%s: bad special token: '%s' = %ud, using default id %d\n",
  3355. __func__, key.c_str(), new_id, id);
  3356. } else {
  3357. id = new_id;
  3358. }
  3359. }
  3360. // Handle add_bos_token and add_eos_token
  3361. {
  3362. bool temp = true;
  3363. if (ml.get_key(LLM_KV_TOKENIZER_ADD_BOS, temp, false)) {
  3364. vocab.special_add_bos = int(temp);
  3365. }
  3366. if (ml.get_key(LLM_KV_TOKENIZER_ADD_EOS, temp, false)) {
  3367. vocab.special_add_eos = int(temp);
  3368. }
  3369. }
  3370. }
  3371. // build special tokens cache
  3372. {
  3373. // TODO: It is unclear (to me) at this point, whether special tokes are guaranteed to be of a deterministic type,
  3374. // and will always be correctly labeled in 'added_tokens.json' etc.
  3375. // The assumption is, since special tokens aren't meant to be exposed to end user, they are designed
  3376. // to be unmatchable by the tokenizer, therefore tokens from the vocab, which are unmatchable by the tokenizer
  3377. // are special tokens.
  3378. // From testing, this appears to correlate 1:1 with special tokens.
  3379. //
  3380. // Counting special tokens and verifying in only one direction
  3381. // is sufficient to detect difference in those two sets.
  3382. //
  3383. uint32_t special_tokens_count_by_type = 0;
  3384. uint32_t special_tokens_count_from_verification = 0;
  3385. bool special_tokens_definition_mismatch = false;
  3386. for (const auto & t : vocab.token_to_id) {
  3387. const auto & token = t.first;
  3388. const auto & id = t.second;
  3389. // Count all non-normal tokens in the vocab while iterating
  3390. if (vocab.id_to_token[id].type != LLAMA_TOKEN_TYPE_NORMAL) {
  3391. special_tokens_count_by_type++;
  3392. }
  3393. // Skip single character tokens
  3394. if (token.length() > 1) {
  3395. bool is_tokenizable = false;
  3396. // Split token string representation in two, in all possible ways
  3397. // and check if both halves can be matched to a valid token
  3398. for (unsigned i = 1; i < token.length();) {
  3399. const auto left = token.substr(0, i);
  3400. const auto right = token.substr(i);
  3401. // check if we didnt partition in the middle of a utf sequence
  3402. auto utf = utf8_len(left.at(left.length() - 1));
  3403. if (utf == 1) {
  3404. if (vocab.token_to_id.find(left) != vocab.token_to_id.end() &&
  3405. vocab.token_to_id.find(right) != vocab.token_to_id.end() ) {
  3406. is_tokenizable = true;
  3407. break;
  3408. }
  3409. i++;
  3410. } else {
  3411. // skip over the rest of multibyte utf sequence
  3412. i += utf - 1;
  3413. }
  3414. }
  3415. if (!is_tokenizable) {
  3416. // Some tokens are multibyte, but they are utf sequences with equivalent text length of 1
  3417. // it's faster to re-filter them here, since there are way less candidates now
  3418. // Calculate a total "utf" length of a token string representation
  3419. size_t utf8_str_len = 0;
  3420. for (unsigned i = 0; i < token.length();) {
  3421. utf8_str_len++;
  3422. i += utf8_len(token.at(i));
  3423. }
  3424. // And skip the ones which are one character
  3425. if (utf8_str_len > 1) {
  3426. // At this point what we have left are special tokens only
  3427. vocab.special_tokens_cache[token] = id;
  3428. // Count manually found special tokens
  3429. special_tokens_count_from_verification++;
  3430. // If this manually found special token is not marked as such, flag a mismatch
  3431. if (vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL) {
  3432. special_tokens_definition_mismatch = true;
  3433. }
  3434. }
  3435. }
  3436. }
  3437. }
  3438. if (special_tokens_definition_mismatch || special_tokens_count_from_verification != special_tokens_count_by_type) {
  3439. LLAMA_LOG_WARN("%s: mismatch in special tokens definition ( %u/%zu vs %u/%zu ).\n",
  3440. __func__,
  3441. special_tokens_count_from_verification, vocab.id_to_token.size(),
  3442. special_tokens_count_by_type, vocab.id_to_token.size()
  3443. );
  3444. } else {
  3445. LLAMA_LOG_INFO("%s: special tokens definition check successful ( %u/%zu ).\n",
  3446. __func__,
  3447. special_tokens_count_from_verification, vocab.id_to_token.size()
  3448. );
  3449. }
  3450. }
  3451. }
  3452. static void llm_load_print_meta(llama_model_loader & ml, llama_model & model) {
  3453. const auto & hparams = model.hparams;
  3454. const auto & vocab = model.vocab;
  3455. const char * rope_scaling_type = LLAMA_ROPE_SCALING_TYPES.at(hparams.rope_scaling_type_train);
  3456. // hparams
  3457. LLAMA_LOG_INFO("%s: format = %s\n", __func__, llama_file_version_name(ml.fver));
  3458. LLAMA_LOG_INFO("%s: arch = %s\n", __func__, LLM_ARCH_NAMES.at(model.arch));
  3459. LLAMA_LOG_INFO("%s: vocab type = %s\n", __func__, llama_model_vocab_type_name(vocab.type));
  3460. LLAMA_LOG_INFO("%s: n_vocab = %u\n", __func__, hparams.n_vocab);
  3461. LLAMA_LOG_INFO("%s: n_merges = %u\n", __func__, (int) vocab.bpe_ranks.size());
  3462. LLAMA_LOG_INFO("%s: n_ctx_train = %u\n", __func__, hparams.n_ctx_train);
  3463. LLAMA_LOG_INFO("%s: n_embd = %u\n", __func__, hparams.n_embd);
  3464. LLAMA_LOG_INFO("%s: n_head = %u\n", __func__, hparams.n_head);
  3465. LLAMA_LOG_INFO("%s: n_head_kv = %u\n", __func__, hparams.n_head_kv);
  3466. LLAMA_LOG_INFO("%s: n_layer = %u\n", __func__, hparams.n_layer);
  3467. LLAMA_LOG_INFO("%s: n_rot = %u\n", __func__, hparams.n_rot);
  3468. LLAMA_LOG_INFO("%s: n_embd_head_k = %u\n", __func__, hparams.n_embd_head_k);
  3469. LLAMA_LOG_INFO("%s: n_embd_head_v = %u\n", __func__, hparams.n_embd_head_v);
  3470. LLAMA_LOG_INFO("%s: n_gqa = %u\n", __func__, hparams.n_gqa());
  3471. LLAMA_LOG_INFO("%s: n_embd_k_gqa = %u\n", __func__, hparams.n_embd_k_gqa());
  3472. LLAMA_LOG_INFO("%s: n_embd_v_gqa = %u\n", __func__, hparams.n_embd_v_gqa());
  3473. LLAMA_LOG_INFO("%s: f_norm_eps = %.1e\n", __func__, hparams.f_norm_eps);
  3474. LLAMA_LOG_INFO("%s: f_norm_rms_eps = %.1e\n", __func__, hparams.f_norm_rms_eps);
  3475. LLAMA_LOG_INFO("%s: f_clamp_kqv = %.1e\n", __func__, hparams.f_clamp_kqv);
  3476. LLAMA_LOG_INFO("%s: f_max_alibi_bias = %.1e\n", __func__, hparams.f_max_alibi_bias);
  3477. LLAMA_LOG_INFO("%s: f_logit_scale = %.1e\n", __func__, hparams.f_logit_scale);
  3478. LLAMA_LOG_INFO("%s: n_ff = %u\n", __func__, hparams.n_ff);
  3479. LLAMA_LOG_INFO("%s: n_expert = %u\n", __func__, hparams.n_expert);
  3480. LLAMA_LOG_INFO("%s: n_expert_used = %u\n", __func__, hparams.n_expert_used);
  3481. LLAMA_LOG_INFO("%s: causal attn = %d\n", __func__, hparams.causal_attn);
  3482. LLAMA_LOG_INFO("%s: pooling type = %d\n", __func__, hparams.pooling_type);
  3483. LLAMA_LOG_INFO("%s: rope type = %d\n", __func__, hparams.rope_type);
  3484. LLAMA_LOG_INFO("%s: rope scaling = %s\n", __func__, rope_scaling_type);
  3485. LLAMA_LOG_INFO("%s: freq_base_train = %.1f\n", __func__, hparams.rope_freq_base_train);
  3486. LLAMA_LOG_INFO("%s: freq_scale_train = %g\n", __func__, hparams.rope_freq_scale_train);
  3487. LLAMA_LOG_INFO("%s: n_yarn_orig_ctx = %u\n", __func__, hparams.n_yarn_orig_ctx);
  3488. LLAMA_LOG_INFO("%s: rope_finetuned = %s\n", __func__, hparams.rope_finetuned ? "yes" : "unknown");
  3489. LLAMA_LOG_INFO("%s: ssm_d_conv = %u\n", __func__, hparams.ssm_d_conv);
  3490. LLAMA_LOG_INFO("%s: ssm_d_inner = %u\n", __func__, hparams.ssm_d_inner);
  3491. LLAMA_LOG_INFO("%s: ssm_d_state = %u\n", __func__, hparams.ssm_d_state);
  3492. LLAMA_LOG_INFO("%s: ssm_dt_rank = %u\n", __func__, hparams.ssm_dt_rank);
  3493. LLAMA_LOG_INFO("%s: model type = %s\n", __func__, llama_model_type_name(model.type));
  3494. LLAMA_LOG_INFO("%s: model ftype = %s\n", __func__, llama_model_ftype_name(model.ftype).c_str());
  3495. if (ml.n_elements >= 1e12) {
  3496. LLAMA_LOG_INFO("%s: model params = %.2f T\n", __func__, ml.n_elements*1e-12);
  3497. } else if (ml.n_elements >= 1e9) {
  3498. LLAMA_LOG_INFO("%s: model params = %.2f B\n", __func__, ml.n_elements*1e-9);
  3499. } else if (ml.n_elements >= 1e6) {
  3500. LLAMA_LOG_INFO("%s: model params = %.2f M\n", __func__, ml.n_elements*1e-6);
  3501. } else {
  3502. LLAMA_LOG_INFO("%s: model params = %.2f K\n", __func__, ml.n_elements*1e-3);
  3503. }
  3504. if (ml.n_bytes < GiB) {
  3505. 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);
  3506. } else {
  3507. 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);
  3508. }
  3509. // general kv
  3510. LLAMA_LOG_INFO("%s: general.name = %s\n", __func__, model.name.c_str());
  3511. // special tokens
  3512. 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() ); }
  3513. 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() ); }
  3514. 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() ); }
  3515. 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() ); }
  3516. 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() ); }
  3517. 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() ); }
  3518. }
  3519. // Returns false if cancelled by progress_callback
  3520. static bool llm_load_tensors(
  3521. llama_model_loader & ml,
  3522. llama_model & model,
  3523. int n_gpu_layers,
  3524. enum llama_split_mode split_mode,
  3525. int main_gpu,
  3526. const float * tensor_split,
  3527. bool use_mlock,
  3528. llama_progress_callback progress_callback,
  3529. void * progress_callback_user_data) {
  3530. model.t_start_us = ggml_time_us();
  3531. auto & hparams = model.hparams;
  3532. model.split_mode = split_mode;
  3533. model.main_gpu = main_gpu;
  3534. model.n_gpu_layers = n_gpu_layers;
  3535. const int64_t n_layer = hparams.n_layer;
  3536. const int64_t i_gpu_start = std::max((int64_t) hparams.n_layer - n_gpu_layers, (int64_t) 0);
  3537. // there is very little benefit to offloading the input layer, so always keep it on the CPU
  3538. model.buft_input = llama_default_buffer_type_cpu(true);
  3539. //model.buft_input = llama_default_buffer_type_offload(main_gpu);
  3540. model.buft_layer.resize(n_layer);
  3541. // assign cpu layers
  3542. for (int64_t i = 0; i < i_gpu_start; ++i) {
  3543. model.buft_layer[i] = llama_default_buffer_type_cpu(true);
  3544. }
  3545. if (split_mode == LLAMA_SPLIT_MODE_LAYER) {
  3546. // calculate the split points
  3547. int device_count = llama_get_device_count();
  3548. bool all_zero = tensor_split == nullptr || std::all_of(tensor_split, tensor_split + device_count, [](float x) { return x == 0.0f; });
  3549. std::vector<float> splits(device_count);
  3550. if (all_zero) {
  3551. // default split, by free memory
  3552. for (int i = 0; i < device_count; ++i) {
  3553. splits[i] = llama_get_device_memory(i);
  3554. }
  3555. } else {
  3556. std::copy(tensor_split, tensor_split + device_count, splits.begin());
  3557. }
  3558. // sum and normalize the splits to get the split points
  3559. float split_sum = 0.0f;
  3560. for (int i = 0; i < device_count; ++i) {
  3561. split_sum += splits[i];
  3562. splits[i] = split_sum;
  3563. }
  3564. for (int i = 0; i < device_count; ++i) {
  3565. splits[i] /= split_sum;
  3566. }
  3567. // assign the repeating layers to the devices according to the splits
  3568. int act_gpu_layers = std::min(n_gpu_layers, (int)n_layer + 1);
  3569. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  3570. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(i - i_gpu_start)/act_gpu_layers) - splits.begin();
  3571. model.buft_layer[i] = llama_default_buffer_type_offload(layer_gpu);
  3572. }
  3573. // assign the output layer
  3574. if (n_gpu_layers > n_layer) {
  3575. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(act_gpu_layers - 1)/act_gpu_layers) - splits.begin();
  3576. model.buft_output = llama_default_buffer_type_offload(layer_gpu);
  3577. } else {
  3578. model.buft_output = llama_default_buffer_type_cpu(true);
  3579. }
  3580. } else {
  3581. ggml_backend_buffer_type_t split_buft;
  3582. if (split_mode == LLAMA_SPLIT_MODE_ROW) {
  3583. split_buft = llama_default_buffer_type_split(main_gpu, tensor_split);
  3584. } else {
  3585. // LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_LAYER in backends where it is not supported
  3586. split_buft = llama_default_buffer_type_offload(main_gpu);
  3587. }
  3588. // assign the repeating layers
  3589. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  3590. model.buft_layer[i] = {
  3591. split_buft,
  3592. llama_default_buffer_type_offload(main_gpu)
  3593. };
  3594. }
  3595. // assign the output layer
  3596. if (n_gpu_layers > n_layer) {
  3597. model.buft_output = {
  3598. split_buft,
  3599. llama_default_buffer_type_offload(main_gpu)
  3600. };
  3601. } else {
  3602. model.buft_output = llama_default_buffer_type_cpu(true);
  3603. }
  3604. }
  3605. // count used buffer types
  3606. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  3607. buft_layer_count[model.buft_input.buft]++;
  3608. buft_layer_count[model.buft_input.buft_matrix]++;
  3609. buft_layer_count[model.buft_output.buft]++;
  3610. buft_layer_count[model.buft_output.buft_matrix]++;
  3611. for (int64_t i = 0; i < n_layer; ++i) {
  3612. buft_layer_count[model.buft_layer[i].buft]++;
  3613. buft_layer_count[model.buft_layer[i].buft_matrix]++;
  3614. }
  3615. // create one context per buffer type
  3616. size_t ctx_size = ggml_tensor_overhead()*(ml.n_tensors + 1); // +1 for models where tok_embd is duplicated as output
  3617. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  3618. for (auto & it : buft_layer_count) {
  3619. struct ggml_init_params params = {
  3620. /*.mem_size =*/ ctx_size,
  3621. /*.mem_buffer =*/ NULL,
  3622. /*.no_alloc =*/ true,
  3623. };
  3624. ggml_context * ctx = ggml_init(params);
  3625. if (!ctx) {
  3626. throw std::runtime_error(format("failed to create context"));
  3627. }
  3628. ctx_map[it.first] = ctx;
  3629. model.ctxs.push_back(ctx);
  3630. }
  3631. LLAMA_LOG_INFO("%s: ggml ctx size = %7.2f MiB\n", __func__, model.ctxs.size()*ctx_size/1024.0/1024.0);
  3632. // create tensors for the weights
  3633. {
  3634. const int64_t n_embd = hparams.n_embd;
  3635. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3636. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  3637. const int64_t n_embd_gqa = n_embd_v_gqa;
  3638. const int64_t n_vocab = hparams.n_vocab;
  3639. const int64_t n_vocab_type = hparams.n_vocab_type;
  3640. const int64_t n_ff = hparams.n_ff;
  3641. GGML_ASSERT(n_embd_gqa == n_embd_k_gqa);
  3642. ggml_context * ctx_input = ctx_map.at(model.buft_input.buft);
  3643. ggml_context * ctx_output = ctx_map.at(model.buft_output.buft);
  3644. ggml_context * ctx_output_split = ctx_map.at(model.buft_output.buft_matrix);
  3645. auto ctx_for_layer = [&](int i) { return ctx_map.at(model.buft_layer[i].buft); };
  3646. auto ctx_for_layer_split = [&](int i) { return ctx_map.at(model.buft_layer[i].buft_matrix); };
  3647. model.layers.resize(n_layer);
  3648. const auto tn = LLM_TN(model.arch);
  3649. switch (model.arch) {
  3650. case LLM_ARCH_LLAMA:
  3651. case LLM_ARCH_REFACT:
  3652. case LLM_ARCH_MINICPM:
  3653. {
  3654. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3655. // output
  3656. {
  3657. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3658. if (model.arch != LLM_ARCH_MINICPM){
  3659. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  3660. // if output is NULL, init from the input tok embed
  3661. if (model.output == NULL) {
  3662. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3663. ml.n_created--; // artificial tensor
  3664. ml.size_data += ggml_nbytes(model.output);
  3665. }
  3666. }
  3667. }
  3668. for (int i = 0; i < n_layer; ++i) {
  3669. ggml_context * ctx_layer = ctx_for_layer(i);
  3670. ggml_context * ctx_split = ctx_for_layer_split(i);
  3671. auto & layer = model.layers[i];
  3672. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3673. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3674. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3675. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3676. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3677. // optional bias tensors
  3678. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, false);
  3679. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, false);
  3680. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, false);
  3681. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, false);
  3682. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3683. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd}, false);
  3684. if (layer.ffn_gate_inp == nullptr) {
  3685. GGML_ASSERT(hparams.n_expert == 0);
  3686. GGML_ASSERT(hparams.n_expert_used == 0);
  3687. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3688. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3689. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3690. } else {
  3691. GGML_ASSERT(hparams.n_expert > 0);
  3692. GGML_ASSERT(hparams.n_expert_used > 0);
  3693. // MoE branch
  3694. for (uint32_t x = 0; x < hparams.n_expert; ++x) {
  3695. layer.ffn_gate_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, x), {n_embd, n_ff});
  3696. layer.ffn_down_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, x), { n_ff, n_embd});
  3697. layer.ffn_up_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, x), {n_embd, n_ff});
  3698. }
  3699. }
  3700. }
  3701. } break;
  3702. case LLM_ARCH_BAICHUAN:
  3703. {
  3704. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3705. {
  3706. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3707. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3708. }
  3709. for (int i = 0; i < n_layer; ++i) {
  3710. ggml_context * ctx_layer = ctx_for_layer(i);
  3711. ggml_context * ctx_split = ctx_for_layer_split(i);
  3712. auto & layer = model.layers[i];
  3713. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3714. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3715. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3716. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3717. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3718. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3719. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3720. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3721. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3722. }
  3723. } break;
  3724. case LLM_ARCH_FALCON:
  3725. {
  3726. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3727. // output
  3728. {
  3729. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3730. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3731. if (gguf_find_tensor(ml.ctx_gguf, tn(LLM_TENSOR_OUTPUT, "weight").c_str()) >= 0) {
  3732. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3733. } else {
  3734. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}); // needs to be on GPU
  3735. ml.n_created--; // artificial tensor
  3736. ml.size_data += ggml_nbytes(model.output);
  3737. }
  3738. }
  3739. for (int i = 0; i < n_layer; ++i) {
  3740. ggml_context * ctx_layer = ctx_for_layer(i);
  3741. ggml_context * ctx_split = ctx_for_layer_split(i);
  3742. auto & layer = model.layers[i];
  3743. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3744. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3745. if (gguf_find_tensor(ml.ctx_gguf, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i).c_str()) >= 0) {
  3746. layer.attn_norm_2 = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i), {n_embd});
  3747. layer.attn_norm_2_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "bias", i), {n_embd});
  3748. }
  3749. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3750. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3751. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3752. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3753. }
  3754. } break;
  3755. case LLM_ARCH_STARCODER:
  3756. {
  3757. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3758. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3759. // output
  3760. {
  3761. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3762. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3763. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3764. }
  3765. for (int i = 0; i < n_layer; ++i) {
  3766. ggml_context * ctx_layer = ctx_for_layer(i);
  3767. ggml_context * ctx_split = ctx_for_layer_split(i);
  3768. auto & layer = model.layers[i];
  3769. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3770. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3771. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3772. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3773. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3774. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3775. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3776. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3777. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3778. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3779. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3780. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3781. }
  3782. } break;
  3783. case LLM_ARCH_PERSIMMON:
  3784. {
  3785. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3786. {
  3787. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3788. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3789. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3790. }
  3791. for (int i = 0; i < n_layer; ++i) {
  3792. ggml_context * ctx_layer = ctx_for_layer(i);
  3793. ggml_context * ctx_split = ctx_for_layer_split(i);
  3794. auto & layer = model.layers[i];
  3795. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3796. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3797. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3798. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3799. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3800. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3801. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3802. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3803. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3804. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3805. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3806. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3807. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {64});
  3808. layer.attn_q_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "bias", i), {64});
  3809. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {64});
  3810. layer.attn_k_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "bias", i), {64});
  3811. }
  3812. } break;
  3813. case LLM_ARCH_BERT:
  3814. case LLM_ARCH_NOMIC_BERT:
  3815. {
  3816. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3817. model.type_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_TYPES, "weight"), {n_embd, n_vocab_type});
  3818. if (model.arch == LLM_ARCH_BERT) {
  3819. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3820. }
  3821. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  3822. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  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. if (model.arch == LLM_ARCH_BERT) {
  3828. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3829. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  3830. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3831. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  3832. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3833. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  3834. } else {
  3835. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3836. }
  3837. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3838. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  3839. layer.attn_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "bias", i), {n_embd});
  3840. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3841. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3842. if (model.arch == LLM_ARCH_BERT) {
  3843. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3844. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3845. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3846. } else {
  3847. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3848. }
  3849. layer.layer_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd});
  3850. layer.layer_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "bias", i), {n_embd});
  3851. }
  3852. } break;
  3853. case LLM_ARCH_BLOOM:
  3854. {
  3855. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3856. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  3857. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  3858. // output
  3859. {
  3860. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3861. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3862. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3863. }
  3864. for (int i = 0; i < n_layer; ++i) {
  3865. ggml_context * ctx_layer = ctx_for_layer(i);
  3866. ggml_context * ctx_split = ctx_for_layer_split(i);
  3867. auto & layer = model.layers[i];
  3868. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3869. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3870. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3871. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3872. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3873. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3874. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3875. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3876. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3877. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3878. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3879. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3880. }
  3881. } break;
  3882. case LLM_ARCH_MPT:
  3883. {
  3884. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3885. // output
  3886. {
  3887. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3888. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, false);
  3889. // same as tok_embd, duplicated to allow offloading
  3890. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3891. ml.n_created--; // artificial tensor
  3892. ml.size_data += ggml_nbytes(model.output);
  3893. }
  3894. for (int i = 0; i < n_layer; ++i) {
  3895. ggml_context * ctx_layer = ctx_for_layer(i);
  3896. ggml_context * ctx_split = ctx_for_layer_split(i);
  3897. auto & layer = model.layers[i];
  3898. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3899. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, false);
  3900. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3901. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, false);
  3902. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3903. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, false);
  3904. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3905. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, false);
  3906. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3907. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, false);
  3908. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3909. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, false);
  3910. // AWQ ScaleActivation layer
  3911. layer.ffn_act = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_ACT, "scales", i), {n_ff}, false);
  3912. }
  3913. } break;
  3914. case LLM_ARCH_STABLELM:
  3915. {
  3916. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3917. // output
  3918. {
  3919. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3920. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3921. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3922. }
  3923. for (int i = 0; i < n_layer; ++i) {
  3924. ggml_context * ctx_layer = ctx_for_layer(i);
  3925. ggml_context * ctx_split = ctx_for_layer_split(i);
  3926. auto & layer = model.layers[i];
  3927. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3928. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3929. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3930. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3931. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3932. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3933. // optional bias tensors, present in Stable LM 2 1.6B
  3934. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, false);
  3935. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, false);
  3936. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, false);
  3937. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3938. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3939. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3940. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3941. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3942. }
  3943. } break;
  3944. case LLM_ARCH_QWEN:
  3945. {
  3946. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3947. // output
  3948. {
  3949. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3950. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3951. }
  3952. for (int i = 0; i < n_layer; ++i) {
  3953. ggml_context * ctx_layer = ctx_for_layer(i);
  3954. ggml_context * ctx_split = ctx_for_layer_split(i);
  3955. auto & layer = model.layers[i];
  3956. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3957. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd*3});
  3958. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd*3});
  3959. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3960. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3961. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff/2});
  3962. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff/2, n_embd});
  3963. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff/2});
  3964. }
  3965. } break;
  3966. case LLM_ARCH_QWEN2:
  3967. {
  3968. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3969. // output
  3970. {
  3971. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3972. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3973. }
  3974. for (int i = 0; i < n_layer; ++i) {
  3975. ggml_context * ctx_layer = ctx_for_layer(i);
  3976. ggml_context * ctx_split = ctx_for_layer_split(i);
  3977. auto & layer = model.layers[i];
  3978. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3979. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3980. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3981. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3982. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3983. // optional bias tensors
  3984. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  3985. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  3986. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  3987. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3988. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3989. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3990. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3991. }
  3992. } break;
  3993. case LLM_ARCH_PHI2:
  3994. {
  3995. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3996. // output
  3997. {
  3998. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3999. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4000. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4001. model.output_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT, "bias"), {n_vocab});
  4002. }
  4003. for (int i = 0; i < n_layer; ++i) {
  4004. ggml_context * ctx_layer = ctx_for_layer(i);
  4005. ggml_context * ctx_split = ctx_for_layer_split(i);
  4006. auto & layer = model.layers[i];
  4007. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4008. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4009. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, false);
  4010. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, false);
  4011. if (layer.wqkv == nullptr) {
  4012. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4013. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  4014. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4015. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  4016. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4017. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  4018. }
  4019. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4020. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4021. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4022. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4023. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4024. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4025. }
  4026. } break;
  4027. case LLM_ARCH_PLAMO:
  4028. {
  4029. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4030. // output
  4031. {
  4032. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4033. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4034. }
  4035. for (int i = 0; i < n_layer; ++i) {
  4036. ggml_context * ctx_layer = ctx_for_layer(i);
  4037. ggml_context * ctx_split = ctx_for_layer_split(i);
  4038. auto & layer = model.layers[i];
  4039. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4040. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4041. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4042. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4043. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4044. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4045. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4046. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4047. }
  4048. } break;
  4049. case LLM_ARCH_GPT2:
  4050. {
  4051. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4052. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  4053. // output
  4054. {
  4055. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4056. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4057. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4058. }
  4059. for (int i = 0; i < n_layer; ++i) {
  4060. ggml_context * ctx_layer = ctx_for_layer(i);
  4061. ggml_context * ctx_split = ctx_for_layer_split(i);
  4062. auto & layer = model.layers[i];
  4063. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4064. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4065. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4066. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  4067. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4068. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4069. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4070. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4071. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4072. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4073. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4074. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4075. }
  4076. } break;
  4077. case LLM_ARCH_CODESHELL:
  4078. {
  4079. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4080. // output
  4081. {
  4082. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4083. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4084. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4085. }
  4086. for (int i = 0; i < n_layer; ++i) {
  4087. ggml_context * ctx_layer = ctx_for_layer(i);
  4088. ggml_context * ctx_split = ctx_for_layer_split(i);
  4089. auto & layer = model.layers[i];
  4090. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4091. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4092. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4093. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  4094. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4095. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4096. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4097. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4098. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  4099. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4100. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4101. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  4102. }
  4103. } break;
  4104. case LLM_ARCH_ORION:
  4105. {
  4106. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4107. {
  4108. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4109. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4110. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4111. }
  4112. for (int i = 0; i < n_layer; ++i) {
  4113. ggml_context * ctx_layer = ctx_for_layer(i);
  4114. ggml_context * ctx_split = ctx_for_layer_split(i);
  4115. auto & layer = model.layers[i];
  4116. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4117. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4118. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4119. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4120. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4121. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4122. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4123. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  4124. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4125. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4126. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4127. }
  4128. } break;
  4129. case LLM_ARCH_INTERNLM2:
  4130. {
  4131. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4132. // output
  4133. {
  4134. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4135. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  4136. }
  4137. for (int i = 0; i < n_layer; ++i) {
  4138. ggml_context * ctx_layer = ctx_for_layer(i);
  4139. ggml_context * ctx_split = ctx_for_layer_split(i);
  4140. auto & layer = model.layers[i];
  4141. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4142. // layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  4143. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4144. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4145. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4146. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4147. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4148. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4149. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4150. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4151. }
  4152. } break;
  4153. case LLM_ARCH_GEMMA:
  4154. {
  4155. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4156. // output
  4157. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4158. 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
  4159. ml.n_created--; // artificial tensor
  4160. ml.size_data += ggml_nbytes(model.output);
  4161. const int64_t n_ff = hparams.n_ff;
  4162. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  4163. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  4164. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  4165. for (uint32_t 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_head_k * hparams.n_head});
  4171. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  4172. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  4173. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * hparams.n_head, n_embd});
  4174. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4175. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4176. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4177. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4178. }
  4179. } break;
  4180. case LLM_ARCH_STARCODER2:
  4181. {
  4182. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4183. // output
  4184. {
  4185. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4186. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  4187. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  4188. // if output is NULL, init from the input tok embed
  4189. if (model.output == NULL) {
  4190. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4191. ml.n_created--; // artificial tensor
  4192. ml.size_data += ggml_nbytes(model.output);
  4193. }
  4194. }
  4195. for (int i = 0; i < n_layer; ++i) {
  4196. ggml_context * ctx_layer = ctx_for_layer(i);
  4197. ggml_context * ctx_split = ctx_for_layer_split(i);
  4198. auto & layer = model.layers[i];
  4199. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4200. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  4201. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4202. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4203. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4204. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4205. // optional bias tensors
  4206. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  4207. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  4208. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  4209. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  4210. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  4211. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "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_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4214. // optional bias tensors
  4215. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  4216. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP , "bias", i), { n_ff});
  4217. }
  4218. } break;
  4219. case LLM_ARCH_MAMBA:
  4220. {
  4221. const int64_t d_conv = hparams.ssm_d_conv;
  4222. const int64_t d_inner = hparams.ssm_d_inner;
  4223. const int64_t d_state = hparams.ssm_d_state;
  4224. const int64_t dt_rank = hparams.ssm_dt_rank;
  4225. // only an expansion factor of 2 is supported for now
  4226. GGML_ASSERT(2 * n_embd == d_inner);
  4227. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4228. // output
  4229. {
  4230. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4231. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, false);
  4232. // if output is NULL, init from the input tok embed, duplicated to allow offloading
  4233. if (model.output == NULL) {
  4234. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4235. ml.n_created--; // artificial tensor
  4236. ml.size_data += ggml_nbytes(model.output);
  4237. }
  4238. }
  4239. for (int i = 0; i < n_layer; ++i) {
  4240. ggml_context * ctx_layer = ctx_for_layer(i);
  4241. ggml_context * ctx_split = ctx_for_layer_split(i);
  4242. auto & layer = model.layers[i];
  4243. // norm
  4244. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4245. layer.ssm_in = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_IN, "weight", i), {n_embd, 2*d_inner});
  4246. layer.ssm_conv1d = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_CONV1D, "weight", i), {d_conv, d_inner});
  4247. layer.ssm_conv1d_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_CONV1D, "bias", i), {d_inner});
  4248. layer.ssm_x = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_X, "weight", i), {d_inner, dt_rank + 2*d_state});
  4249. layer.ssm_dt = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_DT, "weight", i), {dt_rank, d_inner});
  4250. layer.ssm_dt_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_DT, "bias", i), {d_inner});
  4251. // no "weight" suffix for these
  4252. layer.ssm_a = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_A, i), {d_state, d_inner});
  4253. layer.ssm_d = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_SSM_D, i), {d_inner});
  4254. // out_proj
  4255. layer.ssm_out = ml.create_tensor(ctx_split, tn(LLM_TENSOR_SSM_OUT, "weight", i), {d_inner, n_embd});
  4256. }
  4257. } break;
  4258. case LLM_ARCH_COMMAND_R:
  4259. {
  4260. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4261. // output
  4262. {
  4263. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  4264. // init output from the input tok embed
  4265. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  4266. ml.n_created--; // artificial tensor
  4267. ml.size_data += ggml_nbytes(model.output);
  4268. }
  4269. for (int i = 0; i < n_layer; ++i) {
  4270. ggml_context * ctx_layer = ctx_for_layer(i);
  4271. ggml_context * ctx_split = ctx_for_layer_split(i);
  4272. auto & layer = model.layers[i];
  4273. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  4274. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  4275. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  4276. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  4277. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  4278. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  4279. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  4280. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  4281. }
  4282. } break;
  4283. default:
  4284. throw std::runtime_error("unknown architecture");
  4285. }
  4286. }
  4287. ml.done_getting_tensors();
  4288. ml.init_mapping(true, use_mlock ? &model.mlock_mmap : nullptr);
  4289. // create the backend buffers
  4290. std::vector<std::pair<ggml_context *, ggml_backend_buffer_t>> ctx_bufs;
  4291. for (auto & it : ctx_map) {
  4292. ggml_backend_buffer_type_t buft = it.first;
  4293. ggml_context * ctx = it.second;
  4294. ggml_backend_buffer_t buf = nullptr;
  4295. // only the mmap region containing the tensors in the model is mapped to the backend buffer
  4296. // 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
  4297. // this allows using partial offloading when the model size exceeds the metal buffer size, but not the RAM size
  4298. if (ml.use_mmap && buft == llama_default_buffer_type_cpu(true)) {
  4299. size_t first, last;
  4300. ml.get_mapping_range(&first, &last, ctx);
  4301. buf = ggml_backend_cpu_buffer_from_ptr((char *) ml.mapping->addr + first, last - first);
  4302. }
  4303. #ifdef GGML_USE_METAL
  4304. else if (ml.use_mmap && buft == ggml_backend_metal_buffer_type()) {
  4305. const size_t max_size = ggml_get_max_tensor_size(ctx);
  4306. size_t first, last;
  4307. ml.get_mapping_range(&first, &last, ctx);
  4308. buf = ggml_backend_metal_buffer_from_ptr((char *) ml.mapping->addr + first, last - first, max_size);
  4309. }
  4310. #endif
  4311. else {
  4312. buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  4313. if (buf != nullptr && use_mlock && ggml_backend_buffer_is_host(buf)) {
  4314. model.mlock_bufs.emplace_back(new llama_mlock);
  4315. auto & mlock_buf = model.mlock_bufs.back();
  4316. mlock_buf->init (ggml_backend_buffer_get_base(buf));
  4317. mlock_buf->grow_to(ggml_backend_buffer_get_size(buf));
  4318. }
  4319. }
  4320. if (buf == nullptr) {
  4321. throw std::runtime_error("failed to allocate buffer");
  4322. }
  4323. // indicate that this buffer contains weights
  4324. // 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
  4325. ggml_backend_buffer_set_usage(buf, GGML_BACKEND_BUFFER_USAGE_WEIGHTS);
  4326. model.bufs.push_back(buf);
  4327. ctx_bufs.emplace_back(ctx, buf);
  4328. }
  4329. if (llama_supports_gpu_offload()) {
  4330. const int n_gpu = std::min(n_gpu_layers, int(hparams.n_layer));
  4331. LLAMA_LOG_INFO("%s: offloading %d repeating layers to GPU\n", __func__, n_gpu);
  4332. if (n_gpu_layers > (int) hparams.n_layer) {
  4333. LLAMA_LOG_INFO("%s: offloading non-repeating layers to GPU\n", __func__);
  4334. }
  4335. const int max_backend_supported_layers = hparams.n_layer + 1;
  4336. const int max_offloadable_layers = hparams.n_layer + 1;
  4337. LLAMA_LOG_INFO("%s: offloaded %d/%d layers to GPU\n", __func__, std::min(n_gpu_layers, max_offloadable_layers), max_backend_supported_layers);
  4338. }
  4339. // print memory requirements
  4340. for (ggml_backend_buffer_t buf : model.bufs) {
  4341. 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);
  4342. }
  4343. // populate tensors_by_name
  4344. for (ggml_context * ctx : model.ctxs) {
  4345. for (auto * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  4346. model.tensors_by_name.emplace_back(ggml_get_name(cur), cur);
  4347. }
  4348. }
  4349. // load tensor data
  4350. for (auto & it : ctx_bufs) {
  4351. ggml_context * ctx = it.first;
  4352. ggml_backend_buffer_t buf = it.second;
  4353. if (!ml.load_all_data(ctx, progress_callback, progress_callback_user_data, buf, use_mlock ? &model.mlock_mmap : NULL)) {
  4354. return false;
  4355. }
  4356. }
  4357. model.mapping = std::move(ml.mapping);
  4358. // loading time will be recalculate after the first eval, so
  4359. // we take page faults deferred by mmap() into consideration
  4360. model.t_load_us = ggml_time_us() - model.t_start_us;
  4361. return true;
  4362. }
  4363. // Returns 0 on success, -1 on error, and -2 on cancellation via llama_progress_callback
  4364. static int llama_model_load(const std::string & fname, llama_model & model, llama_model_params & params) {
  4365. try {
  4366. llama_model_loader ml(fname, params.use_mmap, params.kv_overrides);
  4367. model.hparams.vocab_only = params.vocab_only;
  4368. try {
  4369. llm_load_arch(ml, model);
  4370. } catch(const std::exception & e) {
  4371. throw std::runtime_error("error loading model architecture: " + std::string(e.what()));
  4372. }
  4373. try {
  4374. llm_load_hparams(ml, model);
  4375. } catch(const std::exception & e) {
  4376. throw std::runtime_error("error loading model hyperparameters: " + std::string(e.what()));
  4377. }
  4378. try {
  4379. llm_load_vocab(ml, model);
  4380. } catch(const std::exception & e) {
  4381. throw std::runtime_error("error loading model vocabulary: " + std::string(e.what()));
  4382. }
  4383. llm_load_print_meta(ml, model);
  4384. if (model.vocab.type != LLAMA_VOCAB_TYPE_NONE &&
  4385. model.hparams.n_vocab != model.vocab.id_to_token.size()) {
  4386. throw std::runtime_error("vocab size mismatch");
  4387. }
  4388. if (params.vocab_only) {
  4389. LLAMA_LOG_INFO("%s: vocab only - skipping tensors\n", __func__);
  4390. return 0;
  4391. }
  4392. #ifdef GGML_USE_KOMPUTE
  4393. if (params.n_gpu_layers > 0 && (
  4394. !(model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON)
  4395. || !(
  4396. model.ftype == LLAMA_FTYPE_ALL_F32 ||
  4397. model.ftype == LLAMA_FTYPE_MOSTLY_F16 ||
  4398. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ||
  4399. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_1
  4400. )
  4401. )) {
  4402. // TODO(cebtenzzre): propagate this error outside of llama_load_model_from_file
  4403. LLAMA_LOG_WARN("%s: disabling Kompute due to unsupported model arch or quantization\n", __func__);
  4404. params.n_gpu_layers = 0;
  4405. }
  4406. #endif
  4407. #ifdef GGML_USE_SYCL
  4408. if (params.split_mode == LLAMA_SPLIT_MODE_NONE) {
  4409. ggml_backend_sycl_set_single_device_mode(params.main_gpu);
  4410. //SYCL use device index (0, 1, 2) directly, uer input device id, then convert to device index.
  4411. params.main_gpu = ggml_backend_sycl_get_device_index(params.main_gpu);
  4412. } else {
  4413. ggml_backend_sycl_set_mul_device_mode();
  4414. }
  4415. #endif
  4416. if (!llm_load_tensors(
  4417. ml, model, params.n_gpu_layers, params.split_mode, params.main_gpu, params.tensor_split, params.use_mlock,
  4418. params.progress_callback, params.progress_callback_user_data
  4419. )) {
  4420. return -2;
  4421. }
  4422. } catch (const std::exception & err) {
  4423. LLAMA_LOG_ERROR("%s: error loading model: %s\n", __func__, err.what());
  4424. return -1;
  4425. }
  4426. return 0;
  4427. }
  4428. //
  4429. // llm_build
  4430. //
  4431. using llm_build_cb = std::function<void(struct ggml_tensor * cur, const char * name, int nl)>;
  4432. enum llm_ffn_op_type {
  4433. LLM_FFN_SILU,
  4434. LLM_FFN_GELU,
  4435. LLM_FFN_RELU,
  4436. LLM_FFN_RELU_SQR,
  4437. };
  4438. enum llm_ffn_gate_type {
  4439. LLM_FFN_SEQ,
  4440. LLM_FFN_PAR, // ffn_gate is parallel to ffn_up
  4441. };
  4442. enum llm_norm_type {
  4443. LLM_NORM,
  4444. LLM_NORM_RMS,
  4445. };
  4446. static struct ggml_tensor * llm_build_inp_embd(
  4447. struct ggml_context * ctx,
  4448. struct llama_context & lctx,
  4449. const llama_hparams & hparams,
  4450. const llama_batch & batch,
  4451. struct ggml_tensor * tok_embd,
  4452. const llm_build_cb & cb) {
  4453. const int64_t n_embd = hparams.n_embd;
  4454. struct ggml_tensor * inpL;
  4455. if (batch.token) {
  4456. lctx.inp_tokens = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, batch.n_tokens);
  4457. cb(lctx.inp_tokens, "inp_tokens", -1);
  4458. ggml_set_input(lctx.inp_tokens);
  4459. inpL = ggml_get_rows(ctx, tok_embd, lctx.inp_tokens);
  4460. } else {
  4461. #ifdef GGML_USE_MPI
  4462. GGML_ASSERT(false && "not implemented");
  4463. #endif
  4464. lctx.inp_embd = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, batch.n_tokens);
  4465. inpL = lctx.inp_embd;
  4466. ggml_set_input(lctx.inp_embd);
  4467. }
  4468. cb(inpL, "inp_embd", -1);
  4469. return inpL;
  4470. }
  4471. static void llm_build_kv_store(
  4472. struct ggml_context * ctx,
  4473. const llama_hparams & hparams,
  4474. const llama_kv_cache & kv,
  4475. struct ggml_cgraph * graph,
  4476. struct ggml_tensor * k_cur,
  4477. struct ggml_tensor * v_cur,
  4478. int64_t n_ctx,
  4479. int32_t n_tokens,
  4480. int32_t kv_head,
  4481. const llm_build_cb & cb,
  4482. int64_t il) {
  4483. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  4484. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  4485. GGML_ASSERT(kv.size == n_ctx);
  4486. // compute the transposed [n_tokens, n_embd] V matrix
  4487. struct ggml_tensor * v_cur_t = ggml_transpose(ctx, ggml_reshape_2d(ctx, v_cur, n_embd_v_gqa, n_tokens));
  4488. //struct ggml_tensor * v_cur_t = ggml_transpose(ctx, v_cur); // TODO: reshape above is likely not needed
  4489. cb(v_cur_t, "v_cur_t", il);
  4490. struct ggml_tensor * k_cache_view = ggml_view_1d(ctx, kv.k_l[il], n_tokens*n_embd_k_gqa,
  4491. (ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa))*kv_head);
  4492. cb(k_cache_view, "k_cache_view", il);
  4493. struct ggml_tensor * v_cache_view = ggml_view_2d(ctx, kv.v_l[il], n_tokens, n_embd_v_gqa,
  4494. ( n_ctx)*ggml_element_size(kv.v_l[il]),
  4495. (kv_head)*ggml_element_size(kv.v_l[il]));
  4496. cb(v_cache_view, "v_cache_view", il);
  4497. // important: storing RoPE-ed version of K in the KV cache!
  4498. ggml_build_forward_expand(graph, ggml_cpy(ctx, k_cur, k_cache_view));
  4499. ggml_build_forward_expand(graph, ggml_cpy(ctx, v_cur_t, v_cache_view));
  4500. }
  4501. static struct ggml_tensor * llm_build_norm(
  4502. struct ggml_context * ctx,
  4503. struct ggml_tensor * cur,
  4504. const llama_hparams & hparams,
  4505. struct ggml_tensor * mw,
  4506. struct ggml_tensor * mb,
  4507. llm_norm_type type,
  4508. const llm_build_cb & cb,
  4509. int il) {
  4510. switch (type) {
  4511. case LLM_NORM: cur = ggml_norm (ctx, cur, hparams.f_norm_eps); break;
  4512. case LLM_NORM_RMS: cur = ggml_rms_norm(ctx, cur, hparams.f_norm_rms_eps); break;
  4513. }
  4514. if (mw || mb) {
  4515. cb(cur, "norm", il);
  4516. }
  4517. if (mw) {
  4518. cur = ggml_mul(ctx, cur, mw);
  4519. if (mb) {
  4520. cb(cur, "norm_w", il);
  4521. }
  4522. }
  4523. if (mb) {
  4524. cur = ggml_add(ctx, cur, mb);
  4525. }
  4526. return cur;
  4527. }
  4528. static struct ggml_tensor * llm_build_ffn(
  4529. struct ggml_context * ctx,
  4530. struct ggml_tensor * cur,
  4531. struct ggml_tensor * up,
  4532. struct ggml_tensor * up_b,
  4533. struct ggml_tensor * gate,
  4534. struct ggml_tensor * gate_b,
  4535. struct ggml_tensor * down,
  4536. struct ggml_tensor * down_b,
  4537. struct ggml_tensor * act_scales,
  4538. llm_ffn_op_type type_op,
  4539. llm_ffn_gate_type type_gate,
  4540. const llm_build_cb & cb,
  4541. int il) {
  4542. struct ggml_tensor * tmp = ggml_mul_mat(ctx, up, cur);
  4543. cb(tmp, "ffn_up", il);
  4544. if (up_b) {
  4545. tmp = ggml_add(ctx, tmp, up_b);
  4546. cb(tmp, "ffn_up_b", il);
  4547. }
  4548. if (gate) {
  4549. switch (type_gate) {
  4550. case LLM_FFN_SEQ:
  4551. {
  4552. cur = ggml_mul_mat(ctx, gate, tmp);
  4553. cb(cur, "ffn_gate", il);
  4554. } break;
  4555. case LLM_FFN_PAR:
  4556. {
  4557. cur = ggml_mul_mat(ctx, gate, cur);
  4558. cb(cur, "ffn_gate", il);
  4559. } break;
  4560. }
  4561. if (gate_b) {
  4562. cur = ggml_add(ctx, cur, gate_b);
  4563. cb(cur, "ffn_gate_b", il);
  4564. }
  4565. } else {
  4566. cur = tmp;
  4567. }
  4568. switch (type_op) {
  4569. case LLM_FFN_SILU:
  4570. {
  4571. cur = ggml_silu(ctx, cur);
  4572. cb(cur, "ffn_silu", il);
  4573. } break;
  4574. case LLM_FFN_GELU:
  4575. {
  4576. cur = ggml_gelu(ctx, cur);
  4577. cb(cur, "ffn_gelu", il);
  4578. if (act_scales != NULL) {
  4579. cur = ggml_div(ctx, cur, act_scales);
  4580. cb(cur, "ffn_act", il);
  4581. }
  4582. } break;
  4583. case LLM_FFN_RELU:
  4584. {
  4585. cur = ggml_relu(ctx, cur);
  4586. cb(cur, "ffn_relu", il);
  4587. } break;
  4588. case LLM_FFN_RELU_SQR:
  4589. {
  4590. cur = ggml_relu(ctx, cur);
  4591. cb(cur, "ffn_relu", il);
  4592. cur = ggml_sqr(ctx, cur);
  4593. cb(cur, "ffn_sqr(relu)", il);
  4594. } break;
  4595. }
  4596. if (type_gate == LLM_FFN_PAR) {
  4597. cur = ggml_mul(ctx, cur, tmp);
  4598. cb(cur, "ffn_gate_par", il);
  4599. }
  4600. cur = ggml_mul_mat(ctx, down, cur);
  4601. if (down_b) {
  4602. cb(cur, "ffn_down", il);
  4603. }
  4604. if (down_b) {
  4605. cur = ggml_add(ctx, cur, down_b);
  4606. }
  4607. return cur;
  4608. }
  4609. // if max_alibi_bias > 0 then apply ALiBi
  4610. static struct ggml_tensor * llm_build_kqv(
  4611. struct ggml_context * ctx,
  4612. const llama_model & model,
  4613. const llama_hparams & hparams,
  4614. const llama_kv_cache & kv,
  4615. struct ggml_cgraph * graph,
  4616. struct ggml_tensor * wo,
  4617. struct ggml_tensor * wo_b,
  4618. struct ggml_tensor * q_cur,
  4619. struct ggml_tensor * kq_mask,
  4620. struct ggml_tensor * kq_pos,
  4621. int64_t n_ctx,
  4622. int32_t n_tokens,
  4623. int32_t n_kv,
  4624. float kq_scale,
  4625. const llm_build_cb & cb,
  4626. int il) {
  4627. const int64_t n_head = hparams.n_head;
  4628. const int64_t n_head_kv = hparams.n_head_kv;
  4629. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  4630. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  4631. const int64_t n_embd_head_v = hparams.n_embd_head_v;
  4632. struct ggml_tensor * q = ggml_permute(ctx, q_cur, 0, 2, 1, 3);
  4633. cb(q, "q", il);
  4634. struct ggml_tensor * k =
  4635. ggml_view_3d(ctx, kv.k_l[il],
  4636. n_embd_head_k, n_kv, n_head_kv,
  4637. ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa),
  4638. ggml_row_size(kv.k_l[il]->type, n_embd_head_k),
  4639. 0);
  4640. cb(k, "k", il);
  4641. struct ggml_tensor * kq = ggml_mul_mat(ctx, k, q);
  4642. cb(kq, "kq", il);
  4643. if (model.arch == LLM_ARCH_PHI2) {
  4644. // for this arch, we need to perform the KQ multiplication with F32 precision, otherwise we get NaNs
  4645. // ref: https://github.com/ggerganov/llama.cpp/pull/4490#issuecomment-1859055847
  4646. ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  4647. }
  4648. #if defined(GGML_USE_KOMPUTE)
  4649. #pragma message("TODO: ALiBi support in ggml_soft_max_ext is not implemented for Kompute")
  4650. #pragma message(" Falling back to ggml_alibi(). Will become an error in Mar 2024")
  4651. #pragma message("ref: https://github.com/ggerganov/llama.cpp/pull/5488")
  4652. if (hparams.f_max_alibi_bias > 0.0f) {
  4653. kq = ggml_scale(ctx, kq, kq_scale);
  4654. cb(kq, "kq_scaled", il);
  4655. kq = ggml_alibi(ctx, kq, /*n_past*/ 0, n_head, hparams.f_max_alibi_bias);
  4656. cb(kq, "kq_scaled_alibi", il);
  4657. kq = ggml_add(ctx, kq, kq_mask);
  4658. cb(kq, "kq_masked", il);
  4659. kq = ggml_soft_max(ctx, kq);
  4660. cb(kq, "kq_soft_max", il);
  4661. } else
  4662. #endif
  4663. {
  4664. kq = ggml_soft_max_ext(ctx, kq, kq_mask, kq_pos, kq_scale, hparams.f_max_alibi_bias);
  4665. cb(kq, "kq_soft_max_ext", il);
  4666. }
  4667. GGML_ASSERT(kv.size == n_ctx);
  4668. // split cached v into n_head heads
  4669. struct ggml_tensor * v =
  4670. ggml_view_3d(ctx, kv.v_l[il],
  4671. n_kv, n_embd_head_v, n_head_kv,
  4672. ggml_element_size(kv.v_l[il])*n_ctx,
  4673. ggml_element_size(kv.v_l[il])*n_ctx*n_embd_head_v,
  4674. 0);
  4675. cb(v, "v", il);
  4676. struct ggml_tensor * kqv = ggml_mul_mat(ctx, v, kq);
  4677. cb(kqv, "kqv", il);
  4678. struct ggml_tensor * kqv_merged = ggml_permute(ctx, kqv, 0, 2, 1, 3);
  4679. cb(kqv_merged, "kqv_merged", il);
  4680. struct ggml_tensor * cur = ggml_cont_2d(ctx, kqv_merged, n_embd_head_k*n_head, n_tokens);
  4681. cb(cur, "kqv_merged_cont", il);
  4682. ggml_build_forward_expand(graph, cur);
  4683. cur = ggml_mul_mat(ctx, wo, cur);
  4684. if (wo_b) {
  4685. cb(cur, "kqv_wo", il);
  4686. }
  4687. if (wo_b) {
  4688. cur = ggml_add(ctx, cur, wo_b);
  4689. }
  4690. return cur;
  4691. }
  4692. static struct ggml_tensor * llm_build_kv(
  4693. struct ggml_context * ctx,
  4694. const llama_model & model,
  4695. const llama_hparams & hparams,
  4696. const llama_kv_cache & kv,
  4697. struct ggml_cgraph * graph,
  4698. struct ggml_tensor * wo,
  4699. struct ggml_tensor * wo_b,
  4700. struct ggml_tensor * k_cur,
  4701. struct ggml_tensor * v_cur,
  4702. struct ggml_tensor * q_cur,
  4703. struct ggml_tensor * kq_mask,
  4704. struct ggml_tensor * kq_pos,
  4705. int64_t n_ctx,
  4706. int32_t n_tokens,
  4707. int32_t kv_head,
  4708. int32_t n_kv,
  4709. float kq_scale,
  4710. const llm_build_cb & cb,
  4711. int il) {
  4712. // these nodes are added to the graph together so that they are not reordered
  4713. // by doing so, the number of splits in the graph is reduced
  4714. ggml_build_forward_expand(graph, q_cur);
  4715. ggml_build_forward_expand(graph, k_cur);
  4716. ggml_build_forward_expand(graph, v_cur);
  4717. llm_build_kv_store(ctx, hparams, kv, graph, k_cur, v_cur, n_ctx, n_tokens, kv_head, cb, il);
  4718. struct ggml_tensor * cur;
  4719. cur = llm_build_kqv(ctx, model, hparams, kv, graph, wo, wo_b,
  4720. q_cur, kq_mask, kq_pos, n_ctx, n_tokens, n_kv, kq_scale, cb, il);
  4721. cb(cur, "kqv_out", il);
  4722. return cur;
  4723. }
  4724. struct llm_build_context {
  4725. const llama_model & model;
  4726. llama_context & lctx;
  4727. const llama_hparams & hparams;
  4728. const llama_cparams & cparams;
  4729. const llama_batch & batch;
  4730. const llama_kv_cache & kv_self;
  4731. const int64_t n_embd;
  4732. const int64_t n_layer;
  4733. const int64_t n_rot;
  4734. const int64_t n_ctx; // user-specified context size (can be different from n_ctx_train)
  4735. const int64_t n_head;
  4736. const int64_t n_head_kv;
  4737. const int64_t n_embd_head_k;
  4738. const int64_t n_embd_k_gqa;
  4739. const int64_t n_embd_head_v;
  4740. const int64_t n_embd_v_gqa;
  4741. const int64_t n_expert;
  4742. const int64_t n_expert_used;
  4743. const float freq_base;
  4744. const float freq_scale;
  4745. const float ext_factor;
  4746. const float attn_factor;
  4747. const float beta_fast;
  4748. const float beta_slow;
  4749. const float norm_eps;
  4750. const float norm_rms_eps;
  4751. const int32_t n_tokens;
  4752. const int32_t n_kv; // size of KV cache to consider (n_kv <= n_ctx)
  4753. const int32_t kv_head; // index of where we store new KV data in the cache
  4754. const int32_t n_orig_ctx;
  4755. const enum llama_pooling_type pooling_type;
  4756. const enum llama_rope_type rope_type;
  4757. const llm_build_cb & cb;
  4758. std::vector<uint8_t> & buf_compute_meta;
  4759. struct ggml_context * ctx0 = nullptr;
  4760. // TODO: consider making the entire interface noexcept
  4761. llm_build_context(
  4762. llama_context & lctx,
  4763. const llama_batch & batch,
  4764. const llm_build_cb & cb,
  4765. bool worst_case) :
  4766. model (lctx.model),
  4767. lctx (lctx),
  4768. hparams (model.hparams),
  4769. cparams (lctx.cparams),
  4770. batch (batch),
  4771. kv_self (lctx.kv_self),
  4772. n_embd (hparams.n_embd),
  4773. n_layer (hparams.n_layer),
  4774. n_rot (hparams.n_rot),
  4775. n_ctx (cparams.n_ctx),
  4776. n_head (hparams.n_head),
  4777. n_head_kv (hparams.n_head_kv),
  4778. n_embd_head_k (hparams.n_embd_head_k),
  4779. n_embd_k_gqa (hparams.n_embd_k_gqa()),
  4780. n_embd_head_v (hparams.n_embd_head_v),
  4781. n_embd_v_gqa (hparams.n_embd_v_gqa()),
  4782. n_expert (hparams.n_expert),
  4783. n_expert_used (hparams.n_expert_used),
  4784. freq_base (cparams.rope_freq_base),
  4785. freq_scale (cparams.rope_freq_scale),
  4786. ext_factor (cparams.yarn_ext_factor),
  4787. attn_factor (cparams.yarn_attn_factor),
  4788. beta_fast (cparams.yarn_beta_fast),
  4789. beta_slow (cparams.yarn_beta_slow),
  4790. norm_eps (hparams.f_norm_eps),
  4791. norm_rms_eps (hparams.f_norm_rms_eps),
  4792. n_tokens (batch.n_tokens),
  4793. n_kv (worst_case ? kv_self.size : kv_self.n),
  4794. kv_head (worst_case ? (kv_self.recurrent ? 0 : kv_self.size - n_tokens) : kv_self.head),
  4795. n_orig_ctx (cparams.n_yarn_orig_ctx),
  4796. pooling_type (cparams.pooling_type),
  4797. rope_type (hparams.rope_type),
  4798. cb (cb),
  4799. buf_compute_meta (lctx.buf_compute_meta) {
  4800. // all initializations should be done in init()
  4801. }
  4802. void init() {
  4803. struct ggml_init_params params = {
  4804. /*.mem_size =*/ buf_compute_meta.size(),
  4805. /*.mem_buffer =*/ buf_compute_meta.data(),
  4806. /*.no_alloc =*/ true,
  4807. };
  4808. ctx0 = ggml_init(params);
  4809. lctx.inp_tokens = nullptr;
  4810. lctx.inp_embd = nullptr;
  4811. lctx.inp_pos = nullptr;
  4812. lctx.inp_KQ_mask = nullptr;
  4813. lctx.inp_KQ_pos = nullptr;
  4814. lctx.inp_K_shift = nullptr;
  4815. lctx.inp_mean = nullptr;
  4816. lctx.inp_cls = nullptr;
  4817. lctx.inp_s_copy = nullptr;
  4818. lctx.inp_s_mask = nullptr;
  4819. lctx.inp_s_seq = nullptr;
  4820. }
  4821. void free() {
  4822. if (ctx0) {
  4823. ggml_free(ctx0);
  4824. ctx0 = nullptr;
  4825. }
  4826. }
  4827. struct ggml_cgraph * build_k_shift() {
  4828. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4829. GGML_ASSERT(kv_self.size == n_ctx);
  4830. lctx.inp_K_shift = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_ctx);
  4831. cb(lctx.inp_K_shift, "K_shift", -1);
  4832. ggml_set_input(lctx.inp_K_shift);
  4833. for (int il = 0; il < n_layer; ++il) {
  4834. struct ggml_tensor * tmp =
  4835. // we rotate only the first n_rot dimensions
  4836. ggml_rope_custom_inplace(ctx0,
  4837. ggml_view_3d(ctx0, kv_self.k_l[il],
  4838. n_embd_head_k, n_head_kv, n_ctx,
  4839. ggml_row_size(kv_self.k_l[il]->type, n_embd_head_k),
  4840. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  4841. 0),
  4842. lctx.inp_K_shift, n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  4843. ext_factor, attn_factor, beta_fast, beta_slow);
  4844. cb(tmp, "K_shifted", il);
  4845. ggml_build_forward_expand(gf, tmp);
  4846. }
  4847. return gf;
  4848. }
  4849. struct ggml_cgraph * build_s_copy() {
  4850. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4851. GGML_ASSERT(kv_self.recurrent);
  4852. struct ggml_tensor * state_copy = build_inp_s_copy();
  4853. for (int il = 0; il < n_layer; ++il) {
  4854. struct ggml_tensor * conv_states = ggml_reshape_2d(ctx0, kv_self.k_l[il], hparams.n_embd_k_s(), kv_self.size);
  4855. struct ggml_tensor * ssm_states = ggml_reshape_2d(ctx0, kv_self.v_l[il], hparams.n_embd_v_s(), kv_self.size);
  4856. conv_states = ggml_get_rows(ctx0, conv_states, state_copy);
  4857. ssm_states = ggml_get_rows(ctx0, ssm_states, state_copy);
  4858. // TODO: name the intermediate tensors with cb()
  4859. ggml_build_forward_expand(gf, ggml_cpy(ctx0, conv_states, kv_self.k_l[il]));
  4860. ggml_build_forward_expand(gf, ggml_cpy(ctx0, ssm_states, kv_self.v_l[il]));
  4861. }
  4862. return gf;
  4863. }
  4864. struct ggml_cgraph * build_defrag(const std::vector<uint32_t> & ids) {
  4865. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4866. for (uint32_t i = 0; i < ids.size(); ++i) {
  4867. const uint32_t id = ids[i];
  4868. if (i == id || id == ids.size()) {
  4869. continue;
  4870. }
  4871. uint32_t nm = 1;
  4872. while (i + nm < ids.size() && ids[i + nm] == id + nm) {
  4873. nm++;
  4874. }
  4875. for (int il = 0; il < n_layer; ++il) {
  4876. ggml_tensor * view_k_src = ggml_view_2d(ctx0, kv_self.k_l[il],
  4877. n_embd_k_gqa, nm,
  4878. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  4879. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*i));
  4880. ggml_tensor * view_k_dst = ggml_view_2d(ctx0, kv_self.k_l[il],
  4881. n_embd_k_gqa, nm,
  4882. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  4883. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*id));
  4884. ggml_tensor * view_v_src = ggml_view_2d(ctx0, kv_self.v_l[il],
  4885. nm, n_embd_v_gqa,
  4886. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  4887. ggml_row_size(kv_self.v_l[il]->type, i));
  4888. ggml_tensor * view_v_dst = ggml_view_2d(ctx0, kv_self.v_l[il],
  4889. nm, n_embd_v_gqa,
  4890. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  4891. ggml_row_size(kv_self.v_l[il]->type, id));
  4892. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_k_src, view_k_dst));
  4893. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_v_src, view_v_dst));
  4894. }
  4895. i += nm - 1;
  4896. }
  4897. //LLAMA_LOG_INFO("gf->n_nodes = %d\n", gf->n_nodes);
  4898. return gf;
  4899. }
  4900. struct ggml_tensor * build_inp_pos() {
  4901. lctx.inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  4902. cb(lctx.inp_pos, "inp_pos", -1);
  4903. ggml_set_input(lctx.inp_pos);
  4904. return lctx.inp_pos;
  4905. }
  4906. struct ggml_tensor * build_inp_KQ_mask(bool causal = true) {
  4907. if (causal) {
  4908. lctx.inp_KQ_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_kv, n_tokens);
  4909. } else {
  4910. lctx.inp_KQ_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, n_tokens);
  4911. }
  4912. cb(lctx.inp_KQ_mask, "KQ_mask", -1);
  4913. ggml_set_input(lctx.inp_KQ_mask);
  4914. return lctx.inp_KQ_mask;
  4915. }
  4916. struct ggml_tensor * build_inp_KQ_pos() {
  4917. lctx.inp_KQ_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, n_kv);
  4918. cb(lctx.inp_KQ_pos, "KQ_pos", -1);
  4919. ggml_set_input(lctx.inp_KQ_pos);
  4920. return lctx.inp_KQ_pos;
  4921. }
  4922. struct ggml_tensor * build_inp_mean() {
  4923. lctx.inp_mean = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, n_tokens);
  4924. cb(lctx.inp_mean, "inp_mean", -1);
  4925. ggml_set_input(lctx.inp_mean);
  4926. return lctx.inp_mean;
  4927. }
  4928. struct ggml_tensor * build_inp_cls() {
  4929. lctx.inp_cls = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  4930. cb(lctx.inp_cls, "inp_cls", -1);
  4931. ggml_set_input(lctx.inp_cls);
  4932. return lctx.inp_cls;
  4933. }
  4934. struct ggml_tensor * build_inp_s_copy() {
  4935. lctx.inp_s_copy = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, kv_self.size);
  4936. cb(lctx.inp_s_copy, "inp_s_copy", -1);
  4937. ggml_set_input(lctx.inp_s_copy);
  4938. return lctx.inp_s_copy;
  4939. }
  4940. struct ggml_tensor * build_inp_s_mask() {
  4941. lctx.inp_s_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, 1, n_kv);
  4942. cb(lctx.inp_s_mask, "inp_s_mask", -1);
  4943. ggml_set_input(lctx.inp_s_mask);
  4944. return lctx.inp_s_mask;
  4945. }
  4946. struct ggml_tensor * build_inp_s_seq() {
  4947. lctx.inp_s_seq = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_kv, n_tokens);
  4948. cb(lctx.inp_s_seq, "inp_s_seq", -1);
  4949. ggml_set_input(lctx.inp_s_seq);
  4950. return lctx.inp_s_seq;
  4951. }
  4952. struct ggml_cgraph * build_llama() {
  4953. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4954. const int64_t n_embd_head = hparams.n_embd_head_v;
  4955. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4956. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4957. struct ggml_tensor * cur;
  4958. struct ggml_tensor * inpL;
  4959. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  4960. // inp_pos - contains the positions
  4961. struct ggml_tensor * inp_pos = build_inp_pos();
  4962. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4963. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  4964. for (int il = 0; il < n_layer; ++il) {
  4965. struct ggml_tensor * inpSA = inpL;
  4966. // norm
  4967. cur = llm_build_norm(ctx0, inpL, hparams,
  4968. model.layers[il].attn_norm, NULL,
  4969. LLM_NORM_RMS, cb, il);
  4970. cb(cur, "attn_norm", il);
  4971. // self-attention
  4972. {
  4973. // compute Q and K and RoPE them
  4974. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4975. cb(Qcur, "Qcur", il);
  4976. if (model.layers[il].bq) {
  4977. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  4978. cb(Qcur, "Qcur", il);
  4979. }
  4980. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4981. cb(Kcur, "Kcur", il);
  4982. if (model.layers[il].bk) {
  4983. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  4984. cb(Kcur, "Kcur", il);
  4985. }
  4986. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4987. cb(Vcur, "Vcur", il);
  4988. if (model.layers[il].bv) {
  4989. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  4990. cb(Vcur, "Vcur", il);
  4991. }
  4992. Qcur = ggml_rope_custom(
  4993. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  4994. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  4995. ext_factor, attn_factor, beta_fast, beta_slow
  4996. );
  4997. cb(Qcur, "Qcur", il);
  4998. Kcur = ggml_rope_custom(
  4999. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5000. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5001. ext_factor, attn_factor, beta_fast, beta_slow
  5002. );
  5003. cb(Kcur, "Kcur", il);
  5004. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5005. model.layers[il].wo, model.layers[il].bo,
  5006. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5007. }
  5008. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5009. cb(ffn_inp, "ffn_inp", il);
  5010. // feed-forward network
  5011. if (model.layers[il].ffn_gate_inp == nullptr) {
  5012. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5013. model.layers[il].ffn_norm, NULL,
  5014. LLM_NORM_RMS, cb, il);
  5015. cb(cur, "ffn_norm", il);
  5016. cur = llm_build_ffn(ctx0, cur,
  5017. model.layers[il].ffn_up, NULL,
  5018. model.layers[il].ffn_gate, NULL,
  5019. model.layers[il].ffn_down, NULL,
  5020. NULL,
  5021. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5022. cb(cur, "ffn_out", il);
  5023. } else {
  5024. // MoE branch
  5025. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5026. model.layers[il].ffn_norm, NULL,
  5027. LLM_NORM_RMS, cb, il);
  5028. cb(cur, "ffn_norm", il);
  5029. ggml_tensor * logits = ggml_mul_mat(ctx0, model.layers[il].ffn_gate_inp, cur); // [n_tokens, num_experts]
  5030. cb(logits, "ffn_moe_logits", il);
  5031. ggml_tensor * probs = ggml_soft_max(ctx0, logits); // [n_tokens, num_experts]
  5032. cb(probs, "ffn_moe_probs", il);
  5033. // select experts
  5034. ggml_tensor * selected_experts = ggml_top_k(ctx0, probs, n_expert_used); // [n_tokens, num_experts_per_tok]
  5035. cb(selected_experts->src[0], "ffn_moe_argsort", il);
  5036. ggml_tensor * weights = ggml_get_rows(ctx0,
  5037. ggml_reshape_3d(ctx0, probs, 1, n_expert, n_tokens), selected_experts);
  5038. cb(weights, "ffn_moe_weights", il);
  5039. weights = ggml_reshape_2d(ctx0, weights, n_expert_used, n_tokens); // [n_tokens, num_experts_per_tok]
  5040. ggml_tensor * weights_sum = ggml_sum_rows(ctx0, weights);
  5041. cb(weights_sum, "ffn_moe_weights_sum", il);
  5042. weights = ggml_div(ctx0, weights, weights_sum); // [n_tokens, num_experts_per_tok]
  5043. cb(weights, "ffn_moe_weights_norm", il);
  5044. // compute expert outputs
  5045. ggml_tensor * moe_out = nullptr;
  5046. for (int i = 0; i < n_expert_used; ++i) {
  5047. ggml_tensor * cur_expert;
  5048. ggml_tensor * cur_up = ggml_mul_mat_id(ctx0, model.layers[il].ffn_up_exp, n_expert, selected_experts, i, cur);
  5049. cb(cur_up, "ffn_moe_up", il);
  5050. ggml_tensor * cur_gate = ggml_mul_mat_id(ctx0, model.layers[il].ffn_gate_exp, n_expert, selected_experts, i, cur);
  5051. cb(cur_gate, "ffn_moe_gate", il);
  5052. cur_gate = ggml_silu(ctx0, cur_gate);
  5053. cb(cur_gate, "ffn_moe_silu", il);
  5054. cur_expert = ggml_mul(ctx0, cur_up, cur_gate); // [n_tokens, n_embd]
  5055. cb(cur_expert, "ffn_moe_gate_par", il);
  5056. cur_expert = ggml_mul_mat_id(ctx0, model.layers[il].ffn_down_exp, n_expert, selected_experts, i, cur_expert); // [n_tokens, n_embd]
  5057. cb(cur_expert, "ffn_moe_down", il);
  5058. cur_expert = ggml_mul(ctx0, cur_expert,
  5059. ggml_view_2d(ctx0, weights, 1, n_tokens, weights->nb[1], i*weights->nb[0]));
  5060. cb(cur_expert, "ffn_moe_weighted", il);
  5061. if (i == 0) {
  5062. moe_out = cur_expert;
  5063. } else {
  5064. moe_out = ggml_add(ctx0, moe_out, cur_expert);
  5065. cb(moe_out, "ffn_moe_out", il);
  5066. }
  5067. }
  5068. cur = moe_out;
  5069. }
  5070. cur = ggml_add(ctx0, cur, ffn_inp);
  5071. cb(cur, "ffn_out", il);
  5072. ggml_tensor * layer_dir = lctx.cvec.tensor_for(il);
  5073. if (layer_dir != nullptr) {
  5074. cur = ggml_add(ctx0, cur, layer_dir);
  5075. }
  5076. cb(cur, "l_out", il);
  5077. // input for next layer
  5078. inpL = cur;
  5079. }
  5080. cur = inpL;
  5081. cur = llm_build_norm(ctx0, cur, hparams,
  5082. model.output_norm, NULL,
  5083. LLM_NORM_RMS, cb, -1);
  5084. cb(cur, "result_norm", -1);
  5085. // lm_head
  5086. cur = ggml_mul_mat(ctx0, model.output, cur);
  5087. cb(cur, "result_output", -1);
  5088. ggml_build_forward_expand(gf, cur);
  5089. return gf;
  5090. }
  5091. struct ggml_cgraph * build_baichuan() {
  5092. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5093. const int64_t n_embd_head = hparams.n_embd_head_v;
  5094. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5095. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5096. struct ggml_tensor * cur;
  5097. struct ggml_tensor * inpL;
  5098. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5099. // inp_pos - contains the positions
  5100. struct ggml_tensor * inp_pos = model.type == MODEL_7B ? build_inp_pos() : nullptr;
  5101. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5102. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5103. // positions of the tokens in the KV cache
  5104. struct ggml_tensor * KQ_pos = build_inp_KQ_pos();
  5105. for (int il = 0; il < n_layer; ++il) {
  5106. struct ggml_tensor * inpSA = inpL;
  5107. cur = llm_build_norm(ctx0, inpL, hparams,
  5108. model.layers[il].attn_norm, NULL,
  5109. LLM_NORM_RMS, cb, il);
  5110. cb(cur, "attn_norm", il);
  5111. // self-attention
  5112. {
  5113. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5114. cb(Qcur, "Qcur", il);
  5115. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5116. cb(Kcur, "Kcur", il);
  5117. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5118. cb(Vcur, "Vcur", il);
  5119. switch (model.type) {
  5120. case MODEL_7B:
  5121. Qcur = ggml_rope_custom(
  5122. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5123. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5124. ext_factor, attn_factor, beta_fast, beta_slow
  5125. );
  5126. Kcur = ggml_rope_custom(
  5127. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5128. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5129. ext_factor, attn_factor, beta_fast, beta_slow
  5130. );
  5131. break;
  5132. case MODEL_13B:
  5133. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd/n_head, n_head, n_tokens);
  5134. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd/n_head, n_head, n_tokens);
  5135. break;
  5136. default:
  5137. GGML_ASSERT(false);
  5138. }
  5139. cb(Qcur, "Qcur", il);
  5140. cb(Kcur, "Kcur", il);
  5141. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5142. model.layers[il].wo, NULL,
  5143. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5144. }
  5145. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5146. cb(ffn_inp, "ffn_inp", il);
  5147. // feed-forward network
  5148. {
  5149. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5150. model.layers[il].ffn_norm, NULL,
  5151. LLM_NORM_RMS, cb, il);
  5152. cb(cur, "ffn_norm", il);
  5153. cur = llm_build_ffn(ctx0, cur,
  5154. model.layers[il].ffn_up, NULL,
  5155. model.layers[il].ffn_gate, NULL,
  5156. model.layers[il].ffn_down, NULL,
  5157. NULL,
  5158. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5159. cb(cur, "ffn_out", il);
  5160. }
  5161. cur = ggml_add(ctx0, cur, ffn_inp);
  5162. cb(cur, "l_out", il);
  5163. // input for next layer
  5164. inpL = cur;
  5165. }
  5166. cur = inpL;
  5167. cur = llm_build_norm(ctx0, cur, hparams,
  5168. model.output_norm, NULL,
  5169. LLM_NORM_RMS, cb, -1);
  5170. cb(cur, "result_norm", -1);
  5171. // lm_head
  5172. cur = ggml_mul_mat(ctx0, model.output, cur);
  5173. cb(cur, "result_output", -1);
  5174. ggml_build_forward_expand(gf, cur);
  5175. return gf;
  5176. }
  5177. struct ggml_cgraph * build_falcon() {
  5178. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5179. const int64_t n_embd_head = hparams.n_embd_head_v;
  5180. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5181. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5182. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5183. struct ggml_tensor * cur;
  5184. struct ggml_tensor * inpL;
  5185. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5186. // inp_pos - contains the positions
  5187. struct ggml_tensor * inp_pos = build_inp_pos();
  5188. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5189. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5190. for (int il = 0; il < n_layer; ++il) {
  5191. struct ggml_tensor * attn_norm;
  5192. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  5193. model.layers[il].attn_norm,
  5194. model.layers[il].attn_norm_b,
  5195. LLM_NORM, cb, il);
  5196. cb(attn_norm, "attn_norm", il);
  5197. // self-attention
  5198. {
  5199. if (model.layers[il].attn_norm_2) {
  5200. // Falcon-40B
  5201. cur = llm_build_norm(ctx0, inpL, hparams,
  5202. model.layers[il].attn_norm_2,
  5203. model.layers[il].attn_norm_2_b,
  5204. LLM_NORM, cb, il);
  5205. cb(cur, "attn_norm_2", il);
  5206. } else {
  5207. cur = attn_norm;
  5208. }
  5209. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5210. cb(cur, "wqkv", il);
  5211. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5212. 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)));
  5213. 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)));
  5214. cb(Qcur, "Qcur", il);
  5215. cb(Kcur, "Kcur", il);
  5216. cb(Vcur, "Vcur", il);
  5217. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5218. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  5219. // using mode = 2 for neox mode
  5220. Qcur = ggml_rope_custom(
  5221. ctx0, Qcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5222. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5223. );
  5224. cb(Qcur, "Qcur", il);
  5225. Kcur = ggml_rope_custom(
  5226. ctx0, Kcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5227. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5228. );
  5229. cb(Kcur, "Kcur", il);
  5230. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5231. model.layers[il].wo, NULL,
  5232. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5233. }
  5234. struct ggml_tensor * ffn_inp = cur;
  5235. // feed forward
  5236. {
  5237. cur = llm_build_ffn(ctx0, attn_norm, // !! use the attn norm, not the result
  5238. model.layers[il].ffn_up, NULL,
  5239. NULL, NULL,
  5240. model.layers[il].ffn_down, NULL,
  5241. NULL,
  5242. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5243. cb(cur, "ffn_out", il);
  5244. }
  5245. cur = ggml_add(ctx0, cur, ffn_inp);
  5246. cb(cur, "l_out", il);
  5247. cur = ggml_add(ctx0, cur, inpL);
  5248. cb(cur, "l_out", il);
  5249. // input for next layer
  5250. inpL = cur;
  5251. }
  5252. cur = inpL;
  5253. // norm
  5254. cur = llm_build_norm(ctx0, cur, hparams,
  5255. model.output_norm,
  5256. model.output_norm_b,
  5257. LLM_NORM, cb, -1);
  5258. cb(cur, "result_norm", -1);
  5259. cur = ggml_mul_mat(ctx0, model.output, cur);
  5260. cb(cur, "result_output", -1);
  5261. ggml_build_forward_expand(gf, cur);
  5262. return gf;
  5263. }
  5264. struct ggml_cgraph * build_starcoder() {
  5265. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5266. const int64_t n_embd_head = hparams.n_embd_head_v;
  5267. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5268. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5269. struct ggml_tensor * cur;
  5270. struct ggml_tensor * inpL;
  5271. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5272. // inp_pos - contains the positions
  5273. struct ggml_tensor * inp_pos = build_inp_pos();
  5274. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5275. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5276. struct ggml_tensor * pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  5277. cb(pos, "pos_embd", -1);
  5278. inpL = ggml_add(ctx0, inpL, pos);
  5279. cb(inpL, "inpL", -1);
  5280. for (int il = 0; il < n_layer; ++il) {
  5281. cur = llm_build_norm(ctx0, inpL, hparams,
  5282. model.layers[il].attn_norm,
  5283. model.layers[il].attn_norm_b,
  5284. LLM_NORM, cb, il);
  5285. cb(cur, "attn_norm", il);
  5286. // self-attention
  5287. {
  5288. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5289. cb(cur, "wqkv", il);
  5290. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5291. cb(cur, "bqkv", il);
  5292. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5293. 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)));
  5294. 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)));
  5295. cb(Qcur, "Qcur", il);
  5296. cb(Kcur, "Kcur", il);
  5297. cb(Vcur, "Vcur", il);
  5298. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5299. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5300. model.layers[il].wo, model.layers[il].bo,
  5301. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5302. }
  5303. // add the input
  5304. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5305. cb(ffn_inp, "ffn_inp", il);
  5306. // FF
  5307. {
  5308. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5309. model.layers[il].ffn_norm,
  5310. model.layers[il].ffn_norm_b,
  5311. LLM_NORM, cb, il);
  5312. cb(cur, "ffn_norm", il);
  5313. cur = llm_build_ffn(ctx0, cur,
  5314. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5315. NULL, NULL,
  5316. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5317. NULL,
  5318. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5319. cb(cur, "ffn_out", il);
  5320. }
  5321. inpL = ggml_add(ctx0, cur, ffn_inp);
  5322. cb(inpL, "l_out", il);
  5323. }
  5324. cur = llm_build_norm(ctx0, inpL, hparams,
  5325. model.output_norm,
  5326. model.output_norm_b,
  5327. LLM_NORM, cb, -1);
  5328. cb(cur, "result_norm", -1);
  5329. cur = ggml_mul_mat(ctx0, model.output, cur);
  5330. cb(cur, "result_output", -1);
  5331. ggml_build_forward_expand(gf, cur);
  5332. return gf;
  5333. }
  5334. struct ggml_cgraph * build_persimmon() {
  5335. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5336. const int64_t n_embd_head = hparams.n_embd_head_v;
  5337. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5338. GGML_ASSERT(n_embd_head/2 == hparams.n_rot);
  5339. struct ggml_tensor * cur;
  5340. struct ggml_tensor * inpL;
  5341. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5342. // inp_pos - contains the positions
  5343. struct ggml_tensor * inp_pos = build_inp_pos();
  5344. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5345. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5346. for (int il = 0; il < n_layer; ++il) {
  5347. struct ggml_tensor * residual = inpL;
  5348. cur = llm_build_norm(ctx0, inpL, hparams,
  5349. model.layers[il].attn_norm,
  5350. model.layers[il].attn_norm_b,
  5351. LLM_NORM, cb, il);
  5352. cb(cur, "attn_norm", il);
  5353. // self attention
  5354. {
  5355. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5356. cb(cur, "wqkv", il);
  5357. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5358. cb(cur, "bqkv", il);
  5359. // split qkv
  5360. GGML_ASSERT(n_head_kv == n_head);
  5361. struct ggml_tensor * tmpqkv = ggml_reshape_4d(ctx0, cur, n_embd_head, 3, n_head, n_tokens);
  5362. cb(tmpqkv, "tmpqkv", il);
  5363. struct ggml_tensor * tmpqkv_perm = ggml_cont(ctx0, ggml_permute(ctx0, tmpqkv, 0, 3, 1, 2));
  5364. cb(tmpqkv_perm, "tmpqkv", il);
  5365. struct ggml_tensor * tmpq = ggml_view_3d(
  5366. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  5367. ggml_element_size(tmpqkv_perm) * n_embd_head,
  5368. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  5369. 0
  5370. );
  5371. cb(tmpq, "tmpq", il);
  5372. struct ggml_tensor * tmpk = ggml_view_3d(
  5373. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  5374. ggml_element_size(tmpqkv_perm) * n_embd_head,
  5375. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  5376. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens
  5377. );
  5378. cb(tmpk, "tmpk", il);
  5379. // Q/K Layernorm
  5380. tmpq = llm_build_norm(ctx0, tmpq, hparams,
  5381. model.layers[il].attn_q_norm,
  5382. model.layers[il].attn_q_norm_b,
  5383. LLM_NORM, cb, il);
  5384. cb(tmpq, "tmpq", il);
  5385. tmpk = llm_build_norm(ctx0, tmpk, hparams,
  5386. model.layers[il].attn_k_norm,
  5387. model.layers[il].attn_k_norm_b,
  5388. LLM_NORM, cb, il);
  5389. cb(tmpk, "tmpk", il);
  5390. // RoPE the first n_rot of q/k, pass the other half, and concat.
  5391. struct ggml_tensor * qrot = ggml_view_3d(
  5392. ctx0, tmpq, n_rot, n_head, n_tokens,
  5393. ggml_element_size(tmpq) * n_embd_head,
  5394. ggml_element_size(tmpq) * n_embd_head * n_head,
  5395. 0
  5396. );
  5397. cb(qrot, "qrot", il);
  5398. struct ggml_tensor * krot = ggml_view_3d(
  5399. ctx0, tmpk, n_rot, n_head, n_tokens,
  5400. ggml_element_size(tmpk) * n_embd_head,
  5401. ggml_element_size(tmpk) * n_embd_head * n_head,
  5402. 0
  5403. );
  5404. cb(krot, "krot", il);
  5405. // get the second half of tmpq, e.g tmpq[n_rot:, :, :]
  5406. struct ggml_tensor * qpass = ggml_view_3d(
  5407. ctx0, tmpq, n_rot, n_head, n_tokens,
  5408. ggml_element_size(tmpq) * n_embd_head,
  5409. ggml_element_size(tmpq) * n_embd_head * n_head,
  5410. ggml_element_size(tmpq) * n_rot
  5411. );
  5412. cb(qpass, "qpass", il);
  5413. struct ggml_tensor * kpass = ggml_view_3d(
  5414. ctx0, tmpk, n_rot, n_head, n_tokens,
  5415. ggml_element_size(tmpk) * n_embd_head,
  5416. ggml_element_size(tmpk) * n_embd_head * n_head,
  5417. ggml_element_size(tmpk) * n_rot
  5418. );
  5419. cb(kpass, "kpass", il);
  5420. struct ggml_tensor * qrotated = ggml_rope_custom(
  5421. ctx0, qrot, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5422. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5423. );
  5424. cb(qrotated, "qrotated", il);
  5425. struct ggml_tensor * krotated = ggml_rope_custom(
  5426. ctx0, krot, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5427. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5428. );
  5429. cb(krotated, "krotated", il);
  5430. // ggml currently only supports concatenation on dim=2
  5431. // so we need to permute qrot, qpass, concat, then permute back.
  5432. qrotated = ggml_cont(ctx0, ggml_permute(ctx0, qrotated, 2, 1, 0, 3));
  5433. cb(qrotated, "qrotated", il);
  5434. krotated = ggml_cont(ctx0, ggml_permute(ctx0, krotated, 2, 1, 0, 3));
  5435. cb(krotated, "krotated", il);
  5436. qpass = ggml_cont(ctx0, ggml_permute(ctx0, qpass, 2, 1, 0, 3));
  5437. cb(qpass, "qpass", il);
  5438. kpass = ggml_cont(ctx0, ggml_permute(ctx0, kpass, 2, 1, 0, 3));
  5439. cb(kpass, "kpass", il);
  5440. struct ggml_tensor * Qcur = ggml_concat(ctx0, qrotated, qpass);
  5441. cb(Qcur, "Qcur", il);
  5442. struct ggml_tensor * Kcur = ggml_concat(ctx0, krotated, kpass);
  5443. cb(Kcur, "Kcur", il);
  5444. struct ggml_tensor * Q = ggml_cont(ctx0, ggml_permute(ctx0, Qcur, 2, 1, 0, 3));
  5445. cb(Q, "Q", il);
  5446. Kcur = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 2, 1, 0, 3));
  5447. cb(Kcur, "Kcur", il);
  5448. struct ggml_tensor * Vcur = ggml_view_3d(
  5449. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  5450. ggml_element_size(tmpqkv_perm) * n_embd_head,
  5451. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  5452. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens * 2
  5453. );
  5454. cb(Vcur, "Vcur", il);
  5455. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5456. model.layers[il].wo, model.layers[il].bo,
  5457. Kcur, Vcur, Q, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5458. }
  5459. struct ggml_tensor * ffn_inp = ggml_add(ctx0, residual, cur);
  5460. cb(ffn_inp, "ffn_inp", il);
  5461. // feed-forward network
  5462. {
  5463. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5464. model.layers[il].ffn_norm,
  5465. model.layers[il].ffn_norm_b,
  5466. LLM_NORM, cb, il);
  5467. cb(cur, "ffn_norm", il);
  5468. cur = llm_build_ffn(ctx0, cur,
  5469. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5470. NULL, NULL,
  5471. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5472. NULL,
  5473. LLM_FFN_RELU_SQR, LLM_FFN_SEQ, cb, il);
  5474. cb(cur, "ffn_out", il);
  5475. }
  5476. cur = ggml_add(ctx0, cur, ffn_inp);
  5477. cb(cur, "l_out", il);
  5478. inpL = cur;
  5479. }
  5480. cur = inpL;
  5481. cur = llm_build_norm(ctx0, cur, hparams,
  5482. model.output_norm,
  5483. model.output_norm_b,
  5484. LLM_NORM, cb, -1);
  5485. cb(cur, "result_norm", -1);
  5486. cur = ggml_mul_mat(ctx0, model.output, cur);
  5487. cb(cur, "result_output", -1);
  5488. ggml_build_forward_expand(gf, cur);
  5489. return gf;
  5490. }
  5491. struct ggml_cgraph * build_refact() {
  5492. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5493. const int64_t n_embd_head = hparams.n_embd_head_v;
  5494. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5495. struct ggml_tensor * cur;
  5496. struct ggml_tensor * inpL;
  5497. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5498. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5499. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5500. // positions of the tokens in the KV cache
  5501. struct ggml_tensor * KQ_pos = build_inp_KQ_pos();
  5502. for (int il = 0; il < n_layer; ++il) {
  5503. struct ggml_tensor * inpSA = inpL;
  5504. cur = llm_build_norm(ctx0, inpL, hparams,
  5505. model.layers[il].attn_norm, NULL,
  5506. LLM_NORM_RMS, cb, il);
  5507. cb(cur, "attn_norm", il);
  5508. // self-attention
  5509. {
  5510. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5511. cb(Qcur, "Qcur", il);
  5512. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5513. cb(Kcur, "Kcur", il);
  5514. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5515. cb(Vcur, "Vcur", il);
  5516. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  5517. cb(Kcur, "Kcur", il);
  5518. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5519. cb(Qcur, "Qcur", il);
  5520. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5521. model.layers[il].wo, NULL,
  5522. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5523. }
  5524. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5525. cb(ffn_inp, "ffn_inp", il);
  5526. // feed-forward network
  5527. {
  5528. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5529. model.layers[il].ffn_norm, NULL,
  5530. LLM_NORM_RMS, cb, il);
  5531. cb(cur, "ffn_norm", il);
  5532. cur = llm_build_ffn(ctx0, cur,
  5533. model.layers[il].ffn_up, NULL,
  5534. model.layers[il].ffn_gate, NULL,
  5535. model.layers[il].ffn_down, NULL,
  5536. NULL,
  5537. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5538. cb(cur, "ffn_out", il);
  5539. }
  5540. cur = ggml_add(ctx0, cur, ffn_inp);
  5541. cb(cur, "l_out", il);
  5542. // input for next layer
  5543. inpL = cur;
  5544. }
  5545. cur = inpL;
  5546. cur = llm_build_norm(ctx0, cur, hparams,
  5547. model.output_norm, NULL,
  5548. LLM_NORM_RMS, cb, -1);
  5549. cb(cur, "result_norm", -1);
  5550. // lm_head
  5551. cur = ggml_mul_mat(ctx0, model.output, cur);
  5552. cb(cur, "result_output", -1);
  5553. ggml_build_forward_expand(gf, cur);
  5554. return gf;
  5555. }
  5556. struct ggml_cgraph * build_bert() {
  5557. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5558. const int64_t n_embd_head = hparams.n_embd_head_v;
  5559. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5560. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5561. struct ggml_tensor * cur;
  5562. struct ggml_tensor * inpL;
  5563. struct ggml_tensor * inp_pos = build_inp_pos();
  5564. struct ggml_tensor * inp_mean = build_inp_mean();
  5565. struct ggml_tensor * inp_cls = build_inp_cls();
  5566. // construct input embeddings (token, type, position)
  5567. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5568. // token types are hardcoded to zero ("Sentence A")
  5569. struct ggml_tensor * type_row0 = ggml_view_1d(ctx0, model.type_embd, n_embd, 0);
  5570. inpL = ggml_add(ctx0, inpL, type_row0);
  5571. if (model.arch == LLM_ARCH_BERT) {
  5572. inpL = ggml_add(ctx0, ggml_get_rows(ctx0, model.pos_embd, inp_pos), inpL);
  5573. }
  5574. cb(inpL, "inp_embd", -1);
  5575. // embed layer norm
  5576. inpL = llm_build_norm(ctx0, inpL, hparams, model.tok_norm, model.tok_norm_b, LLM_NORM, cb, -1);
  5577. cb(inpL, "inp_norm", -1);
  5578. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5579. struct ggml_tensor * KQ_mask = build_inp_KQ_mask(false);
  5580. // iterate layers
  5581. for (int il = 0; il < n_layer; ++il) {
  5582. struct ggml_tensor * cur = inpL;
  5583. struct ggml_tensor * Qcur;
  5584. struct ggml_tensor * Kcur;
  5585. struct ggml_tensor * Vcur;
  5586. // self-attention
  5587. if (model.arch == LLM_ARCH_BERT) {
  5588. Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, cur), model.layers[il].bq);
  5589. cb(Qcur, "Qcur", il);
  5590. Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, cur), model.layers[il].bk);
  5591. cb(Kcur, "Kcur", il);
  5592. Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, cur), model.layers[il].bv);
  5593. cb(Vcur, "Vcur", il);
  5594. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5595. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  5596. } else {
  5597. // compute Q and K and RoPE them
  5598. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5599. cb(cur, "wqkv", il);
  5600. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5601. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  5602. 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)));
  5603. cb(Qcur, "Qcur", il);
  5604. cb(Kcur, "Kcur", il);
  5605. cb(Vcur, "Vcur", il);
  5606. Qcur = ggml_rope_custom(
  5607. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5608. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5609. ext_factor, attn_factor, beta_fast, beta_slow
  5610. );
  5611. cb(Qcur, "Qcur", il);
  5612. Kcur = ggml_rope_custom(
  5613. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5614. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5615. ext_factor, attn_factor, beta_fast, beta_slow
  5616. );
  5617. cb(Kcur, "Kcur", il);
  5618. }
  5619. struct ggml_tensor * q = ggml_permute(ctx0, Qcur, 0, 2, 1, 3);
  5620. struct ggml_tensor * k = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 0, 2, 1, 3));
  5621. struct ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
  5622. cb(kq, "kq", il);
  5623. kq = ggml_soft_max_ext(ctx0, kq, KQ_mask, nullptr, 1.0f/sqrtf(float(n_embd_head)), hparams.f_max_alibi_bias);
  5624. cb(kq, "kq_soft_max_ext", il);
  5625. struct ggml_tensor * v = ggml_cont(ctx0, ggml_transpose(ctx0, ggml_reshape_2d(ctx0, Vcur, n_embd_gqa, n_tokens)));
  5626. cb(v, "v", il);
  5627. struct ggml_tensor * kqv = ggml_mul_mat(ctx0, ggml_reshape_3d(ctx0, v, n_tokens, n_embd_head, n_head_kv), kq);
  5628. cb(kqv, "kqv", il);
  5629. struct ggml_tensor * kqv_merged = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
  5630. cb(kqv_merged, "kqv_merged", il);
  5631. cur = ggml_cont_2d(ctx0, kqv_merged, n_embd_gqa, n_tokens);
  5632. cb(cur, "kqv_merged_cont", il);
  5633. ggml_build_forward_expand(gf, cur);
  5634. cur = ggml_mul_mat(ctx0, model.layers[il].wo, cur);
  5635. if (model.layers[il].bo) {
  5636. cb(cur, "kqv_wo", il);
  5637. }
  5638. if (model.layers[il].bo) {
  5639. cur = ggml_add(ctx0, cur, model.layers[il].bo);
  5640. }
  5641. cb(cur, "kqv_out", il);
  5642. // re-add the layer input
  5643. cur = ggml_add(ctx0, cur, inpL);
  5644. // attention layer norm
  5645. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].attn_out_norm, model.layers[il].attn_out_norm_b, LLM_NORM, cb, il);
  5646. struct ggml_tensor * ffn_inp = cur;
  5647. cb(ffn_inp, "ffn_inp", il);
  5648. // feed-forward network
  5649. if (model.arch == LLM_ARCH_BERT) {
  5650. cur = llm_build_ffn(ctx0, cur,
  5651. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5652. NULL, NULL,
  5653. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5654. NULL,
  5655. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5656. } else {
  5657. cur = llm_build_ffn(ctx0, cur,
  5658. model.layers[il].ffn_up, NULL,
  5659. model.layers[il].ffn_gate, NULL,
  5660. model.layers[il].ffn_down, NULL,
  5661. NULL,
  5662. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5663. }
  5664. cb(cur, "ffn_out", il);
  5665. // attentions bypass the intermediate layer
  5666. cur = ggml_add(ctx0, cur, ffn_inp);
  5667. // output layer norm
  5668. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].layer_out_norm, model.layers[il].layer_out_norm_b, LLM_NORM, cb, il);
  5669. // input for next layer
  5670. inpL = cur;
  5671. }
  5672. // final output
  5673. cur = inpL;
  5674. cb(cur, "result_embd", -1);
  5675. // pooling layer
  5676. switch (pooling_type) {
  5677. case LLAMA_POOLING_TYPE_NONE:
  5678. {
  5679. // nop
  5680. } break;
  5681. case LLAMA_POOLING_TYPE_MEAN:
  5682. {
  5683. cur = ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, cur)), inp_mean);
  5684. cb(cur, "result_embd_pooled", -1);
  5685. } break;
  5686. case LLAMA_POOLING_TYPE_CLS:
  5687. {
  5688. cur = ggml_get_rows(ctx0, cur, inp_cls);
  5689. cb(cur, "result_embd_pooled", -1);
  5690. } break;
  5691. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  5692. {
  5693. GGML_ASSERT(false && "Invalid pooling type");
  5694. } break;
  5695. }
  5696. ggml_build_forward_expand(gf, cur);
  5697. return gf;
  5698. }
  5699. struct ggml_cgraph * build_bloom() {
  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. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5708. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5709. // positions of the tokens in the KV cache
  5710. struct ggml_tensor * KQ_pos = build_inp_KQ_pos();
  5711. inpL = llm_build_norm(ctx0, inpL, hparams,
  5712. model.tok_norm,
  5713. model.tok_norm_b,
  5714. LLM_NORM, cb, -1);
  5715. cb(inpL, "inp_norm", -1);
  5716. for (int il = 0; il < n_layer; ++il) {
  5717. cur = llm_build_norm(ctx0, inpL, hparams,
  5718. model.layers[il].attn_norm,
  5719. model.layers[il].attn_norm_b,
  5720. LLM_NORM, cb, il);
  5721. cb(cur, "attn_norm", il);
  5722. // self-attention
  5723. {
  5724. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5725. cb(cur, "wqkv", il);
  5726. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5727. cb(cur, "bqkv", il);
  5728. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5729. 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)));
  5730. 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)));
  5731. cb(Qcur, "Qcur", il);
  5732. cb(Kcur, "Kcur", il);
  5733. cb(Vcur, "Vcur", il);
  5734. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5735. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5736. model.layers[il].wo, model.layers[il].bo,
  5737. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5738. }
  5739. // Add the input
  5740. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5741. cb(ffn_inp, "ffn_inp", il);
  5742. // FF
  5743. {
  5744. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5745. model.layers[il].ffn_norm,
  5746. model.layers[il].ffn_norm_b,
  5747. LLM_NORM, cb, il);
  5748. cb(cur, "ffn_norm", il);
  5749. cur = llm_build_ffn(ctx0, cur,
  5750. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5751. NULL, NULL,
  5752. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5753. NULL,
  5754. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5755. cb(cur, "ffn_out", il);
  5756. }
  5757. inpL = ggml_add(ctx0, cur, ffn_inp);
  5758. cb(inpL, "l_out", il);
  5759. }
  5760. cur = llm_build_norm(ctx0, inpL, hparams,
  5761. model.output_norm,
  5762. model.output_norm_b,
  5763. LLM_NORM, cb, -1);
  5764. cb(cur, "result_norm", -1);
  5765. cur = ggml_mul_mat(ctx0, model.output, cur);
  5766. cb(cur, "result_output", -1);
  5767. ggml_build_forward_expand(gf, cur);
  5768. return gf;
  5769. }
  5770. struct ggml_cgraph * build_mpt() {
  5771. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5772. const int64_t n_embd_head = hparams.n_embd_head_v;
  5773. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5774. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5775. struct ggml_tensor * cur;
  5776. struct ggml_tensor * inpL;
  5777. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5778. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5779. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5780. // positions of the tokens in the KV cache
  5781. struct ggml_tensor * KQ_pos = build_inp_KQ_pos();
  5782. for (int il = 0; il < n_layer; ++il) {
  5783. struct ggml_tensor * attn_norm;
  5784. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  5785. model.layers[il].attn_norm,
  5786. model.layers[il].attn_norm_b,
  5787. LLM_NORM, cb, il);
  5788. cb(attn_norm, "attn_norm", il);
  5789. // self-attention
  5790. {
  5791. cur = attn_norm;
  5792. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5793. cb(cur, "wqkv", il);
  5794. if (model.layers[il].bqkv){
  5795. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5796. cb(cur, "bqkv", il);
  5797. }
  5798. if (hparams.f_clamp_kqv > 0.0f) {
  5799. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  5800. cb(cur, "wqkv_clamped", il);
  5801. }
  5802. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5803. 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)));
  5804. 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)));
  5805. cb(Qcur, "Qcur", il);
  5806. cb(Kcur, "Kcur", il);
  5807. cb(Vcur, "Vcur", il);
  5808. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5809. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5810. model.layers[il].wo, model.layers[il].bo,
  5811. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5812. }
  5813. // Add the input
  5814. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5815. cb(ffn_inp, "ffn_inp", il);
  5816. // feed forward
  5817. {
  5818. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5819. model.layers[il].ffn_norm,
  5820. model.layers[il].ffn_norm_b,
  5821. LLM_NORM, cb, il);
  5822. cb(cur, "ffn_norm", il);
  5823. cur = llm_build_ffn(ctx0, cur,
  5824. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5825. NULL, NULL,
  5826. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5827. model.layers[il].ffn_act,
  5828. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5829. cb(cur, "ffn_out", il);
  5830. }
  5831. cur = ggml_add(ctx0, cur, ffn_inp);
  5832. cb(cur, "l_out", il);
  5833. // input for next layer
  5834. inpL = cur;
  5835. }
  5836. cur = inpL;
  5837. cur = llm_build_norm(ctx0, cur, hparams,
  5838. model.output_norm,
  5839. model.output_norm_b,
  5840. LLM_NORM, cb, -1);
  5841. cb(cur, "result_norm", -1);
  5842. cur = ggml_mul_mat(ctx0, model.output, cur);
  5843. cb(cur, "result_output", -1);
  5844. ggml_build_forward_expand(gf, cur);
  5845. return gf;
  5846. }
  5847. struct ggml_cgraph * build_stablelm() {
  5848. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  5849. const int64_t n_embd_head = hparams.n_embd_head_v;
  5850. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5851. struct ggml_tensor * cur;
  5852. struct ggml_tensor * inpL;
  5853. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5854. // inp_pos - contains the positions
  5855. struct ggml_tensor * inp_pos = build_inp_pos();
  5856. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5857. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5858. for (int il = 0; il < n_layer; ++il) {
  5859. struct ggml_tensor * inpSA = inpL;
  5860. // norm
  5861. cur = llm_build_norm(ctx0, inpL, hparams,
  5862. model.layers[il].attn_norm,
  5863. model.layers[il].attn_norm_b,
  5864. LLM_NORM, cb, il);
  5865. cb(cur, "attn_norm", il);
  5866. // self-attention
  5867. {
  5868. // compute Q and K and RoPE them
  5869. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5870. cb(Qcur, "Qcur", il);
  5871. if (model.layers[il].bq) {
  5872. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5873. cb(Qcur, "Qcur", il);
  5874. }
  5875. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5876. cb(Kcur, "Kcur", il);
  5877. if (model.layers[il].bk) {
  5878. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5879. cb(Kcur, "Kcur", il);
  5880. }
  5881. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5882. cb(Vcur, "Vcur", il);
  5883. if (model.layers[il].bv) {
  5884. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  5885. cb(Vcur, "Vcur", il);
  5886. }
  5887. Qcur = ggml_rope_custom(
  5888. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5889. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5890. ext_factor, attn_factor, beta_fast, beta_slow
  5891. );
  5892. cb(Qcur, "Qcur", il);
  5893. Kcur = ggml_rope_custom(
  5894. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5895. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5896. ext_factor, attn_factor, beta_fast, beta_slow
  5897. );
  5898. cb(Kcur, "Kcur", il);
  5899. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5900. model.layers[il].wo, NULL,
  5901. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5902. }
  5903. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5904. cb(ffn_inp, "ffn_inp", il);
  5905. // feed-forward network
  5906. {
  5907. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5908. model.layers[il].ffn_norm,
  5909. model.layers[il].ffn_norm_b,
  5910. LLM_NORM, cb, il);
  5911. cb(cur, "ffn_norm", il);
  5912. cur = llm_build_ffn(ctx0, cur,
  5913. model.layers[il].ffn_up, NULL,
  5914. model.layers[il].ffn_gate, NULL,
  5915. model.layers[il].ffn_down, NULL,
  5916. NULL,
  5917. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5918. cb(cur, "ffn_out", il);
  5919. }
  5920. cur = ggml_add(ctx0, cur, ffn_inp);
  5921. cb(cur, "l_out", il);
  5922. // input for next layer
  5923. inpL = cur;
  5924. }
  5925. cur = inpL;
  5926. cur = llm_build_norm(ctx0, cur, hparams,
  5927. model.output_norm,
  5928. model.output_norm_b,
  5929. LLM_NORM, cb, -1);
  5930. cb(cur, "result_norm", -1);
  5931. // lm_head
  5932. cur = ggml_mul_mat(ctx0, model.output, cur);
  5933. cb(cur, "result_output", -1);
  5934. ggml_build_forward_expand(gf, cur);
  5935. return gf;
  5936. }
  5937. struct ggml_cgraph * build_qwen() {
  5938. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5939. const int64_t n_embd_head = hparams.n_embd_head_v;
  5940. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5941. struct ggml_tensor * cur;
  5942. struct ggml_tensor * inpL;
  5943. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  5944. // inp_pos - contains the positions
  5945. struct ggml_tensor * inp_pos = build_inp_pos();
  5946. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5947. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  5948. for (int il = 0; il < n_layer; ++il) {
  5949. struct ggml_tensor * inpSA = inpL;
  5950. cur = llm_build_norm(ctx0, inpL, hparams,
  5951. model.layers[il].attn_norm, NULL,
  5952. LLM_NORM_RMS, cb, il);
  5953. cb(cur, "attn_norm", il);
  5954. // self-attention
  5955. {
  5956. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5957. cb(cur, "wqkv", il);
  5958. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5959. cb(cur, "bqkv", il);
  5960. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5961. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  5962. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 2*sizeof(float)*(n_embd)));
  5963. cb(Qcur, "Qcur", il);
  5964. cb(Kcur, "Kcur", il);
  5965. cb(Vcur, "Vcur", il);
  5966. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5967. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  5968. // using mode = 2 for neox mode
  5969. Qcur = ggml_rope_custom(
  5970. ctx0, Qcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5971. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5972. );
  5973. cb(Qcur, "Qcur", il);
  5974. Kcur = ggml_rope_custom(
  5975. ctx0, Kcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5976. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5977. );
  5978. cb(Kcur, "Kcur", il);
  5979. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5980. model.layers[il].wo, NULL,
  5981. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5982. }
  5983. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5984. cb(ffn_inp, "ffn_inp", il);
  5985. // feed-forward forward
  5986. {
  5987. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5988. model.layers[il].ffn_norm, NULL,
  5989. LLM_NORM_RMS, cb, il);
  5990. cb(cur, "ffn_norm", il);
  5991. cur = llm_build_ffn(ctx0, cur,
  5992. model.layers[il].ffn_up, NULL,
  5993. model.layers[il].ffn_gate, NULL,
  5994. model.layers[il].ffn_down, NULL,
  5995. NULL,
  5996. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5997. cb(cur, "ffn_out", il);
  5998. }
  5999. cur = ggml_add(ctx0, cur, ffn_inp);
  6000. cb(cur, "l_out", il);
  6001. // input for next layer
  6002. inpL = cur;
  6003. }
  6004. cur = inpL;
  6005. cur = llm_build_norm(ctx0, cur, hparams,
  6006. model.output_norm, NULL,
  6007. LLM_NORM_RMS, cb, -1);
  6008. cb(cur, "result_norm", -1);
  6009. // lm_head
  6010. cur = ggml_mul_mat(ctx0, model.output, cur);
  6011. cb(cur, "result_output", -1);
  6012. ggml_build_forward_expand(gf, cur);
  6013. return gf;
  6014. }
  6015. struct ggml_cgraph * build_qwen2() {
  6016. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6017. const int64_t n_embd_head = hparams.n_embd_head_v;
  6018. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6019. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6020. struct ggml_tensor * cur;
  6021. struct ggml_tensor * inpL;
  6022. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6023. // inp_pos - contains the positions
  6024. struct ggml_tensor * inp_pos = build_inp_pos();
  6025. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6026. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6027. for (int il = 0; il < n_layer; ++il) {
  6028. struct ggml_tensor * inpSA = inpL;
  6029. // norm
  6030. cur = llm_build_norm(ctx0, inpL, hparams,
  6031. model.layers[il].attn_norm, NULL,
  6032. LLM_NORM_RMS, cb, il);
  6033. cb(cur, "attn_norm", il);
  6034. // self-attention
  6035. {
  6036. // compute Q and K and RoPE them
  6037. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6038. cb(Qcur, "Qcur", il);
  6039. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6040. cb(Qcur, "Qcur", il);
  6041. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6042. cb(Kcur, "Kcur", il);
  6043. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6044. cb(Kcur, "Kcur", il);
  6045. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6046. cb(Vcur, "Vcur", il);
  6047. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6048. cb(Vcur, "Vcur", il);
  6049. // these nodes are added to the graph together so that they are not reordered
  6050. // by doing so, the number of splits in the graph is reduced
  6051. ggml_build_forward_expand(gf, Qcur);
  6052. ggml_build_forward_expand(gf, Kcur);
  6053. ggml_build_forward_expand(gf, Vcur);
  6054. Qcur = ggml_rope_custom(
  6055. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6056. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6057. ext_factor, attn_factor, beta_fast, beta_slow
  6058. );
  6059. cb(Qcur, "Qcur", il);
  6060. Kcur = ggml_rope_custom(
  6061. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6062. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6063. ext_factor, attn_factor, beta_fast, beta_slow
  6064. );
  6065. cb(Kcur, "Kcur", il);
  6066. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6067. model.layers[il].wo, model.layers[il].bo,
  6068. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6069. }
  6070. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6071. cb(ffn_inp, "ffn_inp", il);
  6072. // feed-forward network
  6073. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6074. model.layers[il].ffn_norm, NULL,
  6075. LLM_NORM_RMS, cb, il);
  6076. cb(cur, "ffn_norm", il);
  6077. cur = llm_build_ffn(ctx0, cur,
  6078. model.layers[il].ffn_up, NULL,
  6079. model.layers[il].ffn_gate, NULL,
  6080. model.layers[il].ffn_down, NULL,
  6081. NULL,
  6082. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6083. cb(cur, "ffn_out", il);
  6084. cur = ggml_add(ctx0, cur, ffn_inp);
  6085. cb(cur, "l_out", il);
  6086. // input for next layer
  6087. inpL = cur;
  6088. }
  6089. cur = inpL;
  6090. cur = llm_build_norm(ctx0, cur, hparams,
  6091. model.output_norm, NULL,
  6092. LLM_NORM_RMS, cb, -1);
  6093. cb(cur, "result_norm", -1);
  6094. // lm_head
  6095. cur = ggml_mul_mat(ctx0, model.output, cur);
  6096. cb(cur, "result_output", -1);
  6097. ggml_build_forward_expand(gf, cur);
  6098. return gf;
  6099. }
  6100. struct ggml_cgraph * build_phi2() {
  6101. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6102. const int64_t n_embd_head = hparams.n_embd_head_v;
  6103. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  6104. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6105. struct ggml_tensor * cur;
  6106. struct ggml_tensor * attn_norm_output;
  6107. struct ggml_tensor * ffn_output;
  6108. struct ggml_tensor * inpL;
  6109. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6110. // inp_pos - contains the positions
  6111. struct ggml_tensor * inp_pos = build_inp_pos();
  6112. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6113. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6114. for (int il = 0; il < n_layer; ++il) {
  6115. attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  6116. model.layers[il].attn_norm,
  6117. model.layers[il].attn_norm_b,
  6118. LLM_NORM, cb, il);
  6119. cb(attn_norm_output, "attn_norm", il);
  6120. // self-attention
  6121. {
  6122. struct ggml_tensor * Qcur = nullptr;
  6123. struct ggml_tensor * Kcur = nullptr;
  6124. struct ggml_tensor * Vcur = nullptr;
  6125. if (model.layers[il].wqkv) {
  6126. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, attn_norm_output);
  6127. cb(cur, "wqkv", il);
  6128. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6129. cb(cur, "bqkv", il);
  6130. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6131. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  6132. 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)));
  6133. } else {
  6134. Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  6135. Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  6136. Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  6137. }
  6138. cb(Qcur, "Qcur", il);
  6139. cb(Kcur, "Kcur", il);
  6140. cb(Vcur, "Vcur", il);
  6141. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6142. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  6143. Qcur = ggml_rope_custom(
  6144. ctx0, Qcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  6145. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  6146. );
  6147. cb(Qcur, "Qcur", il);
  6148. // with phi2, we scale the Q to avoid precision issues
  6149. // ref: https://github.com/ml-explore/mlx-examples/blob/08e862336ade809bc37d1035f94b359e7d1a5152/phi2/phi2.py#L64-L66
  6150. Qcur = ggml_scale(ctx0, Qcur, 1.0f/sqrtf(float(n_embd_head)));
  6151. cb(Qcur, "Qcur", il);
  6152. Kcur = ggml_rope_custom(
  6153. ctx0, Kcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  6154. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  6155. );
  6156. cb(Kcur, "Kcur", il);
  6157. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6158. model.layers[il].wo, model.layers[il].bo,
  6159. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  6160. }
  6161. // FF
  6162. {
  6163. ffn_output = llm_build_ffn(ctx0, attn_norm_output,
  6164. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6165. NULL, NULL,
  6166. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6167. NULL,
  6168. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6169. cb(ffn_output, "ffn_out", il);
  6170. }
  6171. cur = ggml_add(ctx0, cur, ffn_output);
  6172. cb(cur, "l_out", il);
  6173. cur = ggml_add(ctx0, cur, inpL);
  6174. cb(cur, "l_out", il);
  6175. inpL = cur;
  6176. }
  6177. cur = llm_build_norm(ctx0, inpL, hparams,
  6178. model.output_norm,
  6179. model.output_norm_b,
  6180. LLM_NORM, cb, -1);
  6181. cb(cur, "result_norm", -1);
  6182. cur = ggml_mul_mat(ctx0, model.output, cur);
  6183. cb(cur, "result_output_no_bias", -1);
  6184. cur = ggml_add(ctx0, cur, model.output_b);
  6185. cb(cur, "result_output", -1);
  6186. ggml_build_forward_expand(gf, cur);
  6187. return gf;
  6188. }
  6189. struct ggml_cgraph * build_plamo() {
  6190. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  6191. const int64_t n_embd_head = hparams.n_embd_head_v;
  6192. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6193. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6194. struct ggml_tensor * cur;
  6195. struct ggml_tensor * inpL;
  6196. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6197. // inp_pos - contains the positions
  6198. struct ggml_tensor * inp_pos = build_inp_pos();
  6199. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6200. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6201. for (int il = 0; il < n_layer; ++il) {
  6202. // norm
  6203. cur = llm_build_norm(ctx0, inpL, hparams,
  6204. model.layers[il].attn_norm, NULL,
  6205. LLM_NORM_RMS, cb, il);
  6206. cb(cur, "attn_norm", il);
  6207. struct ggml_tensor * attention_norm = cur;
  6208. // self-attention
  6209. {
  6210. // compute Q and K and RoPE them
  6211. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6212. cb(Qcur, "Qcur", il);
  6213. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6214. cb(Kcur, "Kcur", il);
  6215. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6216. cb(Vcur, "Vcur", il);
  6217. Qcur = ggml_rope_custom(
  6218. ctx0, ggml_reshape_3d(ctx0, Qcur, n_rot, n_head, n_tokens), inp_pos,
  6219. n_embd_head, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6220. ext_factor, attn_factor, beta_fast, beta_slow);
  6221. cb(Qcur, "Qcur", il);
  6222. Kcur = ggml_rope_custom(
  6223. ctx0, ggml_reshape_3d(ctx0, Kcur, n_rot, n_head_kv, n_tokens), inp_pos,
  6224. n_embd_head, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6225. ext_factor, attn_factor, beta_fast, beta_slow);
  6226. cb(Kcur, "Kcur", il);
  6227. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6228. model.layers[il].wo, NULL,
  6229. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6230. }
  6231. struct ggml_tensor * sa_out = cur;
  6232. cur = attention_norm;
  6233. // feed-forward network
  6234. {
  6235. cur = llm_build_ffn(ctx0, cur,
  6236. model.layers[il].ffn_up, NULL,
  6237. model.layers[il].ffn_gate, NULL,
  6238. model.layers[il].ffn_down, NULL,
  6239. NULL,
  6240. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6241. cb(cur, "ffn_out", il);
  6242. }
  6243. cur = ggml_add(ctx0, cur, sa_out);
  6244. cb(cur, "l_out", il);
  6245. cur = ggml_add(ctx0, cur, inpL);
  6246. cb(cur, "l_out", il);
  6247. // input for next layer
  6248. inpL = cur;
  6249. }
  6250. cur = inpL;
  6251. cur = llm_build_norm(ctx0, cur, hparams,
  6252. model.output_norm, NULL,
  6253. LLM_NORM_RMS, cb, -1);
  6254. cb(cur, "result_norm", -1);
  6255. // lm_head
  6256. cur = ggml_mul_mat(ctx0, model.output, cur);
  6257. cb(cur, "result_output", -1);
  6258. ggml_build_forward_expand(gf, cur);
  6259. return gf;
  6260. }
  6261. struct ggml_cgraph * build_gpt2() {
  6262. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6263. const int64_t n_embd_head = hparams.n_embd_head_v;
  6264. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  6265. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6266. struct ggml_tensor * cur;
  6267. struct ggml_tensor * pos;
  6268. struct ggml_tensor * inpL;
  6269. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6270. // inp_pos - contains the positions
  6271. struct ggml_tensor * inp_pos = build_inp_pos();
  6272. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6273. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6274. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  6275. cb(pos, "pos_embd", -1);
  6276. inpL = ggml_add(ctx0, inpL, pos);
  6277. cb(inpL, "inpL", -1);
  6278. for (int il = 0; il < n_layer; ++il) {
  6279. cur = llm_build_norm(ctx0, inpL, hparams,
  6280. model.layers[il].attn_norm,
  6281. model.layers[il].attn_norm_b,
  6282. LLM_NORM, cb, il);
  6283. cb(cur, "attn_norm", il);
  6284. // self-attention
  6285. {
  6286. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6287. cb(cur, "wqkv", il);
  6288. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6289. cb(cur, "bqkv", il);
  6290. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6291. 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)));
  6292. 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)));
  6293. cb(Qcur, "Qcur", il);
  6294. cb(Kcur, "Kcur", il);
  6295. cb(Vcur, "Vcur", il);
  6296. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  6297. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6298. model.layers[il].wo, model.layers[il].bo,
  6299. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6300. }
  6301. // add the input
  6302. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  6303. cb(ffn_inp, "ffn_inp", il);
  6304. // FF
  6305. {
  6306. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6307. model.layers[il].ffn_norm,
  6308. model.layers[il].ffn_norm_b,
  6309. LLM_NORM, cb, il);
  6310. cb(cur, "ffn_norm", il);
  6311. cur = llm_build_ffn(ctx0, cur,
  6312. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6313. NULL, NULL,
  6314. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6315. NULL,
  6316. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6317. cb(cur, "ffn_out", il);
  6318. }
  6319. inpL = ggml_add(ctx0, cur, ffn_inp);
  6320. cb(inpL, "l_out", il);
  6321. }
  6322. cur = llm_build_norm(ctx0, inpL, hparams,
  6323. model.output_norm,
  6324. model.output_norm_b,
  6325. LLM_NORM, cb, -1);
  6326. cb(cur, "result_norm", -1);
  6327. cur = ggml_mul_mat(ctx0, model.output, cur);
  6328. cb(cur, "result_output", -1);
  6329. ggml_build_forward_expand(gf, cur);
  6330. return gf;
  6331. }
  6332. struct ggml_cgraph * build_codeshell() {
  6333. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6334. const int64_t n_embd_head = hparams.n_embd_head_v;
  6335. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  6336. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6337. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6338. struct ggml_tensor * cur;
  6339. struct ggml_tensor * inpL;
  6340. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6341. // inp_pos - contains the positions
  6342. struct ggml_tensor * inp_pos = build_inp_pos();
  6343. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6344. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6345. for (int il = 0; il < n_layer; ++il) {
  6346. cur = llm_build_norm(ctx0, inpL, hparams,
  6347. model.layers[il].attn_norm,
  6348. model.layers[il].attn_norm_b,
  6349. LLM_NORM, cb, il);
  6350. cb(cur, "attn_norm", il);
  6351. // self-attention
  6352. {
  6353. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  6354. cb(cur, "wqkv", il);
  6355. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  6356. cb(cur, "bqkv", il);
  6357. struct ggml_tensor * tmpq = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  6358. 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)));
  6359. 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)));
  6360. cb(tmpq, "tmpq", il);
  6361. cb(tmpk, "tmpk", il);
  6362. cb(Vcur, "Vcur", il);
  6363. struct ggml_tensor * Qcur = ggml_rope_custom(
  6364. ctx0, ggml_reshape_3d(ctx0, tmpq, n_embd_head, n_head, n_tokens), inp_pos,
  6365. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6366. ext_factor, attn_factor, beta_fast, beta_slow
  6367. );
  6368. cb(Qcur, "Qcur", il);
  6369. struct ggml_tensor * Kcur = ggml_rope_custom(
  6370. ctx0, ggml_reshape_3d(ctx0, tmpk, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6371. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6372. ext_factor, attn_factor, beta_fast, beta_slow
  6373. );
  6374. cb(Kcur, "Kcur", il);
  6375. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6376. model.layers[il].wo, model.layers[il].bo,
  6377. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6378. }
  6379. // add the input
  6380. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  6381. cb(ffn_inp, "ffn_inp", il);
  6382. // FF
  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, model.layers[il].ffn_up_b,
  6391. NULL, NULL,
  6392. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6393. NULL,
  6394. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6395. cb(cur, "ffn_out", il);
  6396. }
  6397. inpL = ggml_add(ctx0, cur, ffn_inp);
  6398. cb(inpL, "l_out", il);
  6399. }
  6400. cur = llm_build_norm(ctx0, inpL, hparams,
  6401. model.output_norm,
  6402. model.output_norm_b,
  6403. LLM_NORM, cb, -1);
  6404. cb(cur, "result_norm", -1);
  6405. cur = ggml_mul_mat(ctx0, model.output, cur);
  6406. cb(cur, "result_output", -1);
  6407. ggml_build_forward_expand(gf, cur);
  6408. return gf;
  6409. }
  6410. struct ggml_cgraph * build_orion() {
  6411. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6412. const int64_t n_embd_head = hparams.n_embd_head_v;
  6413. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6414. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6415. struct ggml_tensor * cur;
  6416. struct ggml_tensor * inpL;
  6417. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6418. // inp_pos - contains the positions
  6419. struct ggml_tensor * inp_pos = build_inp_pos();
  6420. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6421. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6422. for (int il = 0; il < n_layer; ++il) {
  6423. struct ggml_tensor * inpSA = inpL;
  6424. // norm
  6425. cur = llm_build_norm(ctx0, inpL, hparams,
  6426. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  6427. LLM_NORM, cb, il);
  6428. cb(cur, "attn_norm", il);
  6429. // self-attention
  6430. {
  6431. // compute Q and K and RoPE them
  6432. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6433. cb(Qcur, "Qcur", il);
  6434. // if (model.layers[il].bq) {
  6435. // Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6436. // cb(Qcur, "Qcur", il);
  6437. // }
  6438. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6439. cb(Kcur, "Kcur", il);
  6440. // if (model.layers[il].bk) {
  6441. // Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6442. // cb(Kcur, "Kcur", il);
  6443. // }
  6444. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6445. cb(Vcur, "Vcur", il);
  6446. // if (model.layers[il].bv) {
  6447. // Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6448. // cb(Vcur, "Vcur", il);
  6449. // }
  6450. Qcur = ggml_rope_custom(
  6451. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6452. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6453. ext_factor, attn_factor, beta_fast, beta_slow
  6454. );
  6455. cb(Qcur, "Qcur", il);
  6456. Kcur = ggml_rope_custom(
  6457. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6458. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6459. ext_factor, attn_factor, beta_fast, beta_slow
  6460. );
  6461. cb(Kcur, "Kcur", il);
  6462. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6463. model.layers[il].wo, NULL,
  6464. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6465. }
  6466. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6467. cb(ffn_inp, "ffn_inp", il);
  6468. // feed-forward network
  6469. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6470. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  6471. LLM_NORM, cb, il);
  6472. cb(cur, "ffn_norm", il);
  6473. cur = llm_build_ffn(ctx0, cur,
  6474. model.layers[il].ffn_up, NULL,
  6475. model.layers[il].ffn_gate, NULL,
  6476. model.layers[il].ffn_down, NULL,
  6477. NULL,
  6478. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6479. cb(cur, "ffn_out", il);
  6480. cur = ggml_add(ctx0, cur, ffn_inp);
  6481. cb(cur, "l_out", il);
  6482. // input for next layer
  6483. inpL = cur;
  6484. }
  6485. cur = inpL;
  6486. cur = llm_build_norm(ctx0, cur, hparams,
  6487. model.output_norm, model.output_norm_b,
  6488. LLM_NORM, cb, -1);
  6489. cb(cur, "result_norm", -1);
  6490. // lm_head
  6491. cur = ggml_mul_mat(ctx0, model.output, cur);
  6492. cb(cur, "result_output", -1);
  6493. ggml_build_forward_expand(gf, cur);
  6494. return gf;
  6495. }
  6496. struct ggml_cgraph * build_internlm2() {
  6497. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6498. const int64_t n_embd_head = hparams.n_embd_head_v;
  6499. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6500. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6501. struct ggml_tensor * cur;
  6502. struct ggml_tensor * inpL;
  6503. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6504. // inp_pos - contains the positions
  6505. struct ggml_tensor * inp_pos = build_inp_pos();
  6506. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6507. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6508. for (int il = 0; il < n_layer; ++il) {
  6509. struct ggml_tensor * inpSA = inpL;
  6510. // norm
  6511. cur = llm_build_norm(ctx0, inpL, hparams,
  6512. model.layers[il].attn_norm, NULL,
  6513. LLM_NORM_RMS, cb, il);
  6514. cb(cur, "attn_norm", il);
  6515. // self-attention
  6516. {
  6517. // compute Q and K and RoPE them
  6518. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6519. cb(Qcur, "Qcur", il);
  6520. if (model.layers[il].bq) {
  6521. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6522. cb(Qcur, "Qcur", il);
  6523. }
  6524. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6525. cb(Kcur, "Kcur", il);
  6526. if (model.layers[il].bk) {
  6527. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6528. cb(Kcur, "Kcur", il);
  6529. }
  6530. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6531. cb(Vcur, "Vcur", il);
  6532. if (model.layers[il].bv) {
  6533. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6534. cb(Vcur, "Vcur", il);
  6535. }
  6536. Qcur = ggml_rope_custom(
  6537. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6538. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6539. ext_factor, attn_factor, beta_fast, beta_slow
  6540. );
  6541. cb(Qcur, "Qcur", il);
  6542. Kcur = ggml_rope_custom(
  6543. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6544. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6545. ext_factor, attn_factor, beta_fast, beta_slow
  6546. );
  6547. cb(Kcur, "Kcur", il);
  6548. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6549. model.layers[il].wo, model.layers[il].bo,
  6550. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6551. }
  6552. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6553. cb(ffn_inp, "ffn_inp", il);
  6554. // feed-forward network
  6555. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6556. model.layers[il].ffn_norm, NULL,
  6557. LLM_NORM_RMS, cb, il);
  6558. cb(cur, "ffn_norm", il);
  6559. cur = llm_build_ffn(ctx0, cur,
  6560. model.layers[il].ffn_up, NULL,
  6561. model.layers[il].ffn_gate, NULL,
  6562. model.layers[il].ffn_down, NULL,
  6563. NULL,
  6564. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6565. cb(cur, "ffn_out", il);
  6566. cur = ggml_add(ctx0, cur, ffn_inp);
  6567. cb(cur, "l_out", il);
  6568. // input for next layer
  6569. inpL = cur;
  6570. }
  6571. cur = inpL;
  6572. cur = llm_build_norm(ctx0, cur, hparams,
  6573. model.output_norm, NULL,
  6574. LLM_NORM_RMS, cb, -1);
  6575. cb(cur, "result_norm", -1);
  6576. // lm_head
  6577. cur = ggml_mul_mat(ctx0, model.output, cur);
  6578. cb(cur, "result_output", -1);
  6579. ggml_build_forward_expand(gf, cur);
  6580. return gf;
  6581. }
  6582. // ref: https://arxiv.org/abs/2203.03466
  6583. // https://github.com/ggerganov/llama.cpp/issues/5276#issuecomment-1925774738
  6584. // based on the original build_llama() function
  6585. struct ggml_cgraph * build_minicpm() {
  6586. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6587. const int64_t n_embd_head = hparams.n_embd_head_v;
  6588. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6589. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6590. const int64_t n_embd = hparams.n_embd;
  6591. //TODO: if the model varies, these parameters need to be read from the model
  6592. const int64_t n_embd_base = 256;
  6593. const float scale_embd = 12.0f;
  6594. const float scale_depth = 1.4f;
  6595. struct ggml_tensor * cur;
  6596. struct ggml_tensor * inpL;
  6597. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6598. // scale the input embeddings
  6599. inpL = ggml_scale(ctx0, inpL, scale_embd);
  6600. cb(inpL, "inp_scaled", -1);
  6601. // inp_pos - contains the positions
  6602. struct ggml_tensor * inp_pos = build_inp_pos();
  6603. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6604. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6605. for (int il = 0; il < n_layer; ++il) {
  6606. struct ggml_tensor * inpSA = inpL;
  6607. // norm
  6608. cur = llm_build_norm(ctx0, inpL, hparams,
  6609. model.layers[il].attn_norm, NULL,
  6610. LLM_NORM_RMS, cb, il);
  6611. cb(cur, "attn_norm", il);
  6612. // self-attention
  6613. {
  6614. // compute Q and K and RoPE them
  6615. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6616. cb(Qcur, "Qcur", il);
  6617. if (model.layers[il].bq) {
  6618. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6619. cb(Qcur, "Qcur", il);
  6620. }
  6621. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6622. cb(Kcur, "Kcur", il);
  6623. if (model.layers[il].bk) {
  6624. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6625. cb(Kcur, "Kcur", il);
  6626. }
  6627. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6628. cb(Vcur, "Vcur", il);
  6629. if (model.layers[il].bv) {
  6630. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6631. cb(Vcur, "Vcur", il);
  6632. }
  6633. Qcur = ggml_rope_custom(
  6634. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6635. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6636. ext_factor, attn_factor, beta_fast, beta_slow
  6637. );
  6638. cb(Qcur, "Qcur", il);
  6639. Kcur = ggml_rope_custom(
  6640. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6641. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6642. ext_factor, attn_factor, beta_fast, beta_slow
  6643. );
  6644. cb(Kcur, "Kcur", il);
  6645. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6646. model.layers[il].wo, model.layers[il].bo,
  6647. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6648. }
  6649. // scale_res - scale the hidden states for residual connection
  6650. const float scale_res = scale_depth/sqrtf(float(n_layer));
  6651. cur = ggml_scale(ctx0, cur, scale_res);
  6652. cb(cur, "hidden_scaled", -1);
  6653. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6654. cb(ffn_inp, "ffn_inp", il);
  6655. // feed-forward network
  6656. {
  6657. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6658. model.layers[il].ffn_norm, NULL,
  6659. LLM_NORM_RMS, cb, il);
  6660. cb(cur, "ffn_norm", il);
  6661. cur = llm_build_ffn(ctx0, cur,
  6662. model.layers[il].ffn_up, NULL,
  6663. model.layers[il].ffn_gate, NULL,
  6664. model.layers[il].ffn_down, NULL,
  6665. NULL,
  6666. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6667. cb(cur, "ffn_out", il);
  6668. }
  6669. // scale the hidden states for residual connection
  6670. cur = ggml_scale(ctx0, cur, scale_res);
  6671. cb(cur, "hidden_scaled_ffn", -1);
  6672. cur = ggml_add(ctx0, cur, ffn_inp);
  6673. cb(cur, "l_out", il);
  6674. // input for next layer
  6675. inpL = cur;
  6676. }
  6677. cur = inpL;
  6678. cur = llm_build_norm(ctx0, cur, hparams,
  6679. model.output_norm, NULL,
  6680. LLM_NORM_RMS, cb, -1);
  6681. cb(cur, "result_norm", -1);
  6682. // lm_head scaling
  6683. const float scale_lmhead = float(n_embd_base)/float(n_embd);
  6684. cur = ggml_scale(ctx0, cur, scale_lmhead);
  6685. cb(cur, "lmhead_scaling", -1);
  6686. // lm_head
  6687. cur = ggml_mul_mat(ctx0, model.tok_embd, cur);
  6688. cb(cur, "result_output", -1);
  6689. ggml_build_forward_expand(gf, cur);
  6690. return gf;
  6691. }
  6692. struct ggml_cgraph * build_gemma() {
  6693. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6694. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  6695. struct ggml_tensor * cur;
  6696. struct ggml_tensor * inpL;
  6697. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6698. inpL = ggml_scale(ctx0, inpL, sqrtf(n_embd));
  6699. cb(inpL, "inp_scaled", -1);
  6700. // inp_pos - contains the positions
  6701. struct ggml_tensor * inp_pos = build_inp_pos();
  6702. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6703. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6704. for (int il = 0; il < n_layer; ++il) {
  6705. // norm
  6706. cur = llm_build_norm(ctx0, inpL, hparams,
  6707. model.layers[il].attn_norm, NULL,
  6708. LLM_NORM_RMS, cb, il);
  6709. cb(cur, "attn_norm", il);
  6710. // self-attention
  6711. {
  6712. // compute Q and K and RoPE them
  6713. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6714. cb(Qcur, "Qcur", il);
  6715. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6716. cb(Kcur, "Kcur", il);
  6717. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6718. cb(Vcur, "Vcur", il);
  6719. Qcur = ggml_rope_custom(
  6720. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head_k, n_head, n_tokens), inp_pos,
  6721. n_embd_head_k, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6722. ext_factor, attn_factor, beta_fast, beta_slow);
  6723. cb(Qcur, "Qcur", il);
  6724. Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head_k)));
  6725. cb(Qcur, "Qcur_scaled", il);
  6726. Kcur = ggml_rope_custom(
  6727. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head_k, n_head_kv, n_tokens), inp_pos,
  6728. n_embd_head_k, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6729. ext_factor, attn_factor, beta_fast, beta_slow);
  6730. cb(Kcur, "Kcur", il);
  6731. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6732. model.layers[il].wo, NULL,
  6733. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  6734. }
  6735. struct ggml_tensor * sa_out = ggml_add(ctx0, cur, inpL);
  6736. cb(sa_out, "sa_out", il);
  6737. cur = llm_build_norm(ctx0, sa_out, hparams,
  6738. model.layers[il].ffn_norm, NULL,
  6739. LLM_NORM_RMS, cb, il);
  6740. cb(cur, "ffn_norm", il);
  6741. // feed-forward network
  6742. {
  6743. cur = llm_build_ffn(ctx0, cur,
  6744. model.layers[il].ffn_up, NULL,
  6745. model.layers[il].ffn_gate, NULL,
  6746. model.layers[il].ffn_down, NULL,
  6747. NULL,
  6748. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  6749. cb(cur, "ffn_out", il);
  6750. }
  6751. cur = ggml_add(ctx0, cur, sa_out);
  6752. cb(cur, "l_out", il);
  6753. // input for next layer
  6754. inpL = cur;
  6755. }
  6756. cur = inpL;
  6757. cur = llm_build_norm(ctx0, cur, hparams,
  6758. model.output_norm, NULL,
  6759. LLM_NORM_RMS, cb, -1);
  6760. cb(cur, "result_norm", -1);
  6761. // lm_head
  6762. cur = ggml_mul_mat(ctx0, model.output, cur);
  6763. cb(cur, "result_output", -1);
  6764. ggml_build_forward_expand(gf, cur);
  6765. return gf;
  6766. }
  6767. struct ggml_cgraph * build_starcoder2() {
  6768. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6769. const int64_t n_embd_head = hparams.n_embd_head_v;
  6770. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6771. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6772. struct ggml_tensor * cur;
  6773. struct ggml_tensor * inpL;
  6774. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6775. // inp_pos - contains the positions
  6776. struct ggml_tensor * inp_pos = build_inp_pos();
  6777. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6778. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6779. for (int il = 0; il < n_layer; ++il) {
  6780. struct ggml_tensor * inpSA = inpL;
  6781. // norm
  6782. cur = llm_build_norm(ctx0, inpL, hparams,
  6783. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  6784. LLM_NORM, cb, il);
  6785. cb(cur, "attn_norm", il);
  6786. // self-attention
  6787. {
  6788. // compute Q and K and RoPE them
  6789. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6790. cb(Qcur, "Qcur", il);
  6791. if (model.layers[il].bq) {
  6792. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6793. cb(Qcur, "Qcur", il);
  6794. }
  6795. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6796. cb(Kcur, "Kcur", il);
  6797. if (model.layers[il].bk) {
  6798. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6799. cb(Kcur, "Kcur", il);
  6800. }
  6801. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6802. cb(Vcur, "Vcur", il);
  6803. if (model.layers[il].bv) {
  6804. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6805. cb(Vcur, "Vcur", il);
  6806. }
  6807. Qcur = ggml_rope_custom(
  6808. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6809. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6810. ext_factor, attn_factor, beta_fast, beta_slow
  6811. );
  6812. cb(Qcur, "Qcur", il);
  6813. Kcur = ggml_rope_custom(
  6814. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6815. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6816. ext_factor, attn_factor, beta_fast, beta_slow
  6817. );
  6818. cb(Kcur, "Kcur", il);
  6819. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6820. model.layers[il].wo, model.layers[il].bo,
  6821. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6822. cb(cur, "kqv_out", il);
  6823. }
  6824. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6825. cb(ffn_inp, "ffn_inp", il);
  6826. // feed-forward network
  6827. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6828. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  6829. LLM_NORM, cb, il);
  6830. cb(cur, "ffn_norm", il);
  6831. cur = llm_build_ffn(ctx0, cur,
  6832. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  6833. NULL, NULL,
  6834. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  6835. NULL,
  6836. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  6837. cb(cur, "ffn_out", il);
  6838. cur = ggml_add(ctx0, cur, ffn_inp);
  6839. cb(cur, "l_out", il);
  6840. // input for next layer
  6841. inpL = cur;
  6842. }
  6843. cur = inpL;
  6844. cur = llm_build_norm(ctx0, cur, hparams,
  6845. model.output_norm, model.output_norm_b,
  6846. LLM_NORM, cb, -1);
  6847. cb(cur, "result_norm", -1);
  6848. // lm_head
  6849. cur = ggml_mul_mat(ctx0, model.output, cur);
  6850. cb(cur, "result_output", -1);
  6851. ggml_build_forward_expand(gf, cur);
  6852. return gf;
  6853. }
  6854. struct ggml_cgraph * build_mamba() {
  6855. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6856. const int64_t d_model = n_embd;
  6857. const int64_t d_conv = hparams.ssm_d_conv;
  6858. const int64_t d_inner = hparams.ssm_d_inner;
  6859. GGML_ASSERT(2 * d_model == d_inner);
  6860. const int64_t d_state = hparams.ssm_d_state;
  6861. const int64_t dt_rank = hparams.ssm_dt_rank;
  6862. struct ggml_tensor * cur;
  6863. struct ggml_tensor * inpL;
  6864. // {n_embd, n_tokens}
  6865. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6866. struct ggml_tensor * state_mask = build_inp_s_mask();
  6867. struct ggml_tensor * state_seq = build_inp_s_seq();
  6868. for (int il = 0; il < n_layer; ++il) {
  6869. // (ab)using the KV cache to store the states
  6870. struct ggml_tensor * conv_states = ggml_reshape_2d(ctx0, kv_self.k_l[il], hparams.n_embd_k_s(), kv_self.size);
  6871. struct ggml_tensor * ssm_states = ggml_reshape_2d(ctx0, kv_self.v_l[il], hparams.n_embd_v_s(), kv_self.size);
  6872. // clear states of sequences which are starting at the beginning of this batch
  6873. {
  6874. conv_states = ggml_mul(ctx0,
  6875. ggml_view_2d(ctx0, conv_states, conv_states->ne[0], n_kv, conv_states->nb[1], kv_head*conv_states->nb[1]),
  6876. state_mask);
  6877. ssm_states = ggml_mul(ctx0,
  6878. ggml_view_2d(ctx0, ssm_states, ssm_states->ne[0], n_kv, ssm_states->nb[1], kv_head*ssm_states->nb[1]),
  6879. state_mask);
  6880. }
  6881. conv_states = ggml_reshape_3d(ctx0, conv_states, d_conv - 1, d_inner, n_kv);
  6882. ssm_states = ggml_reshape_3d(ctx0, ssm_states, d_state, d_inner, n_kv);
  6883. // norm
  6884. cur = llm_build_norm(ctx0, inpL, hparams,
  6885. model.layers[il].attn_norm, NULL,
  6886. LLM_NORM_RMS, cb, il);
  6887. cb(cur, "attn_norm", il);
  6888. // {n_embd, 2*d_inner} * {n_embd, n_tokens} => {2*d_inner, n_tokens}
  6889. struct ggml_tensor * xz = ggml_mul_mat(ctx0, model.layers[il].ssm_in, cur);
  6890. // split the above in two
  6891. // => {d_inner, n_tokens}
  6892. struct ggml_tensor * x = ggml_view_2d(ctx0, xz, d_inner, xz->ne[1], xz->nb[1], 0);
  6893. struct ggml_tensor * z = ggml_view_2d(ctx0, xz, d_inner, xz->ne[1], xz->nb[1], ggml_element_size(xz)*d_inner);
  6894. // conv
  6895. {
  6896. // Custom operator which is needed only to ease simultaneous sequence processing.
  6897. // For a single sequence, the equivalent is to concatenate the columns of conv_states and x,
  6898. // then make a self-overlapping view of that over d_conv columns at each stride in the 3rd dimension,
  6899. // then element-wise multiply that with the conv1d weigth,
  6900. // then sum the elements of each row,
  6901. // (the last two steps are a dot product over rows (also doable with mul_mat))
  6902. // then permute away the ne[0] dimension,
  6903. // and then you're left with the resulting x tensor.
  6904. // The new conv_states is the last (d_conv - 1) columns
  6905. // of the last 3rd dimensional "layer" of the self-overlapping view.
  6906. // For simultaneous sequences, it's more complicated.
  6907. struct ggml_tensor * x_conv = ggml_ssm_conv(ctx0, conv_states, x, model.layers[il].ssm_conv1d, state_seq);
  6908. // store last (d_conv - 1) columns of the conv_state part of x_conv back into the KV cache
  6909. ggml_build_forward_expand(gf,
  6910. ggml_cpy(ctx0,
  6911. 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)),
  6912. 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))));
  6913. // extract x from x_conv
  6914. x = ggml_view_2d(ctx0, x_conv, d_inner, n_tokens, d_inner*ggml_element_size(x_conv), 0);
  6915. // bias
  6916. x = ggml_add(ctx0, x, model.layers[il].ssm_conv1d_b);
  6917. x = ggml_silu(ctx0, x);
  6918. }
  6919. // ssm
  6920. {
  6921. // {d_inner, dt_rank + 2*d_state} * {d_inner, n_tokens} => {dt_rank + 2*d_state, n_tokens}
  6922. struct ggml_tensor * x_db = ggml_mul_mat(ctx0, model.layers[il].ssm_x, x);
  6923. // split
  6924. struct ggml_tensor * dt = ggml_view_2d(ctx0, x_db, dt_rank, n_tokens, x_db->nb[1], 0);
  6925. 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);
  6926. 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));
  6927. // {dt_rank, d_inner} * {dt_rank, n_tokens} => {d_inner, n_tokens}
  6928. dt = ggml_mul_mat(ctx0, model.layers[il].ssm_dt, dt);
  6929. dt = ggml_add(ctx0, dt, model.layers[il].ssm_dt_b);
  6930. // Custom operator to optimize the parallel associative scan
  6931. // as described in the Annex D of the Mamba paper.
  6932. // => {d_inner, n_tokens} and {d_state, d_inner, n_kv} combined,
  6933. // because only a single tensor can be returned.
  6934. struct ggml_tensor * y_ssm_states = ggml_ssm_scan(ctx0, ssm_states, x, dt, model.layers[il].ssm_a, B, C, state_seq);
  6935. // store last states (the second part of y_ssm_states)
  6936. ggml_build_forward_expand(gf,
  6937. ggml_cpy(ctx0,
  6938. ggml_view_1d(ctx0, y_ssm_states, d_state*d_inner*n_kv, d_inner*n_tokens*ggml_element_size(y_ssm_states)),
  6939. 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))));
  6940. struct ggml_tensor * y = ggml_view_2d(ctx0, y_ssm_states, d_inner, n_tokens, d_inner*ggml_element_size(y_ssm_states), 0);
  6941. // {d_inner, n_tokens} * {d_inner} => {d_inner, n_tokens}
  6942. y = ggml_add(ctx0, y, ggml_mul(ctx0, x, model.layers[il].ssm_d));
  6943. y = ggml_mul(ctx0, y, ggml_silu(ctx0, z));
  6944. // {d_inner, n_embd} * {d_inner, n_tokens} => {n_embd, n_tokens}
  6945. cur = ggml_mul_mat(ctx0, model.layers[il].ssm_out, y);
  6946. }
  6947. // residual
  6948. cur = ggml_add(ctx0, cur, inpL);
  6949. cb(cur, "l_out", il);
  6950. // input for next layer
  6951. inpL = cur;
  6952. }
  6953. // final rmsnorm
  6954. cur = llm_build_norm(ctx0, inpL, hparams,
  6955. model.output_norm, NULL,
  6956. LLM_NORM_RMS, cb, -1);
  6957. cb(cur, "result_norm", -1);
  6958. // lm_head
  6959. cur = ggml_mul_mat(ctx0, model.output, cur);
  6960. cb(cur, "result_output", -1);
  6961. ggml_build_forward_expand(gf, cur);
  6962. return gf;
  6963. }
  6964. struct ggml_cgraph * build_command_r() {
  6965. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6966. const int64_t n_embd_head = hparams.n_embd_head_v;
  6967. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6968. const float f_logit_scale = hparams.f_logit_scale;
  6969. struct ggml_tensor * cur;
  6970. struct ggml_tensor * inpL;
  6971. inpL = llm_build_inp_embd(ctx0, lctx, hparams, batch, model.tok_embd, cb);
  6972. // inp_pos - contains the positions
  6973. struct ggml_tensor * inp_pos = build_inp_pos();
  6974. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6975. struct ggml_tensor * KQ_mask = build_inp_KQ_mask();
  6976. for (int il = 0; il < n_layer; ++il) {
  6977. // norm
  6978. cur = llm_build_norm(ctx0, inpL, hparams,
  6979. model.layers[il].attn_norm, NULL,
  6980. LLM_NORM, cb, il);
  6981. cb(cur, "attn_norm", il);
  6982. struct ggml_tensor * ffn_inp = cur;
  6983. // self-attention
  6984. {
  6985. // compute Q and K and RoPE them
  6986. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6987. cb(Qcur, "Qcur", il);
  6988. if (model.layers[il].bq) {
  6989. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6990. cb(Qcur, "Qcur", il);
  6991. }
  6992. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6993. cb(Kcur, "Kcur", il);
  6994. if (model.layers[il].bk) {
  6995. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6996. cb(Kcur, "Kcur", il);
  6997. }
  6998. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6999. cb(Vcur, "Vcur", il);
  7000. if (model.layers[il].bv) {
  7001. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  7002. cb(Vcur, "Vcur", il);
  7003. }
  7004. Qcur = ggml_rope_custom(
  7005. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  7006. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7007. ext_factor, attn_factor, beta_fast, beta_slow
  7008. );
  7009. cb(Qcur, "Qcur", il);
  7010. Kcur = ggml_rope_custom(
  7011. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  7012. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  7013. ext_factor, attn_factor, beta_fast, beta_slow
  7014. );
  7015. cb(Kcur, "Kcur", il);
  7016. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  7017. model.layers[il].wo, model.layers[il].bo,
  7018. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  7019. }
  7020. struct ggml_tensor * attn_out = cur;
  7021. // feed-forward network
  7022. {
  7023. cur = llm_build_ffn(ctx0, ffn_inp,
  7024. model.layers[il].ffn_up, NULL,
  7025. model.layers[il].ffn_gate, NULL,
  7026. model.layers[il].ffn_down, NULL,
  7027. NULL,
  7028. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  7029. cb(cur, "ffn_out", il);
  7030. }
  7031. // add together residual + FFN + self-attention
  7032. cur = ggml_add(ctx0, cur, inpL);
  7033. cur = ggml_add(ctx0, cur, attn_out);
  7034. cb(cur, "l_out", il);
  7035. // input for next layer
  7036. inpL = cur;
  7037. }
  7038. cur = inpL;
  7039. cur = llm_build_norm(ctx0, cur, hparams,
  7040. model.output_norm, NULL,
  7041. LLM_NORM, cb, -1);
  7042. cb(cur, "result_norm", -1);
  7043. // lm_head
  7044. cur = ggml_mul_mat(ctx0, model.output, cur);
  7045. if (f_logit_scale) {
  7046. cur = ggml_scale(ctx0, cur, f_logit_scale);
  7047. }
  7048. cb(cur, "result_output", -1);
  7049. ggml_build_forward_expand(gf, cur);
  7050. return gf;
  7051. }
  7052. };
  7053. static struct ggml_cgraph * llama_build_graph_defrag(llama_context & lctx, const std::vector<uint32_t> & ids) {
  7054. llama_batch dummy;
  7055. dummy.n_tokens = 0;
  7056. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  7057. struct llm_build_context llm(lctx, dummy, cb, false);
  7058. llm.init();
  7059. struct ggml_cgraph * result = llm.build_defrag(ids);
  7060. llm.free();
  7061. return result;
  7062. }
  7063. static struct ggml_cgraph * llama_build_graph_k_shift(llama_context & lctx) {
  7064. llama_batch dummy;
  7065. dummy.n_tokens = 0;
  7066. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  7067. struct llm_build_context llm(lctx, dummy, cb, false);
  7068. llm.init();
  7069. struct ggml_cgraph * result = llm.build_k_shift();
  7070. llm.free();
  7071. return result;
  7072. }
  7073. static struct ggml_cgraph * llama_build_graph_s_copy(llama_context & lctx) {
  7074. llama_batch dummy;
  7075. dummy.n_tokens = 0;
  7076. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  7077. struct llm_build_context llm(lctx, dummy, cb, false);
  7078. llm.init();
  7079. struct ggml_cgraph * result = llm.build_s_copy();
  7080. llm.free();
  7081. return result;
  7082. }
  7083. static struct ggml_cgraph * llama_build_graph(
  7084. llama_context & lctx,
  7085. const llama_batch & batch,
  7086. bool worst_case) {
  7087. const auto & model = lctx.model;
  7088. // this callback allows us to apply custom logic to each tensor (e.g. ggml-alloc, offloading, etc.)
  7089. llm_build_cb cb = [&](struct ggml_tensor * cur, const char * name, int il) {
  7090. if (il >= 0) {
  7091. ggml_format_name(cur, "%s-%d", name, il);
  7092. } else {
  7093. ggml_set_name(cur, name);
  7094. }
  7095. if (!lctx.cparams.offload_kqv) {
  7096. if (strcmp(name, "kqv_merged_cont") == 0) {
  7097. // all nodes between the KV store and the attention output are run on the CPU
  7098. ggml_backend_sched_set_tensor_backend(lctx.sched, cur, lctx.backend_cpu);
  7099. }
  7100. }
  7101. // norm may be automatically assigned to the backend of the previous layer, increasing data transfer between backends
  7102. // to fix this, we assign the norm layer manually to the backend of its layer
  7103. if (il != -1 && strcmp(name, "norm") == 0) {
  7104. for (auto * backend : lctx.backends) {
  7105. if (ggml_backend_buft_supports_backend(lctx.model.buft_layer[il].buft, backend)) {
  7106. ggml_backend_sched_set_tensor_backend(lctx.sched, cur, backend);
  7107. break;
  7108. }
  7109. }
  7110. }
  7111. };
  7112. struct ggml_cgraph * result = NULL;
  7113. struct llm_build_context llm(lctx, batch, cb, worst_case);
  7114. llm.init();
  7115. switch (model.arch) {
  7116. case LLM_ARCH_LLAMA:
  7117. {
  7118. result = llm.build_llama();
  7119. } break;
  7120. case LLM_ARCH_BAICHUAN:
  7121. {
  7122. result = llm.build_baichuan();
  7123. } break;
  7124. case LLM_ARCH_FALCON:
  7125. {
  7126. result = llm.build_falcon();
  7127. } break;
  7128. case LLM_ARCH_STARCODER:
  7129. {
  7130. result = llm.build_starcoder();
  7131. } break;
  7132. case LLM_ARCH_PERSIMMON:
  7133. {
  7134. result = llm.build_persimmon();
  7135. } break;
  7136. case LLM_ARCH_REFACT:
  7137. {
  7138. result = llm.build_refact();
  7139. } break;
  7140. case LLM_ARCH_BERT:
  7141. case LLM_ARCH_NOMIC_BERT:
  7142. {
  7143. result = llm.build_bert();
  7144. } break;
  7145. case LLM_ARCH_BLOOM:
  7146. {
  7147. result = llm.build_bloom();
  7148. } break;
  7149. case LLM_ARCH_MPT:
  7150. {
  7151. result = llm.build_mpt();
  7152. } break;
  7153. case LLM_ARCH_STABLELM:
  7154. {
  7155. result = llm.build_stablelm();
  7156. } break;
  7157. case LLM_ARCH_QWEN:
  7158. {
  7159. result = llm.build_qwen();
  7160. } break;
  7161. case LLM_ARCH_QWEN2:
  7162. {
  7163. result = llm.build_qwen2();
  7164. } break;
  7165. case LLM_ARCH_PHI2:
  7166. {
  7167. result = llm.build_phi2();
  7168. } break;
  7169. case LLM_ARCH_PLAMO:
  7170. {
  7171. result = llm.build_plamo();
  7172. } break;
  7173. case LLM_ARCH_GPT2:
  7174. {
  7175. result = llm.build_gpt2();
  7176. } break;
  7177. case LLM_ARCH_CODESHELL:
  7178. {
  7179. result = llm.build_codeshell();
  7180. } break;
  7181. case LLM_ARCH_ORION:
  7182. {
  7183. result = llm.build_orion();
  7184. } break;
  7185. case LLM_ARCH_INTERNLM2:
  7186. {
  7187. result = llm.build_internlm2();
  7188. } break;
  7189. case LLM_ARCH_MINICPM:
  7190. {
  7191. result = llm.build_minicpm();
  7192. } break;
  7193. case LLM_ARCH_GEMMA:
  7194. {
  7195. result = llm.build_gemma();
  7196. } break;
  7197. case LLM_ARCH_STARCODER2:
  7198. {
  7199. result = llm.build_starcoder2();
  7200. } break;
  7201. case LLM_ARCH_MAMBA:
  7202. {
  7203. result = llm.build_mamba();
  7204. } break;
  7205. case LLM_ARCH_COMMAND_R:
  7206. {
  7207. result = llm.build_command_r();
  7208. } break;
  7209. default:
  7210. GGML_ASSERT(false);
  7211. }
  7212. llm.free();
  7213. return result;
  7214. }
  7215. static void llama_set_k_shift(llama_context & lctx) {
  7216. const int64_t kv_size = lctx.kv_self.size;
  7217. assert(ggml_backend_buffer_is_host(lctx.inp_K_shift->buffer));
  7218. int32_t * data = (int32_t *) lctx.inp_K_shift->data;
  7219. for (int i = 0; i < kv_size; ++i) {
  7220. data[i] = lctx.kv_self.cells[i].delta;
  7221. }
  7222. }
  7223. static void llama_set_s_copy(llama_context & lctx) {
  7224. const int64_t kv_size = lctx.kv_self.size;
  7225. assert(ggml_backend_buffer_is_host(lctx.inp_s_copy->buffer));
  7226. int32_t * data = (int32_t *) lctx.inp_s_copy->data;
  7227. for (int i = 0; i < kv_size; ++i) {
  7228. data[i] = lctx.kv_self.cells[i].src;
  7229. }
  7230. }
  7231. static void llama_set_inputs(llama_context & lctx, const llama_batch & batch) {
  7232. //
  7233. // set input data
  7234. //
  7235. const auto & hparams = lctx.model.hparams;
  7236. const auto & cparams = lctx.cparams;
  7237. const auto & kv_self = lctx.kv_self;
  7238. if (batch.token) {
  7239. const int64_t n_tokens = batch.n_tokens;
  7240. ggml_backend_tensor_set(lctx.inp_tokens, batch.token, 0, n_tokens*ggml_element_size(lctx.inp_tokens));
  7241. }
  7242. if (batch.embd) {
  7243. const int64_t n_embd = hparams.n_embd;
  7244. const int64_t n_tokens = batch.n_tokens;
  7245. ggml_backend_tensor_set(lctx.inp_embd, batch.embd, 0, n_tokens*n_embd*ggml_element_size(lctx.inp_embd));
  7246. }
  7247. if (batch.pos && lctx.inp_pos) {
  7248. const int64_t n_tokens = batch.n_tokens;
  7249. ggml_backend_tensor_set(lctx.inp_pos, batch.pos, 0, n_tokens*ggml_element_size(lctx.inp_pos));
  7250. }
  7251. GGML_ASSERT(
  7252. (hparams.causal_attn || !cparams.causal_attn) &&
  7253. "non-causal attention with generative models is not supported"
  7254. );
  7255. if (lctx.inp_KQ_mask) {
  7256. // NOTE: hparams.causal_attn indicates the model is capable of generation and uses the kv cache.
  7257. if (cparams.causal_attn) {
  7258. const int64_t n_kv = kv_self.n;
  7259. const int64_t n_tokens = batch.n_tokens;
  7260. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  7261. float * data = (float *) lctx.inp_KQ_mask->data;
  7262. // For causal attention, use only the previous KV cells
  7263. // of the correct sequence for each token of the batch.
  7264. // It's assumed that if a token in the batch has multiple sequences, they are equivalent.
  7265. for (int h = 0; h < 1; ++h) {
  7266. for (int j = 0; j < n_tokens; ++j) {
  7267. const llama_pos pos = batch.pos[j];
  7268. const llama_seq_id seq_id = batch.seq_id[j][0];
  7269. for (int i = 0; i < n_kv; ++i) {
  7270. float f;
  7271. if (!lctx.kv_self.cells[i].has_seq_id(seq_id) || lctx.kv_self.cells[i].pos > pos) {
  7272. f = -INFINITY;
  7273. } else {
  7274. f = 0.0f;
  7275. }
  7276. data[h*(n_kv*n_tokens) + j*n_kv + i] = f;
  7277. }
  7278. }
  7279. }
  7280. } else {
  7281. // when using kv cache, the mask needs to match the kv cache size
  7282. const int64_t n_tokens = batch.n_tokens;
  7283. const int64_t n_stride = hparams.causal_attn ? kv_self.n : n_tokens;
  7284. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  7285. float * data = (float *) lctx.inp_KQ_mask->data;
  7286. for (int h = 0; h < 1; ++h) {
  7287. for (int j = 0; j < n_tokens; ++j) {
  7288. const llama_seq_id seq_id = batch.seq_id[j][0];
  7289. for (int i = 0; i < n_tokens; ++i) {
  7290. float f = -INFINITY;
  7291. for (int s = 0; s < batch.n_seq_id[i]; ++s) {
  7292. if (batch.seq_id[i][s] == seq_id) {
  7293. f = 0.0f;
  7294. break;
  7295. }
  7296. }
  7297. data[h*(n_tokens*n_tokens) + j*n_stride + i] = f;
  7298. }
  7299. for (int i = n_tokens; i < n_stride; ++i) {
  7300. data[h*(n_tokens*n_tokens) + j*n_stride + i] = -INFINITY;
  7301. }
  7302. }
  7303. }
  7304. }
  7305. }
  7306. if (hparams.need_kq_pos) {
  7307. const int64_t n_kv = kv_self.n;
  7308. GGML_ASSERT(lctx.inp_KQ_pos);
  7309. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_pos->buffer));
  7310. float * data = (float *) lctx.inp_KQ_pos->data;
  7311. for (int i = 0; i < n_kv; ++i) {
  7312. data[i] = float(lctx.kv_self.cells[i].pos);
  7313. }
  7314. }
  7315. if (cparams.pooling_type == LLAMA_POOLING_TYPE_MEAN) {
  7316. const int64_t n_tokens = batch.n_tokens;
  7317. GGML_ASSERT(lctx.inp_mean);
  7318. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_mean->buffer));
  7319. float * data = (float *) lctx.inp_mean->data;
  7320. memset(lctx.inp_mean->data, 0, n_tokens * n_tokens * ggml_element_size(lctx.inp_mean));
  7321. std::vector<uint64_t> sum(n_tokens, 0);
  7322. for (int i = 0; i < n_tokens; ++i) {
  7323. const llama_seq_id seq_id = batch.seq_id[i][0];
  7324. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == MEAN");
  7325. sum[seq_id] += 1;
  7326. }
  7327. std::vector<float> div(n_tokens, 0.0f);
  7328. for (int i = 0; i < n_tokens; ++i) {
  7329. const uint64_t s = sum[i];
  7330. if (s > 0) {
  7331. div[i] = 1.0f/float(s);
  7332. }
  7333. }
  7334. for (int i = 0; i < n_tokens; ++i) {
  7335. const llama_seq_id seq_id = batch.seq_id[i][0];
  7336. data[seq_id*n_tokens + i] = div[seq_id];
  7337. }
  7338. }
  7339. if (cparams.pooling_type == LLAMA_POOLING_TYPE_CLS) {
  7340. const int64_t n_tokens = batch.n_tokens;
  7341. GGML_ASSERT(lctx.inp_cls);
  7342. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_cls->buffer));
  7343. uint32_t * data = (uint32_t *) lctx.inp_cls->data;
  7344. memset(lctx.inp_cls->data, 0, n_tokens * ggml_element_size(lctx.inp_cls));
  7345. for (int i = 0; i < n_tokens; ++i) {
  7346. const llama_seq_id seq_id = batch.seq_id[i][0];
  7347. const llama_pos pos = batch.pos[i];
  7348. GGML_ASSERT(seq_id < n_tokens && "seq_id cannot be larger than n_tokens with pooling_type == CLS");
  7349. if (pos == 0) {
  7350. data[seq_id] = i;
  7351. }
  7352. }
  7353. }
  7354. if (kv_self.recurrent) {
  7355. const int64_t n_kv = kv_self.n;
  7356. if (lctx.inp_s_mask) {
  7357. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_s_mask->buffer));
  7358. float * data = (float *) lctx.inp_s_mask->data;
  7359. // states which are not affected by the current batch are left untouched
  7360. for (int i = 0; i < n_kv; ++i) {
  7361. llama_seq_id seq_id = i + lctx.kv_self.head;
  7362. llama_kv_cell & kv_cell = lctx.kv_self.cells[seq_id];
  7363. bool has_self_seq = kv_cell.has_seq_id(seq_id);
  7364. data[i] = (float) has_self_seq;
  7365. // ensure current sequences will be kept
  7366. if (!has_self_seq && kv_cell.pos >= 0) {
  7367. kv_cell.seq_id.insert(seq_id);
  7368. }
  7369. }
  7370. }
  7371. // For Mamba (and other recurrent architectures),
  7372. // update the correct state(s)/sequence(s) for each token of the batch.
  7373. // Like with the KQ_mask, if a token in the batch has multiple sequences,
  7374. // they are assumed to be equivalent (not here, but in ggml_ssm_scan and ggml_ssm_conv).
  7375. if (lctx.inp_s_seq) {
  7376. const int64_t n_tokens = batch.n_tokens;
  7377. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_s_seq->buffer));
  7378. int32_t * data = (int32_t *) lctx.inp_s_seq->data;
  7379. for (int j = 0; j < n_tokens; ++j) {
  7380. const int32_t n_seq = batch.n_seq_id[j];
  7381. GGML_ASSERT(0 < n_seq); // a token should be part of at least 1 sequence
  7382. for (int i = 0; i < n_kv; ++i) {
  7383. if (i < n_seq) {
  7384. // for this type of model, the head is the minimum seq_id of the batch
  7385. data[j*n_kv + i] = batch.seq_id[j][i] - kv_self.head;
  7386. } else {
  7387. data[j*n_kv + i] = -1;
  7388. }
  7389. }
  7390. }
  7391. }
  7392. }
  7393. }
  7394. static void llama_graph_compute(
  7395. llama_context & lctx,
  7396. ggml_cgraph * gf,
  7397. int n_threads) {
  7398. #ifdef GGML_USE_MPI
  7399. const int64_t n_layer = lctx.model.hparams.n_layer;
  7400. ggml_mpi_graph_compute_pre(lctx.ctx_mpi, gf, n_layer);
  7401. #endif
  7402. #ifdef GGML_USE_METAL
  7403. if (ggml_backend_is_metal(lctx.backend_metal)) {
  7404. ggml_backend_metal_set_n_cb(lctx.backend_metal, n_threads);
  7405. }
  7406. #endif
  7407. if (lctx.backend_cpu != nullptr) {
  7408. ggml_backend_cpu_set_n_threads(lctx.backend_cpu, n_threads);
  7409. ggml_backend_cpu_set_abort_callback(lctx.backend_cpu, lctx.abort_callback, lctx.abort_callback_data);
  7410. }
  7411. ggml_backend_sched_graph_compute_async(lctx.sched, gf);
  7412. // fprintf(stderr, "splits: %d\n", ggml_backend_sched_get_n_splits(lctx.sched));
  7413. #ifdef GGML_USE_MPI
  7414. ggml_mpi_graph_compute_post(lctx.ctx_mpi, gf, n_layer);
  7415. #endif
  7416. }
  7417. // decode a batch of tokens by evaluating the transformer
  7418. //
  7419. // - lctx: llama context
  7420. // - batch: batch to evaluate
  7421. //
  7422. // return 0 on success
  7423. // return positive int on warning
  7424. // return negative int on error
  7425. //
  7426. static int llama_decode_internal(
  7427. llama_context & lctx,
  7428. llama_batch batch_all) { // TODO: rename back to batch
  7429. const uint32_t n_tokens_all = batch_all.n_tokens;
  7430. if (n_tokens_all == 0) {
  7431. LLAMA_LOG_ERROR("%s: n_tokens == 0", __func__);
  7432. return -1;
  7433. }
  7434. const auto & model = lctx.model;
  7435. const auto & hparams = model.hparams;
  7436. const auto & cparams = lctx.cparams;
  7437. GGML_ASSERT((!batch_all.token && batch_all.embd) || (batch_all.token && !batch_all.embd)); // NOLINT
  7438. GGML_ASSERT(n_tokens_all <= cparams.n_batch);
  7439. GGML_ASSERT((cparams.causal_attn || cparams.n_ubatch >= n_tokens_all) && "non-causal attention requires n_ubatch >= n_tokens");
  7440. if (lctx.t_compute_start_us == 0) {
  7441. lctx.t_compute_start_us = ggml_time_us();
  7442. }
  7443. lctx.n_queued_tokens += n_tokens_all;
  7444. #ifdef GGML_USE_MPI
  7445. // TODO: needs fix after #3228
  7446. GGML_ASSERT(false && "not implemented");
  7447. //ggml_mpi_eval_init(lctx.ctx_mpi, &n_tokens, &n_past, &n_threads);
  7448. #endif
  7449. auto & kv_self = lctx.kv_self;
  7450. const int64_t n_embd = hparams.n_embd;
  7451. const int64_t n_vocab = hparams.n_vocab;
  7452. auto * logits_out = lctx.logits;
  7453. #ifndef NDEBUG
  7454. auto & logits_valid = lctx.logits_valid;
  7455. logits_valid.clear();
  7456. logits_valid.resize(n_tokens_all);
  7457. memset(logits_out, 0, lctx.logits_size*sizeof(float));
  7458. #endif
  7459. const auto n_ubatch = cparams.n_ubatch;
  7460. std::vector<llama_pos> pos;
  7461. std::vector<int32_t> n_seq_id;
  7462. std::vector<llama_seq_id *> seq_id_arr;
  7463. std::vector<std::vector<llama_seq_id>> seq_id;
  7464. for (uint32_t cur_token = 0; cur_token < n_tokens_all; cur_token += n_ubatch) {
  7465. const uint32_t n_tokens = std::min(n_ubatch, n_tokens_all - cur_token);
  7466. llama_batch u_batch = {
  7467. /* .n_tokens = */ (int32_t) n_tokens,
  7468. /* .token = */ batch_all.token ? batch_all.token + cur_token : nullptr,
  7469. /* .embd = */ batch_all.embd ? batch_all.embd + cur_token*n_embd : nullptr,
  7470. /* .pos = */ batch_all.pos ? batch_all.pos + cur_token : nullptr,
  7471. /* .n_seq_id = */ batch_all.n_seq_id ? batch_all.n_seq_id + cur_token : nullptr,
  7472. /* .seq_id = */ batch_all.seq_id ? batch_all.seq_id + cur_token : nullptr,
  7473. /* .logits = */ batch_all.logits ? batch_all.logits + cur_token : nullptr,
  7474. /* .all_pos_0 = */ batch_all.all_pos_0 + (llama_pos) cur_token*batch_all.all_pos_1,
  7475. /* .all_pos_1 = */ batch_all.all_pos_1,
  7476. /* .all_seq_id = */ batch_all.all_seq_id,
  7477. };
  7478. int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  7479. GGML_ASSERT(n_threads > 0);
  7480. // helpers for smoother batch API transition
  7481. // after deprecating the llama_eval calls, these will be removed
  7482. if (u_batch.pos == nullptr) {
  7483. pos.resize(n_tokens);
  7484. for (uint32_t i = 0; i < n_tokens; i++) {
  7485. pos[i] = u_batch.all_pos_0 + i*u_batch.all_pos_1;
  7486. }
  7487. u_batch.pos = pos.data();
  7488. }
  7489. if (u_batch.seq_id == nullptr) {
  7490. n_seq_id.resize(n_tokens);
  7491. seq_id.resize(n_tokens);
  7492. seq_id_arr.resize(n_tokens);
  7493. for (uint32_t i = 0; i < n_tokens; i++) {
  7494. n_seq_id[i] = 1;
  7495. seq_id[i].resize(1);
  7496. seq_id[i][0] = u_batch.all_seq_id;
  7497. seq_id_arr[i] = seq_id[i].data();
  7498. }
  7499. u_batch.n_seq_id = n_seq_id.data();
  7500. u_batch.seq_id = seq_id_arr.data();
  7501. }
  7502. // non-causal masks do not use the KV cache
  7503. if (hparams.causal_attn) {
  7504. llama_kv_cache_update(&lctx);
  7505. // if we have enough unused cells before the current head ->
  7506. // better to start searching from the beginning of the cache, hoping to fill it
  7507. if (kv_self.head > kv_self.used + 2*n_tokens) {
  7508. kv_self.head = 0;
  7509. }
  7510. if (!llama_kv_cache_find_slot(kv_self, u_batch)) {
  7511. return 1;
  7512. }
  7513. if (!kv_self.recurrent) {
  7514. // a heuristic, to avoid attending the full cache if it is not yet utilized
  7515. // after enough generations, the benefit from this heuristic disappears
  7516. // if we start defragmenting the cache, the benefit from this will be more important
  7517. kv_self.n = std::min(kv_self.size, std::max(32u, GGML_PAD(llama_kv_cache_cell_max(kv_self), 32)));
  7518. //kv_self.n = llama_kv_cache_cell_max(kv_self);
  7519. }
  7520. }
  7521. //printf("kv_self.n = %5d, kv_self.used = %5d, kv_self.head = %5d\n", kv_self.n, kv_self.used, kv_self.head);
  7522. ggml_backend_sched_reset(lctx.sched);
  7523. ggml_backend_sched_set_eval_callback(lctx.sched, lctx.cparams.cb_eval, lctx.cparams.cb_eval_user_data);
  7524. ggml_cgraph * gf = llama_build_graph(lctx, u_batch, false);
  7525. // the output is always the last tensor in the graph
  7526. struct ggml_tensor * res = gf->nodes[gf->n_nodes - 1];
  7527. struct ggml_tensor * embd = gf->nodes[gf->n_nodes - 2];
  7528. if (!hparams.causal_attn) {
  7529. res = nullptr; // do not extract logits for embedding models such as BERT
  7530. // token or sequence embeddings
  7531. embd = gf->nodes[gf->n_nodes - 1];
  7532. GGML_ASSERT(strcmp(embd->name, "result_embd") == 0 || strcmp(embd->name, "result_embd_pooled") == 0);
  7533. } else {
  7534. if (strcmp(res->name, "result_output") == 0) {
  7535. // the token embeddings could be the second to last tensor, or the third to last tensor
  7536. if (strcmp(embd->name, "result_norm") != 0) {
  7537. embd = gf->nodes[gf->n_nodes - 3];
  7538. GGML_ASSERT(strcmp(embd->name, "result_norm") == 0);
  7539. }
  7540. } else {
  7541. GGML_ASSERT(false && "missing result_output tensor");
  7542. }
  7543. }
  7544. // 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);
  7545. // for big prompts, if BLAS is enabled, it is better to use only one thread
  7546. // otherwise, the threads are spin-lock waiting for the BLAS calls and are degrading the performance
  7547. // TODO: this is mostly important for Apple Silicon where CBLAS is still performing very well
  7548. // we still need some threads to process all non-mul_mat ops, but not too much to avoid interfering
  7549. // with the BLAS calls. need a better solution
  7550. // MoE Special Case: This logic applies when hparams.n_expert == 0, i.e. the model is NOT an MoE model. When an MoE is
  7551. // being processed then Accelerate/BLAS will not be involved, so capping would limit performance.
  7552. if (n_tokens >= 32 && hparams.n_expert == 0 && ggml_cpu_has_blas() && !ggml_cpu_has_gpublas()) {
  7553. n_threads = std::min(4, n_threads);
  7554. }
  7555. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  7556. llama_set_inputs(lctx, u_batch);
  7557. llama_graph_compute(lctx, gf, n_threads);
  7558. // update the kv ring buffer
  7559. {
  7560. kv_self.head += n_tokens;
  7561. // Ensure kv cache head points to a valid index.
  7562. if (kv_self.head >= kv_self.size) {
  7563. kv_self.head = 0;
  7564. }
  7565. }
  7566. #ifdef GGML_PERF
  7567. // print timing information per ggml operation (for debugging purposes)
  7568. // requires GGML_PERF to be defined
  7569. ggml_graph_print(gf);
  7570. #endif
  7571. // plot the computation graph in dot format (for debugging purposes)
  7572. //if (n_past%100 == 0) {
  7573. // ggml_graph_dump_dot(gf, NULL, "llama.dot");
  7574. //}
  7575. // extract logits
  7576. // TODO: do not compute and extract logits if only embeddings are needed
  7577. // update the graphs to skip "result_output" if logits are not needed
  7578. if (res) {
  7579. ggml_backend_t backend_res = ggml_backend_sched_get_tensor_backend(lctx.sched, res);
  7580. GGML_ASSERT(backend_res != nullptr);
  7581. if (u_batch.logits) {
  7582. int32_t i_first = -1;
  7583. for (uint32_t i = 0; i < n_tokens; i++) {
  7584. if (u_batch.logits[i] && i_first == -1) {
  7585. i_first = (int32_t) i;
  7586. }
  7587. if (u_batch.logits[i] == 0 || i == n_tokens - 1) {
  7588. if (i_first != -1) {
  7589. int i_last = u_batch.logits[i] == 0 ? i : i + 1;
  7590. // extract logits for the range [i_first, i_last)
  7591. // group the requests to minimize the number of calls to the backend
  7592. ggml_backend_tensor_get_async(backend_res, res,
  7593. logits_out + n_vocab*(cur_token + i_first),
  7594. i_first*n_vocab*sizeof(float),
  7595. (i_last - i_first)*n_vocab*sizeof(float));
  7596. i_first = -1;
  7597. }
  7598. }
  7599. #ifndef NDEBUG
  7600. logits_valid[cur_token + i] = u_batch.logits[i] != 0;;
  7601. #endif
  7602. }
  7603. } else if (lctx.logits_all) {
  7604. ggml_backend_tensor_get_async(backend_res, res, logits_out + n_vocab*cur_token, 0, n_vocab*n_tokens*sizeof(float));
  7605. #ifndef NDEBUG
  7606. std::fill(logits_valid.begin() + cur_token, logits_valid.begin() + cur_token + n_tokens, true);
  7607. #endif
  7608. } else {
  7609. if (cur_token + n_tokens >= n_tokens_all) {
  7610. ggml_backend_tensor_get_async(backend_res, res, logits_out, n_vocab*(n_tokens - 1)*sizeof(float), n_vocab*sizeof(float));
  7611. #ifndef NDEBUG
  7612. logits_valid[0] = true;
  7613. #endif
  7614. }
  7615. }
  7616. }
  7617. // extract embeddings
  7618. if (cparams.embeddings && embd) {
  7619. ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend(lctx.sched, embd);
  7620. GGML_ASSERT(backend_embd != nullptr);
  7621. switch (cparams.pooling_type) {
  7622. case LLAMA_POOLING_TYPE_NONE:
  7623. {
  7624. // extract token embeddings
  7625. auto & embd_out = lctx.embd;
  7626. if (u_batch.logits) {
  7627. //embd_out.resize(n_embd * n_tokens);
  7628. for (uint32_t i = 0; i < n_tokens; i++) {
  7629. if (u_batch.logits[i] == 0) {
  7630. continue;
  7631. }
  7632. ggml_backend_tensor_get_async(backend_embd, embd, embd_out + n_embd*(i + cur_token), (n_embd*i)*sizeof(float), n_embd*sizeof(float));
  7633. }
  7634. }
  7635. } break;
  7636. case LLAMA_POOLING_TYPE_CLS:
  7637. case LLAMA_POOLING_TYPE_MEAN:
  7638. {
  7639. GGML_ASSERT(strcmp(embd->name, "result_embd_pooled") == 0);
  7640. // extract sequence embeddings
  7641. auto & embd_seq_out = lctx.embd_seq;
  7642. embd_seq_out.clear();
  7643. for (uint32_t i = 0; i < n_tokens; i++) {
  7644. const llama_seq_id seq_id = u_batch.seq_id[i][0];
  7645. if (embd_seq_out.find(seq_id) != embd_seq_out.end()) {
  7646. continue;
  7647. }
  7648. embd_seq_out[seq_id].resize(n_embd);
  7649. ggml_backend_tensor_get_async(backend_embd, embd, embd_seq_out[seq_id].data(), (n_embd*seq_id)*sizeof(float), n_embd*sizeof(float));
  7650. }
  7651. } break;
  7652. case LLAMA_POOLING_TYPE_UNSPECIFIED:
  7653. {
  7654. GGML_ASSERT(false && "unknown pooling type");
  7655. } break;
  7656. }
  7657. }
  7658. }
  7659. // wait for the computation to finish (automatically done when obtaining the model output)
  7660. //llama_synchronize(&lctx);
  7661. // decide if we need to defrag the kv cache
  7662. if (cparams.causal_attn && cparams.defrag_thold >= 0.0f) {
  7663. const float fragmentation = kv_self.n >= 128 ? 1.0f - float(kv_self.used)/float(kv_self.n) : 0.0f;
  7664. // queue defragmentation for next llama_kv_cache_update
  7665. if (fragmentation > cparams.defrag_thold) {
  7666. //LLAMA_LOG_INFO("fragmentation: %.2f\n", fragmentation);
  7667. llama_kv_cache_defrag(kv_self);
  7668. }
  7669. }
  7670. return 0;
  7671. }
  7672. // find holes from the beginning of the KV cache and fill them by moving data from the end of the cache
  7673. static void llama_kv_cache_defrag_internal(struct llama_context & lctx) {
  7674. auto & kv_self = lctx.kv_self;
  7675. const auto & hparams = lctx.model.hparams;
  7676. const uint32_t n_layer = hparams.n_layer;
  7677. const uint32_t n_kv = llama_kv_cache_cell_max(kv_self);
  7678. const uint32_t n_used = kv_self.used;
  7679. assert(n_used <= n_kv);
  7680. //const int64_t t_start = ggml_time_us();
  7681. // number of cells moved
  7682. uint32_t n_moves = 0;
  7683. // each move requires 6*n_layer tensors (see build_defrag)
  7684. // - source view, destination view, copy operation
  7685. // - x2 for keys and values
  7686. const uint32_t max_moves = LLAMA_MAX_NODES/(6*n_layer);
  7687. // determine which KV cells to move where
  7688. //
  7689. // cell i moves to ids[i]
  7690. //
  7691. // if ids[i] == i || ids[i] == n_kv, then cell i is not moved
  7692. //
  7693. std::vector<uint32_t> ids(n_kv, n_kv);
  7694. for (uint32_t i0 = 0; i0 < n_used; ++i0) {
  7695. const auto & cell0 = kv_self.cells[i0];
  7696. if (!cell0.is_empty()) {
  7697. ids[i0] = i0;
  7698. continue;
  7699. }
  7700. // found a hole - fill it with data from the end of the cache
  7701. uint32_t nh = 1;
  7702. // determine the size of the hole
  7703. while (i0 + nh < n_used && kv_self.cells[i0 + nh].is_empty()) {
  7704. nh++;
  7705. }
  7706. uint32_t nf = 0;
  7707. uint32_t is = n_kv - 1;
  7708. // starting from the end, find nh non-empty cells
  7709. for (; is > i0; --is) {
  7710. const auto & cell1 = kv_self.cells[is];
  7711. if (cell1.is_empty() || ids[is] != n_kv) {
  7712. continue;
  7713. }
  7714. // non-empty cell which is not yet moved
  7715. nf++;
  7716. if (nf == nh) {
  7717. break;
  7718. }
  7719. }
  7720. // this can only happen if `n_used` is not accurate, which would be a bug
  7721. GGML_ASSERT(nf == nh && "KV defrag bug: nf != nh");
  7722. nf = 0;
  7723. uint32_t i1 = is;
  7724. // are we moving a continuous block of memory?
  7725. bool cont = false;
  7726. // should we stop searching for the next move?
  7727. bool stop = false;
  7728. // go back and move the nf cells to the hole
  7729. for (; i1 < n_kv; ++i1) {
  7730. auto & cell1 = kv_self.cells[i1];
  7731. if (cell1.is_empty() || ids[i1] != n_kv) {
  7732. if (n_moves == max_moves) {
  7733. stop = true;
  7734. break;
  7735. }
  7736. cont = false;
  7737. continue;
  7738. }
  7739. // this cell goes to (i0 + nf)
  7740. ids[i1] = i0 + nf;
  7741. // move the cell meta data
  7742. kv_self.cells[i0 + nf] = cell1;
  7743. // clear the old cell and move the head there
  7744. cell1 = llama_kv_cell();
  7745. kv_self.head = n_used;
  7746. if (!cont) {
  7747. n_moves++;
  7748. cont = true;
  7749. }
  7750. nf++;
  7751. if (nf == nh) {
  7752. break;
  7753. }
  7754. }
  7755. if (stop || n_moves == max_moves) {
  7756. break;
  7757. }
  7758. //LLAMA_LOG_INFO("(tmp log) KV defrag: move [%u, %u) to [%u, %u)\n", is, i1 + 1, i0, i0 + nh);
  7759. i0 += nh - 1;
  7760. }
  7761. if (n_moves == 0) {
  7762. return;
  7763. }
  7764. //LLAMA_LOG_INFO("(tmp log) KV defrag cell moves: %u\n", n_moves);
  7765. //LLAMA_LOG_INFO("expected gf nodes: %u\n", 6*n_moves*n_layer);
  7766. #if 0
  7767. // CPU defrag
  7768. //
  7769. // TODO: optimizations are possible:
  7770. // - multiple threads
  7771. // - avoid copying to the host memory when already there
  7772. //
  7773. // likely not worth the effort, as we have ggml_graph based defrag
  7774. //
  7775. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  7776. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  7777. const uint32_t kv_size = kv_self.size;
  7778. std::vector<uint8_t> buf_k;
  7779. std::vector<uint8_t> buf_v;
  7780. for (uint32_t il = 0; il < n_layer; ++il) {
  7781. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  7782. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_size);
  7783. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  7784. const size_t v_size = ggml_row_size (kv_self.v_l[il]->type, n_embd_v_gqa*kv_size);
  7785. buf_k.resize(k_size);
  7786. buf_v.resize(v_size);
  7787. ggml_backend_tensor_get(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  7788. ggml_backend_tensor_get(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  7789. // batch move [i, i+nm) to [id, id+nm)
  7790. // note: cells can move only to a lower index
  7791. for (uint32_t i = 0; i < n_kv; ++i) {
  7792. const uint32_t id = ids[i];
  7793. if (i == id || id == n_kv) {
  7794. continue;
  7795. }
  7796. uint32_t nm = 1;
  7797. while (i + nm < n_kv && ids[i + nm] == id + nm) {
  7798. nm++;
  7799. }
  7800. // move keys
  7801. {
  7802. const int64_t os = i*k_size_row;
  7803. const int64_t od = id*k_size_row;
  7804. memcpy(buf_k.data() + od, buf_k.data() + os, nm*k_size_row);
  7805. }
  7806. // move values (note: they are transposed)
  7807. {
  7808. const int64_t os = i;
  7809. const int64_t od = id;
  7810. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  7811. 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);
  7812. }
  7813. }
  7814. i += nm - 1;
  7815. }
  7816. ggml_backend_tensor_set(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  7817. ggml_backend_tensor_set(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  7818. }
  7819. #else
  7820. // ggml_graph defrag
  7821. ggml_backend_sched_reset(lctx.sched);
  7822. ggml_cgraph * gf = llama_build_graph_defrag(lctx, ids);
  7823. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  7824. #endif
  7825. //const int64_t t_end = ggml_time_us();
  7826. //LLAMA_LOG_INFO("(tmp log) KV defrag time: %.3f ms\n", (t_end - t_start)/1000.0);
  7827. }
  7828. static void llama_kv_cache_update_internal(struct llama_context & lctx) {
  7829. bool need_reserve = false;
  7830. // apply K-shift if needed
  7831. if (lctx.model.hparams.rope_type != LLAMA_ROPE_TYPE_NONE && lctx.kv_self.has_shift) {
  7832. {
  7833. ggml_backend_sched_reset(lctx.sched);
  7834. ggml_cgraph * gf = llama_build_graph_k_shift(lctx);
  7835. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  7836. llama_set_k_shift(lctx);
  7837. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  7838. need_reserve = true;
  7839. }
  7840. {
  7841. auto & kv_self = lctx.kv_self;
  7842. kv_self.has_shift = false;
  7843. for (uint32_t i = 0; i < kv_self.size; ++i) {
  7844. kv_self.cells[i].delta = 0;
  7845. }
  7846. }
  7847. }
  7848. if (lctx.kv_self.recurrent && lctx.kv_self.do_copy) {
  7849. {
  7850. ggml_backend_sched_reset(lctx.sched);
  7851. ggml_cgraph * gf = llama_build_graph_s_copy(lctx);
  7852. ggml_backend_sched_alloc_graph(lctx.sched, gf);
  7853. llama_set_s_copy(lctx);
  7854. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  7855. need_reserve = true;
  7856. }
  7857. {
  7858. auto & kv_self = lctx.kv_self;
  7859. kv_self.do_copy = false;
  7860. for (uint32_t i = 0; i < kv_self.size; ++i) {
  7861. kv_self.cells[i].src = i;
  7862. }
  7863. }
  7864. }
  7865. // defragment the KV cache if needed
  7866. if (lctx.kv_self.do_defrag) {
  7867. llama_kv_cache_defrag_internal(lctx);
  7868. need_reserve = true;
  7869. lctx.kv_self.do_defrag = false;
  7870. }
  7871. // reserve a worst case graph again
  7872. if (need_reserve) {
  7873. // TODO: extract to a function
  7874. // build worst-case graph
  7875. int n_tokens = (int)std::min(lctx.cparams.n_ctx, lctx.cparams.n_ubatch);
  7876. int n_past = lctx.cparams.n_ctx - n_tokens;
  7877. 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
  7878. ggml_cgraph * gf = llama_build_graph(lctx, llama_batch_get_one(&token, n_tokens, n_past, 0), true);
  7879. // initialize scheduler with the worst-case graph
  7880. ggml_backend_sched_reset(lctx.sched);
  7881. if (!ggml_backend_sched_reserve(lctx.sched, gf)) {
  7882. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  7883. }
  7884. }
  7885. }
  7886. //
  7887. // tokenizer
  7888. //
  7889. static enum llama_vocab_type llama_vocab_get_type(const llama_vocab & vocab) {
  7890. return vocab.type;
  7891. }
  7892. static bool llama_is_normal_token(const llama_vocab & vocab, llama_token id) {
  7893. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  7894. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL;
  7895. }
  7896. static bool llama_is_unknown_token(const llama_vocab & vocab, llama_token id) {
  7897. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  7898. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_UNKNOWN;
  7899. }
  7900. static bool llama_is_control_token(const llama_vocab & vocab, llama_token id) {
  7901. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  7902. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_CONTROL;
  7903. }
  7904. static bool llama_is_byte_token(const llama_vocab & vocab, llama_token id) {
  7905. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  7906. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_BYTE;
  7907. }
  7908. static bool llama_is_user_defined_token(const llama_vocab& vocab, llama_token id) {
  7909. GGML_ASSERT(vocab.type != LLAMA_VOCAB_TYPE_NONE);
  7910. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_USER_DEFINED;
  7911. }
  7912. static uint8_t llama_token_to_byte(const llama_vocab& vocab, llama_token id) {
  7913. GGML_ASSERT(llama_vocab_get_type(vocab) != LLAMA_VOCAB_TYPE_NONE);
  7914. GGML_ASSERT(llama_is_byte_token(vocab, id));
  7915. const auto& token_data = vocab.id_to_token.at(id);
  7916. switch (llama_vocab_get_type(vocab)) {
  7917. case LLAMA_VOCAB_TYPE_SPM: {
  7918. auto buf = token_data.text.substr(3, 2);
  7919. return strtol(buf.c_str(), NULL, 16);
  7920. }
  7921. case LLAMA_VOCAB_TYPE_BPE: {
  7922. GGML_ASSERT(false);
  7923. return unicode_utf8_to_byte(token_data.text);
  7924. }
  7925. case LLAMA_VOCAB_TYPE_WPM: {
  7926. GGML_ASSERT(false);
  7927. }
  7928. default:
  7929. GGML_ASSERT(false);
  7930. }
  7931. }
  7932. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch) {
  7933. GGML_ASSERT(llama_vocab_get_type(vocab) != LLAMA_VOCAB_TYPE_NONE);
  7934. static const char * hex = "0123456789ABCDEF";
  7935. switch (llama_vocab_get_type(vocab)) {
  7936. case LLAMA_VOCAB_TYPE_SPM: {
  7937. const char buf[7] = { '<', '0', 'x', hex[ch >> 4], hex[ch & 15], '>', 0 };
  7938. auto token = vocab.token_to_id.find(buf);
  7939. if (token != vocab.token_to_id.end()) {
  7940. return (*token).second;
  7941. }
  7942. // Try to fall back to just the byte as a string
  7943. const char buf2[2] = { (char)ch, 0 };
  7944. return vocab.token_to_id.at(buf2);
  7945. }
  7946. case LLAMA_VOCAB_TYPE_WPM:
  7947. case LLAMA_VOCAB_TYPE_BPE: {
  7948. return vocab.token_to_id.at(unicode_byte_to_utf8(ch));
  7949. }
  7950. default:
  7951. GGML_ASSERT(false);
  7952. }
  7953. }
  7954. static void llama_escape_whitespace(std::string & text) {
  7955. replace_all(text, " ", "\xe2\x96\x81");
  7956. }
  7957. static void llama_unescape_whitespace(std::string & word) {
  7958. replace_all(word, "\xe2\x96\x81", " ");
  7959. }
  7960. struct llm_symbol {
  7961. using index = int;
  7962. index prev;
  7963. index next;
  7964. const char * text;
  7965. size_t n;
  7966. };
  7967. static_assert(std::is_trivially_copyable<llm_symbol>::value, "llm_symbol is not trivially copyable");
  7968. // SPM tokenizer
  7969. // original implementation:
  7970. // https://github.com/ggerganov/llama.cpp/commit/074bea2eb1f1349a0118239c4152914aecaa1be4
  7971. struct llm_bigram_spm {
  7972. struct comparator {
  7973. bool operator()(llm_bigram_spm & l, llm_bigram_spm & r) {
  7974. return (l.score < r.score) || (l.score == r.score && l.left > r.left);
  7975. }
  7976. };
  7977. using queue_storage = std::vector<llm_bigram_spm>;
  7978. using queue = std::priority_queue<llm_bigram_spm, queue_storage, comparator>;
  7979. llm_symbol::index left;
  7980. llm_symbol::index right;
  7981. float score;
  7982. size_t size;
  7983. };
  7984. struct llm_tokenizer_spm {
  7985. llm_tokenizer_spm(const llama_vocab & vocab) : vocab(vocab) {}
  7986. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  7987. // split string into utf8 chars
  7988. int index = 0;
  7989. size_t offs = 0;
  7990. while (offs < text.size()) {
  7991. llm_symbol sym;
  7992. size_t len = utf8_len(text[offs]);
  7993. sym.text = text.c_str() + offs;
  7994. sym.n = std::min(len, text.size() - offs);
  7995. offs += sym.n;
  7996. sym.prev = index - 1;
  7997. sym.next = offs == text.size() ? -1 : index + 1;
  7998. index++;
  7999. symbols.emplace_back(sym);
  8000. }
  8001. // seed the work queue with all possible 2-character tokens.
  8002. for (size_t i = 1; i < symbols.size(); ++i) {
  8003. try_add_bigram(i - 1, i);
  8004. }
  8005. // keep substituting the highest frequency pairs for as long as we can.
  8006. while (!work_queue.empty()) {
  8007. auto bigram = work_queue.top();
  8008. work_queue.pop();
  8009. auto & left_sym = symbols[bigram.left];
  8010. auto & right_sym = symbols[bigram.right];
  8011. // if one of the symbols already got merged, skip it.
  8012. if (left_sym.n == 0 || right_sym.n == 0 ||
  8013. left_sym.n + right_sym.n != bigram.size) {
  8014. continue;
  8015. }
  8016. // merge the right sym into the left one
  8017. left_sym.n += right_sym.n;
  8018. right_sym.n = 0;
  8019. //LLAMA_LOG_INFO("left = '%*s' size = %zu\n", (int) left_sym.n, left_sym.text, bigram.size);
  8020. // remove the right sym from the chain
  8021. left_sym.next = right_sym.next;
  8022. if (right_sym.next >= 0) {
  8023. symbols[right_sym.next].prev = bigram.left;
  8024. }
  8025. // find more substitutions
  8026. try_add_bigram(left_sym.prev, bigram.left);
  8027. try_add_bigram(bigram.left, left_sym.next);
  8028. }
  8029. for (int i = 0; i != -1; i = symbols[i].next) {
  8030. auto & symbol = symbols[i];
  8031. resegment(symbol, output);
  8032. }
  8033. }
  8034. private:
  8035. void resegment(llm_symbol & symbol, std::vector<llama_vocab::id> & output) {
  8036. auto text = std::string(symbol.text, symbol.n);
  8037. auto token = vocab.token_to_id.find(text);
  8038. // Do we need to support is_unused?
  8039. if (token != vocab.token_to_id.end()) {
  8040. output.push_back((*token).second);
  8041. return;
  8042. }
  8043. const auto p = rev_merge.find(text);
  8044. if (p == rev_merge.end()) {
  8045. // output any symbols that did not form tokens as bytes.
  8046. output.reserve(output.size() + symbol.n);
  8047. for (int j = 0; j < (int)symbol.n; ++j) {
  8048. llama_vocab::id token_id = llama_byte_to_token(vocab, symbol.text[j]);
  8049. output.push_back(token_id);
  8050. }
  8051. return;
  8052. }
  8053. resegment(symbols[p->second.first], output);
  8054. resegment(symbols[p->second.second], output);
  8055. }
  8056. void try_add_bigram(int left, int right) {
  8057. if (left == -1 || right == -1) {
  8058. return;
  8059. }
  8060. const std::string text = std::string(symbols[left].text, symbols[left].n + symbols[right].n);
  8061. auto token = vocab.token_to_id.find(text);
  8062. if (token == vocab.token_to_id.end()) {
  8063. return;
  8064. }
  8065. if (static_cast<size_t>((*token).second) >= vocab.id_to_token.size()) {
  8066. return;
  8067. }
  8068. const auto & tok_data = vocab.id_to_token[(*token).second];
  8069. llm_bigram_spm bigram;
  8070. bigram.left = left;
  8071. bigram.right = right;
  8072. bigram.score = tok_data.score;
  8073. bigram.size = text.size();
  8074. work_queue.push(bigram);
  8075. // Do we need to support is_unused?
  8076. rev_merge[text] = std::make_pair(left, right);
  8077. }
  8078. const llama_vocab & vocab;
  8079. std::vector<llm_symbol> symbols;
  8080. llm_bigram_spm::queue work_queue;
  8081. std::map<std::string, std::pair<int, int>> rev_merge;
  8082. };
  8083. // BPE tokenizer
  8084. // adapted from https://github.com/cmp-nct/ggllm.cpp [MIT License]
  8085. // tried to simplify unicode stuff, so most likely does not work 100% correctly!
  8086. // TODO: there are a lot of common parts between spm and bpe tokenizers, should be refactored and reused
  8087. struct llm_bigram_bpe {
  8088. struct comparator {
  8089. bool operator()(const llm_bigram_bpe & l, const llm_bigram_bpe & r) const {
  8090. return l.rank > r.rank || (l.rank == r.rank && l.left > r.left);
  8091. }
  8092. };
  8093. using queue_storage = std::vector<llm_bigram_bpe>;
  8094. using queue = std::priority_queue<llm_bigram_bpe, queue_storage, comparator>;
  8095. llm_symbol::index left;
  8096. llm_symbol::index right;
  8097. std::string text;
  8098. int rank;
  8099. size_t size;
  8100. };
  8101. struct llm_tokenizer_bpe {
  8102. llm_tokenizer_bpe(const llama_vocab & vocab): vocab(vocab) {}
  8103. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  8104. int final_prev_index = -1;
  8105. auto word_collection = bpe_gpt2_preprocess(text);
  8106. symbols_final.clear();
  8107. for (auto & word : word_collection) {
  8108. work_queue = llm_bigram_bpe::queue();
  8109. symbols.clear();
  8110. int index = 0;
  8111. size_t offset = 0;
  8112. while (offset < word.size()) {
  8113. llm_symbol sym;
  8114. size_t char_len = std::min(word.size() - offset, (size_t) ::utf8_len(word[offset]));
  8115. sym.text = word.c_str() + offset;
  8116. sym.n = char_len;
  8117. offset += sym.n;
  8118. sym.prev = index - 1;
  8119. sym.next = offset == word.size() ? -1 : index + 1;
  8120. index++;
  8121. symbols.emplace_back(sym);
  8122. }
  8123. for (size_t i = 1; i < symbols.size(); ++i) {
  8124. add_new_bigram(i - 1, i);
  8125. }
  8126. // build token(s)
  8127. while (!work_queue.empty()) {
  8128. auto bigram = work_queue.top();
  8129. work_queue.pop();
  8130. auto & left_symbol = symbols[bigram.left];
  8131. auto & right_symbol = symbols[bigram.right];
  8132. if (left_symbol.n == 0 || right_symbol.n == 0) {
  8133. continue;
  8134. }
  8135. std::string left_token = std::string(left_symbol.text, left_symbol.n);
  8136. std::string right_token = std::string(right_symbol.text, right_symbol.n);
  8137. if (left_token + right_token != bigram.text) {
  8138. continue; // Skip this bigram if it's outdated
  8139. }
  8140. // merge the right sym into the left one
  8141. left_symbol.n += right_symbol.n;
  8142. right_symbol.n = 0;
  8143. // remove the right sym from the chain
  8144. left_symbol.next = right_symbol.next;
  8145. if (right_symbol.next >= 0) {
  8146. symbols[right_symbol.next].prev = bigram.left;
  8147. }
  8148. add_new_bigram(left_symbol.prev, bigram.left); // left side of current symbol
  8149. add_new_bigram(bigram.left, left_symbol.next); // right side of current symbol
  8150. }
  8151. // add the fnished tokens to the final list keeping correct order for next and prev
  8152. for (auto & sym : symbols) {
  8153. if (sym.n > 0) {
  8154. sym.prev = final_prev_index;
  8155. sym.next = -1;
  8156. if (final_prev_index != -1) {
  8157. symbols_final[final_prev_index].next = symbols_final.size();
  8158. }
  8159. symbols_final.emplace_back(sym);
  8160. final_prev_index = symbols_final.size() - 1;
  8161. }
  8162. }
  8163. }
  8164. symbols = symbols_final;
  8165. if (!symbols.empty()) {
  8166. for (int i = 0; i != -1; i = symbols[i].next) {
  8167. auto & symbol = symbols[i];
  8168. if (symbol.n == 0) {
  8169. continue;
  8170. }
  8171. const std::string str = std::string(symbol.text, symbol.n);
  8172. const auto token = vocab.token_to_id.find(str);
  8173. if (token == vocab.token_to_id.end()) {
  8174. for (auto j = str.begin(); j != str.end(); ++j) {
  8175. std::string byte_str(1, *j);
  8176. auto token_multibyte = vocab.token_to_id.find(byte_str);
  8177. if (token_multibyte == vocab.token_to_id.end()) {
  8178. throw std::runtime_error("ERROR: byte not found in vocab");
  8179. }
  8180. output.push_back((*token_multibyte).second);
  8181. }
  8182. } else {
  8183. output.push_back((*token).second);
  8184. }
  8185. }
  8186. }
  8187. }
  8188. private:
  8189. void add_new_bigram(int left, int right) {
  8190. if (left == -1 || right == -1) {
  8191. return;
  8192. }
  8193. std::string left_token = std::string(symbols[left].text, symbols[left].n);
  8194. std::string right_token = std::string(symbols[right].text, symbols[right].n);
  8195. int rank_found = -1;
  8196. rank_found = vocab.find_bpe_rank(left_token, right_token);
  8197. if (rank_found < 0) {
  8198. return;
  8199. }
  8200. llm_bigram_bpe bigram;
  8201. bigram.left = left;
  8202. bigram.right = right;
  8203. bigram.text = left_token + right_token;
  8204. bigram.size = left_token.size() + right_token.size();
  8205. bigram.rank = rank_found;
  8206. work_queue.push(bigram);
  8207. }
  8208. std::vector<std::string> bpe_gpt2_preprocess(const std::string & text) {
  8209. std::vector<std::string> bpe_words;
  8210. std::vector<std::string> bpe_encoded_words;
  8211. std::string token = "";
  8212. // GPT2 system regex: 's|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+
  8213. bool collecting_numeric = false;
  8214. bool collecting_letter = false;
  8215. bool collecting_special = false;
  8216. bool collecting_whitespace_lookahead = false;
  8217. bool collecting = false;
  8218. std::vector<std::string> text_utf;
  8219. text_utf.reserve(text.size());
  8220. bpe_words.reserve(text.size());
  8221. bpe_encoded_words.reserve(text.size());
  8222. const auto cpts = unicode_cpts_from_utf8(text);
  8223. for (size_t i = 0; i < cpts.size(); ++i)
  8224. text_utf.emplace_back(unicode_cpt_to_utf8(cpts[i]));
  8225. for (int i = 0; i < (int)text_utf.size(); i++) {
  8226. const std::string & utf_char = text_utf[i];
  8227. bool split_condition = false;
  8228. int bytes_remain = text_utf.size() - i;
  8229. // forward backward lookups
  8230. const std::string & utf_char_next = (i + 1 < (int)text_utf.size()) ? text_utf[i + 1] : "";
  8231. const std::string & utf_char_next_next = (i + 2 < (int)text_utf.size()) ? text_utf[i + 2] : "";
  8232. // handling contractions
  8233. if (!split_condition && bytes_remain >= 2) {
  8234. // 's|'t|'m|'d
  8235. if (utf_char == "\'" && (utf_char_next == "s" || utf_char_next == "t" || utf_char_next == "m" || utf_char_next == "d")) {
  8236. split_condition = true;
  8237. }
  8238. if (split_condition) {
  8239. if (token.size()) {
  8240. bpe_words.emplace_back(token); // push previous content as token
  8241. }
  8242. token = utf_char + utf_char_next;
  8243. bpe_words.emplace_back(token);
  8244. token = "";
  8245. i++;
  8246. continue;
  8247. }
  8248. }
  8249. if (!split_condition && bytes_remain >= 3) {
  8250. // 're|'ve|'ll
  8251. if (utf_char == "\'" && (
  8252. (utf_char_next == "r" && utf_char_next_next == "e") ||
  8253. (utf_char_next == "v" && utf_char_next_next == "e") ||
  8254. (utf_char_next == "l" && utf_char_next_next == "l"))
  8255. ) {
  8256. split_condition = true;
  8257. }
  8258. if (split_condition) {
  8259. // current token + next token can be defined
  8260. if (token.size()) {
  8261. bpe_words.emplace_back(token); // push previous content as token
  8262. }
  8263. token = utf_char + utf_char_next + utf_char_next_next;
  8264. bpe_words.emplace_back(token); // the contraction
  8265. token = "";
  8266. i += 2;
  8267. continue;
  8268. }
  8269. }
  8270. if (!split_condition && !collecting) {
  8271. if (unicode_cpt_type(utf_char) == CODEPOINT_TYPE_LETTER || (!token.size() && utf_char == " " && unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_LETTER)) {
  8272. collecting_letter = true;
  8273. collecting = true;
  8274. }
  8275. else if (unicode_cpt_type(utf_char) == CODEPOINT_TYPE_DIGIT || (!token.size() && utf_char == " " && unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  8276. collecting_numeric = true;
  8277. collecting = true;
  8278. }
  8279. else if (
  8280. ((unicode_cpt_type(utf_char) != CODEPOINT_TYPE_LETTER && unicode_cpt_type(utf_char) != CODEPOINT_TYPE_DIGIT) && (unicode_cpt_type(utf_char) != CODEPOINT_TYPE_WHITESPACE)) ||
  8281. (!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)
  8282. ) {
  8283. collecting_special = true;
  8284. collecting = true;
  8285. }
  8286. else if (unicode_cpt_type(utf_char) == CODEPOINT_TYPE_WHITESPACE && unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_WHITESPACE) {
  8287. collecting_whitespace_lookahead = true;
  8288. collecting = true;
  8289. }
  8290. else if (unicode_cpt_type(utf_char) == CODEPOINT_TYPE_WHITESPACE) {
  8291. split_condition = true;
  8292. }
  8293. }
  8294. else if (!split_condition && collecting) {
  8295. if (collecting_letter && unicode_cpt_type(utf_char) != CODEPOINT_TYPE_LETTER) {
  8296. split_condition = true;
  8297. }
  8298. else if (collecting_numeric && unicode_cpt_type(utf_char) != CODEPOINT_TYPE_DIGIT) {
  8299. split_condition = true;
  8300. }
  8301. 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)) {
  8302. split_condition = true;
  8303. }
  8304. else if (collecting_whitespace_lookahead && (unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_LETTER || unicode_cpt_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  8305. split_condition = true;
  8306. }
  8307. }
  8308. if (utf_char_next == "") {
  8309. split_condition = true; // final
  8310. token += utf_char;
  8311. }
  8312. if (split_condition) {
  8313. if (token.size()) {
  8314. bpe_words.emplace_back(token);
  8315. }
  8316. token = utf_char;
  8317. collecting = false;
  8318. collecting_letter = false;
  8319. collecting_numeric = false;
  8320. collecting_special = false;
  8321. collecting_whitespace_lookahead = false;
  8322. }
  8323. else {
  8324. token += utf_char;
  8325. }
  8326. }
  8327. for (std::string & word : bpe_words) {
  8328. std::string encoded_token = "";
  8329. for (char & c : word) {
  8330. encoded_token += unicode_byte_to_utf8(c);
  8331. }
  8332. bpe_encoded_words.emplace_back(encoded_token);
  8333. }
  8334. return bpe_encoded_words;
  8335. }
  8336. const llama_vocab & vocab;
  8337. std::vector<llm_symbol> symbols;
  8338. std::vector<llm_symbol> symbols_final;
  8339. llm_bigram_bpe::queue work_queue;
  8340. };
  8341. struct llm_tokenizer_wpm {
  8342. llm_tokenizer_wpm(const llama_vocab & vocab): vocab(vocab) {}
  8343. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  8344. auto * token_map = &vocab.token_to_id;
  8345. // normalize and split by whitespace
  8346. std::vector<std::string> words = preprocess(text);
  8347. // bos token prepended already
  8348. // find the longest tokens that form the words
  8349. for (const std::string &word : words) {
  8350. // skip empty words
  8351. if (word.size() == 0) {
  8352. continue;
  8353. }
  8354. // prepend phantom space
  8355. std::string word1 = "\xe2\x96\x81" + word;
  8356. int n = word1.size();
  8357. // we're at the start of a new word
  8358. int i = 0;
  8359. bool match_any = false;
  8360. // move through character position in word
  8361. while (i < n) {
  8362. // loop through possible match length
  8363. bool match = false;
  8364. for (int j = n; j > i; j--) {
  8365. auto it = token_map->find(word1.substr(i, j - i));
  8366. if (it != token_map->end()) {
  8367. output.push_back(it->second);
  8368. match = true;
  8369. match_any = true;
  8370. i = j;
  8371. break;
  8372. }
  8373. }
  8374. // must be an unknown character
  8375. if (!match) {
  8376. i++;
  8377. }
  8378. }
  8379. // we didn't find any matches for this word
  8380. if (!match_any) {
  8381. output.push_back(vocab.special_unk_id);
  8382. }
  8383. }
  8384. // append eos token
  8385. output.push_back(vocab.special_eos_id);
  8386. }
  8387. std::vector<std::string> preprocess(const std::string & text) {
  8388. std::vector<uint32_t> cpts_nfd = unicode_cpts_normalize_nfd(unicode_cpts_from_utf8(text));
  8389. // strip accents, strip control, uniformize whitespace,
  8390. // to lowercase, pad chinese characters, pad punctuation
  8391. std::string new_str = "";
  8392. for (uint32_t code : cpts_nfd) {
  8393. int type = unicode_cpt_type(code);
  8394. if (type == CODEPOINT_TYPE_ACCENT_MARK || type == CODEPOINT_TYPE_CONTROL) {
  8395. continue;
  8396. }
  8397. code = to_lower(code);
  8398. if (type == CODEPOINT_TYPE_WHITESPACE) {
  8399. code = ' ';
  8400. }
  8401. std::string s = unicode_cpt_to_utf8(code);
  8402. if (type == CODEPOINT_TYPE_PUNCTUATION || is_ascii_punct(code) || is_chinese_char(code)) {
  8403. new_str += " ";
  8404. new_str += s;
  8405. new_str += " ";
  8406. } else {
  8407. new_str += s;
  8408. }
  8409. }
  8410. // split by whitespace
  8411. uint64_t l = 0;
  8412. uint64_t r = 0;
  8413. std::vector<std::string> words;
  8414. while (r < new_str.size()) {
  8415. // if is whitespace
  8416. if (isspace(new_str[r])) {
  8417. if (r > l) words.push_back(new_str.substr(l, (r - l)));
  8418. l = r + 1;
  8419. r = l;
  8420. } else {
  8421. r += 1;
  8422. }
  8423. }
  8424. if (r > l) {
  8425. words.push_back(new_str.substr(l, (r - l)));
  8426. }
  8427. return words;
  8428. }
  8429. uint32_t to_lower(uint32_t code) {
  8430. static const std::locale locale("en_US.UTF-8");
  8431. #if defined(_WIN32)
  8432. if (code > 0xFFFF) {
  8433. return code;
  8434. }
  8435. #endif
  8436. return std::tolower(wchar_t(code), locale);
  8437. }
  8438. bool is_ascii_punct(uint32_t code) {
  8439. return code < 256 && ispunct(code);
  8440. }
  8441. bool is_chinese_char(uint32_t cpt) {
  8442. if ((cpt >= 0x4E00 && cpt <= 0x9FFF) ||
  8443. (cpt >= 0x3400 && cpt <= 0x4DBF) ||
  8444. (cpt >= 0x20000 && cpt <= 0x2A6DF) ||
  8445. (cpt >= 0x2A700 && cpt <= 0x2B73F) ||
  8446. (cpt >= 0x2B740 && cpt <= 0x2B81F) ||
  8447. (cpt >= 0x2B920 && cpt <= 0x2CEAF) || // this should be 0x2B820 but in hf rust code it is 0x2B920
  8448. (cpt >= 0xF900 && cpt <= 0xFAFF) ||
  8449. (cpt >= 0x2F800 && cpt <= 0x2FA1F) ||
  8450. (cpt >= 0x3000 && cpt <= 0x303F) ||
  8451. (cpt >= 0xFF00 && cpt <= 0xFFEF)) {
  8452. return true; // NOLINT
  8453. }
  8454. return false;
  8455. }
  8456. const llama_vocab & vocab;
  8457. };
  8458. typedef enum FRAGMENT_BUFFER_VARIANT_TYPE {
  8459. FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN,
  8460. FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT
  8461. } FRAGMENT_BUFFER_VARIANT_TYPE;
  8462. struct fragment_buffer_variant {
  8463. fragment_buffer_variant(llama_vocab::id _token)
  8464. :
  8465. type(FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN),
  8466. token(_token),
  8467. raw_text(_dummy),
  8468. offset(0),
  8469. length(0) {}
  8470. fragment_buffer_variant(const std::string & _raw_text, int64_t _offset, int64_t _length)
  8471. :
  8472. type(FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT),
  8473. token((llama_vocab::id) - 1),
  8474. raw_text(_raw_text),
  8475. offset(_offset),
  8476. length(_length){
  8477. GGML_ASSERT(_offset >= 0);
  8478. GGML_ASSERT(_length >= 1);
  8479. GGML_ASSERT(offset + length <= raw_text.length());
  8480. }
  8481. const FRAGMENT_BUFFER_VARIANT_TYPE type;
  8482. const llama_vocab::id token;
  8483. const std::string _dummy;
  8484. const std::string & raw_text;
  8485. const uint64_t offset;
  8486. const uint64_t length;
  8487. };
  8488. // #define PRETOKENIZERDEBUG
  8489. static void tokenizer_st_partition(const llama_vocab & vocab, std::forward_list<fragment_buffer_variant> & buffer) {
  8490. // for each special token
  8491. for (const auto & st: vocab.special_tokens_cache) {
  8492. const auto & special_token = st.first;
  8493. const auto & special_id = st.second;
  8494. // for each text fragment
  8495. std::forward_list<fragment_buffer_variant>::iterator it = buffer.begin();
  8496. while (it != buffer.end()) {
  8497. auto & fragment = (*it);
  8498. // if a fragment is text ( not yet processed )
  8499. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  8500. auto * raw_text = &(fragment.raw_text);
  8501. auto raw_text_base_offset = fragment.offset;
  8502. auto raw_text_base_length = fragment.length;
  8503. // loop over the text
  8504. while (true) {
  8505. // find the first occurrence of a given special token in this fragment
  8506. // passing offset argument only limit the "search area" but match coordinates
  8507. // are still relative to the source full raw_text
  8508. auto match = raw_text->find(special_token, raw_text_base_offset);
  8509. // no occurrences found, stop processing this fragment for a given special token
  8510. if (match == std::string::npos) break;
  8511. // check if match is within bounds of offset <-> length
  8512. if (match + special_token.length() > raw_text_base_offset + raw_text_base_length) break;
  8513. #ifdef PRETOKENIZERDEBUG
  8514. 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());
  8515. #endif
  8516. auto source = std::distance(buffer.begin(), it);
  8517. // if match is further than base offset
  8518. // then we have some text to the left of it
  8519. if (match > raw_text_base_offset) {
  8520. // left
  8521. const int64_t left_reminder_offset = raw_text_base_offset + 0;
  8522. const int64_t left_reminder_length = match - raw_text_base_offset;
  8523. buffer.emplace_after(it, (*raw_text), left_reminder_offset, left_reminder_length);
  8524. #ifdef PRETOKENIZERDEBUG
  8525. 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());
  8526. #endif
  8527. it++;
  8528. }
  8529. // special token
  8530. buffer.emplace_after(it, special_id);
  8531. it++;
  8532. // right
  8533. if (match + special_token.length() < raw_text_base_offset + raw_text_base_length) {
  8534. const int64_t right_reminder_offset = match + special_token.length();
  8535. const int64_t right_reminder_length = raw_text_base_length - ((match - raw_text_base_offset) + special_token.length());
  8536. buffer.emplace_after(it, (*raw_text), right_reminder_offset, right_reminder_length);
  8537. #ifdef PRETOKENIZERDEBUG
  8538. 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());
  8539. #endif
  8540. it++;
  8541. if (source == 0) {
  8542. buffer.erase_after(buffer.before_begin());
  8543. } else {
  8544. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  8545. }
  8546. // repeat for the right side
  8547. raw_text_base_offset = right_reminder_offset;
  8548. raw_text_base_length = right_reminder_length;
  8549. #ifdef PRETOKENIZERDEBUG
  8550. 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());
  8551. #endif
  8552. } else {
  8553. if (source == 0) {
  8554. buffer.erase_after(buffer.before_begin());
  8555. } else {
  8556. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  8557. }
  8558. break;
  8559. }
  8560. }
  8561. }
  8562. it++;
  8563. }
  8564. }
  8565. }
  8566. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special) {
  8567. std::vector<llama_vocab::id> output;
  8568. // OG tokenizer behavior:
  8569. //
  8570. // tokenizer.encode('', add_bos=True) returns [1]
  8571. // tokenizer.encode('', add_bos=False) returns []
  8572. if (bos && vocab.special_bos_id != -1) {
  8573. output.push_back(vocab.special_bos_id);
  8574. }
  8575. if (raw_text.empty()) {
  8576. return output;
  8577. }
  8578. std::forward_list<fragment_buffer_variant> fragment_buffer;
  8579. fragment_buffer.emplace_front(raw_text, 0, raw_text.length());
  8580. if (special) tokenizer_st_partition(vocab, fragment_buffer);
  8581. switch (vocab.type) {
  8582. case LLAMA_VOCAB_TYPE_SPM:
  8583. {
  8584. for (const auto & fragment : fragment_buffer) {
  8585. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  8586. // without adding this leading whitespace, we do not get the same results as the original tokenizer
  8587. // TODO: It's likely possible to get rid of this string copy entirely
  8588. // by modifying llm_tokenizer_x to operate with string offsets like pre-tokenizer
  8589. // and passing 'add space prefix' as bool argument
  8590. //
  8591. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  8592. if (&fragment == &fragment_buffer.front()) {
  8593. if (vocab.add_space_prefix) {
  8594. raw_text = " " + raw_text; // prefix with space if the first token is not special
  8595. }
  8596. }
  8597. #ifdef PRETOKENIZERDEBUG
  8598. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  8599. #endif
  8600. llm_tokenizer_spm tokenizer(vocab);
  8601. llama_escape_whitespace(raw_text);
  8602. tokenizer.tokenize(raw_text, output);
  8603. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  8604. output.push_back(fragment.token);
  8605. }
  8606. }
  8607. } break;
  8608. case LLAMA_VOCAB_TYPE_BPE:
  8609. {
  8610. for (const auto & fragment : fragment_buffer) {
  8611. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  8612. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  8613. #ifdef PRETOKENIZERDEBUG
  8614. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  8615. #endif
  8616. llm_tokenizer_bpe tokenizer(vocab);
  8617. tokenizer.tokenize(raw_text, output);
  8618. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  8619. output.push_back(fragment.token);
  8620. }
  8621. }
  8622. } break;
  8623. case LLAMA_VOCAB_TYPE_WPM:
  8624. {
  8625. for (const auto & fragment : fragment_buffer) {
  8626. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  8627. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  8628. #ifdef PRETOKENIZERDEBUG
  8629. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  8630. #endif
  8631. llm_tokenizer_wpm tokenizer(vocab);
  8632. tokenizer.tokenize(raw_text, output);
  8633. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  8634. output.push_back(fragment.token);
  8635. }
  8636. }
  8637. } break;
  8638. case LLAMA_VOCAB_TYPE_NONE:
  8639. GGML_ASSERT(false);
  8640. }
  8641. return output;
  8642. }
  8643. //
  8644. // grammar - internal
  8645. //
  8646. struct llama_partial_utf8 {
  8647. uint32_t value; // bit value so far (unshifted)
  8648. int n_remain; // num bytes remaining; -1 indicates invalid sequence
  8649. };
  8650. struct llama_grammar {
  8651. const std::vector<std::vector<llama_grammar_element>> rules;
  8652. std::vector<std::vector<const llama_grammar_element *>> stacks;
  8653. // buffer for partially generated UTF-8 sequence from accepted tokens
  8654. llama_partial_utf8 partial_utf8;
  8655. };
  8656. struct llama_grammar_candidate {
  8657. size_t index;
  8658. const uint32_t * code_points;
  8659. llama_partial_utf8 partial_utf8;
  8660. };
  8661. // Decodes a UTF-8 string which may end in an incomplete sequence. Adds a terminating 0 for use as
  8662. // pointer. If an invalid sequence is encountered, returns `llama_partial_utf8.n_remain == -1`.
  8663. static std::pair<std::vector<uint32_t>, llama_partial_utf8> decode_utf8(
  8664. const std::string & src,
  8665. llama_partial_utf8 partial_start) {
  8666. static const int lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 3, 4 };
  8667. const char * pos = src.c_str();
  8668. std::vector<uint32_t> code_points;
  8669. // common english strings have the same number of codepoints and bytes. `+ 1` for the terminating 0.
  8670. code_points.reserve(src.size() + 1);
  8671. uint32_t value = partial_start.value;
  8672. int n_remain = partial_start.n_remain;
  8673. // continue previous decode, if applicable
  8674. while (*pos != 0 && n_remain > 0) {
  8675. uint8_t next_byte = static_cast<uint8_t>(*pos);
  8676. if ((next_byte >> 6) != 2) {
  8677. // invalid sequence, abort
  8678. code_points.push_back(0);
  8679. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, -1 });
  8680. }
  8681. value = (value << 6) + (next_byte & 0x3F);
  8682. ++pos;
  8683. --n_remain;
  8684. }
  8685. if (partial_start.n_remain > 0 && n_remain == 0) {
  8686. code_points.push_back(value);
  8687. }
  8688. // decode any subsequent utf-8 sequences, which may end in an incomplete one
  8689. while (*pos != 0) {
  8690. uint8_t first_byte = static_cast<uint8_t>(*pos);
  8691. uint8_t highbits = first_byte >> 4;
  8692. n_remain = lookup[highbits] - 1;
  8693. if (n_remain < 0) {
  8694. // invalid sequence, abort
  8695. code_points.clear();
  8696. code_points.push_back(0);
  8697. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, n_remain });
  8698. }
  8699. uint8_t mask = (1 << (7 - n_remain)) - 1;
  8700. value = first_byte & mask;
  8701. ++pos;
  8702. while (*pos != 0 && n_remain > 0) {
  8703. value = (value << 6) + (static_cast<uint8_t>(*pos) & 0x3F);
  8704. ++pos;
  8705. --n_remain;
  8706. }
  8707. if (n_remain == 0) {
  8708. code_points.push_back(value);
  8709. }
  8710. }
  8711. code_points.push_back(0);
  8712. return std::make_pair(std::move(code_points), llama_partial_utf8{ value, n_remain });
  8713. }
  8714. // returns true iff pos points to the end of one of the definitions of a rule
  8715. static bool llama_grammar_is_end_of_sequence(const llama_grammar_element * pos) {
  8716. switch (pos->type) {
  8717. case LLAMA_GRETYPE_END: return true; // NOLINT
  8718. case LLAMA_GRETYPE_ALT: return true; // NOLINT
  8719. default: return false;
  8720. }
  8721. }
  8722. // returns true iff chr satisfies the char range at pos (regular or inverse range)
  8723. // asserts that pos is pointing to a char range element
  8724. static std::pair<bool, const llama_grammar_element *> llama_grammar_match_char(
  8725. const llama_grammar_element * pos,
  8726. const uint32_t chr) {
  8727. bool found = false;
  8728. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  8729. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT); // NOLINT
  8730. do {
  8731. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  8732. // inclusive range, e.g. [a-z]
  8733. found = found || (pos->value <= chr && chr <= pos[1].value);
  8734. pos += 2;
  8735. } else {
  8736. // exact char match, e.g. [a] or "a"
  8737. found = found || pos->value == chr;
  8738. pos += 1;
  8739. }
  8740. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  8741. return std::make_pair(found == is_positive_char, pos);
  8742. }
  8743. // returns true iff some continuation of the given partial UTF-8 sequence could satisfy the char
  8744. // range at pos (regular or inverse range)
  8745. // asserts that pos is pointing to a char range element
  8746. static bool llama_grammar_match_partial_char(
  8747. const llama_grammar_element * pos,
  8748. const llama_partial_utf8 partial_utf8) {
  8749. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  8750. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT);
  8751. uint32_t partial_value = partial_utf8.value;
  8752. int n_remain = partial_utf8.n_remain;
  8753. // invalid sequence or 7-bit char split across 2 bytes (overlong)
  8754. if (n_remain < 0 || (n_remain == 1 && partial_value < 2)) {
  8755. return false;
  8756. }
  8757. // range of possible code points this partial UTF-8 sequence could complete to
  8758. uint32_t low = partial_value << (n_remain * 6);
  8759. uint32_t high = low | ((1 << (n_remain * 6)) - 1);
  8760. if (low == 0) {
  8761. if (n_remain == 2) {
  8762. low = 1 << 11;
  8763. } else if (n_remain == 3) {
  8764. low = 1 << 16;
  8765. }
  8766. }
  8767. do {
  8768. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  8769. // inclusive range, e.g. [a-z]
  8770. if (pos->value <= high && low <= pos[1].value) {
  8771. return is_positive_char;
  8772. }
  8773. pos += 2;
  8774. } else {
  8775. // exact char match, e.g. [a] or "a"
  8776. if (low <= pos->value && pos->value <= high) {
  8777. return is_positive_char;
  8778. }
  8779. pos += 1;
  8780. }
  8781. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  8782. return !is_positive_char;
  8783. }
  8784. // transforms a grammar pushdown stack into N possible stacks, all ending
  8785. // at a character range (terminal element)
  8786. static void llama_grammar_advance_stack(
  8787. const std::vector<std::vector<llama_grammar_element>> & rules,
  8788. const std::vector<const llama_grammar_element *> & stack,
  8789. std::vector<std::vector<const llama_grammar_element *>> & new_stacks) {
  8790. if (stack.empty()) {
  8791. new_stacks.emplace_back(stack);
  8792. return;
  8793. }
  8794. const llama_grammar_element * pos = stack.back();
  8795. switch (pos->type) {
  8796. case LLAMA_GRETYPE_RULE_REF: {
  8797. const size_t rule_id = static_cast<size_t>(pos->value);
  8798. const llama_grammar_element * subpos = rules[rule_id].data();
  8799. do {
  8800. // init new stack without the top (pos)
  8801. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  8802. if (!llama_grammar_is_end_of_sequence(pos + 1)) {
  8803. // if this rule ref is followed by another element, add that to stack
  8804. new_stack.push_back(pos + 1);
  8805. }
  8806. if (!llama_grammar_is_end_of_sequence(subpos)) {
  8807. // if alternate is nonempty, add to stack
  8808. new_stack.push_back(subpos);
  8809. }
  8810. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  8811. while (!llama_grammar_is_end_of_sequence(subpos)) {
  8812. // scan to end of alternate def
  8813. subpos++;
  8814. }
  8815. if (subpos->type == LLAMA_GRETYPE_ALT) {
  8816. // there's another alternate def of this rule to process
  8817. subpos++;
  8818. } else {
  8819. break;
  8820. }
  8821. } while (true);
  8822. break;
  8823. }
  8824. case LLAMA_GRETYPE_CHAR:
  8825. case LLAMA_GRETYPE_CHAR_NOT:
  8826. new_stacks.emplace_back(stack);
  8827. break;
  8828. default:
  8829. // end of alternate (LLAMA_GRETYPE_END, LLAMA_GRETYPE_ALT) or middle of char range
  8830. // (LLAMA_GRETYPE_CHAR_ALT, LLAMA_GRETYPE_CHAR_RNG_UPPER); stack should never be left on
  8831. // those
  8832. GGML_ASSERT(false);
  8833. }
  8834. }
  8835. // takes a set of possible pushdown stacks on a grammar, which are required to
  8836. // be positioned at a character range (see `llama_grammar_advance_stack`), and
  8837. // produces the N possible stacks if the given char is accepted at those
  8838. // positions
  8839. static std::vector<std::vector<const llama_grammar_element *>> llama_grammar_accept(
  8840. const std::vector<std::vector<llama_grammar_element>> & rules,
  8841. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  8842. const uint32_t chr) {
  8843. std::vector<std::vector<const llama_grammar_element *>> new_stacks;
  8844. for (const auto & stack : stacks) {
  8845. if (stack.empty()) {
  8846. continue;
  8847. }
  8848. auto match = llama_grammar_match_char(stack.back(), chr);
  8849. if (match.first) {
  8850. const llama_grammar_element * pos = match.second;
  8851. // update top of stack to next element, if any
  8852. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  8853. if (!llama_grammar_is_end_of_sequence(pos)) {
  8854. new_stack.push_back(pos);
  8855. }
  8856. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  8857. }
  8858. }
  8859. return new_stacks;
  8860. }
  8861. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  8862. const std::vector<std::vector<llama_grammar_element>> & rules,
  8863. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  8864. const std::vector<llama_grammar_candidate> & candidates);
  8865. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates_for_stack(
  8866. const std::vector<std::vector<llama_grammar_element>> & rules,
  8867. const std::vector<const llama_grammar_element *> & stack,
  8868. const std::vector<llama_grammar_candidate> & candidates) {
  8869. std::vector<llama_grammar_candidate> rejects;
  8870. if (stack.empty()) {
  8871. for (const auto & tok : candidates) {
  8872. if (*tok.code_points != 0 || tok.partial_utf8.n_remain != 0) {
  8873. rejects.push_back(tok);
  8874. }
  8875. }
  8876. return rejects;
  8877. }
  8878. const llama_grammar_element * stack_pos = stack.back();
  8879. std::vector<llama_grammar_candidate> next_candidates;
  8880. for (const auto & tok : candidates) {
  8881. if (*tok.code_points == 0) {
  8882. // reached end of full codepoints in token, reject iff it ended in a partial sequence
  8883. // that cannot satisfy this position in grammar
  8884. if (tok.partial_utf8.n_remain != 0 &&
  8885. !llama_grammar_match_partial_char(stack_pos, tok.partial_utf8)) {
  8886. rejects.push_back(tok);
  8887. }
  8888. } else if (llama_grammar_match_char(stack_pos, *tok.code_points).first) {
  8889. next_candidates.push_back({ tok.index, tok.code_points + 1, tok.partial_utf8 });
  8890. } else {
  8891. rejects.push_back(tok);
  8892. }
  8893. }
  8894. const auto * stack_pos_after = llama_grammar_match_char(stack_pos, 0).second;
  8895. // update top of stack to next element, if any
  8896. std::vector<const llama_grammar_element *> stack_after(stack.begin(), stack.end() - 1);
  8897. if (!llama_grammar_is_end_of_sequence(stack_pos_after)) {
  8898. stack_after.push_back(stack_pos_after);
  8899. }
  8900. std::vector<std::vector<const llama_grammar_element *>> next_stacks;
  8901. llama_grammar_advance_stack(rules, stack_after, next_stacks);
  8902. auto next_rejects = llama_grammar_reject_candidates(rules, next_stacks, next_candidates);
  8903. for (const auto & tok : next_rejects) {
  8904. rejects.push_back({ tok.index, tok.code_points - 1, tok.partial_utf8 });
  8905. }
  8906. return rejects;
  8907. }
  8908. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  8909. const std::vector<std::vector<llama_grammar_element>> & rules,
  8910. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  8911. const std::vector<llama_grammar_candidate> & candidates) {
  8912. GGML_ASSERT(!stacks.empty()); // REVIEW
  8913. if (candidates.empty()) {
  8914. return std::vector<llama_grammar_candidate>();
  8915. }
  8916. auto rejects = llama_grammar_reject_candidates_for_stack(rules, stacks.front(), candidates);
  8917. for (size_t i = 1, size = stacks.size(); i < size; ++i) {
  8918. rejects = llama_grammar_reject_candidates_for_stack(rules, stacks[i], rejects);
  8919. }
  8920. return rejects;
  8921. }
  8922. //
  8923. // grammar - external
  8924. //
  8925. struct llama_grammar * llama_grammar_init(
  8926. const llama_grammar_element ** rules,
  8927. size_t n_rules,
  8928. size_t start_rule_index) {
  8929. const llama_grammar_element * pos;
  8930. // copy rule definitions into vectors
  8931. std::vector<std::vector<llama_grammar_element>> vec_rules(n_rules);
  8932. for (size_t i = 0; i < n_rules; i++) {
  8933. for (pos = rules[i]; pos->type != LLAMA_GRETYPE_END; pos++) {
  8934. vec_rules[i].push_back(*pos);
  8935. }
  8936. vec_rules[i].push_back({LLAMA_GRETYPE_END, 0});
  8937. }
  8938. // loop over alternates of start rule to build initial stacks
  8939. std::vector<std::vector<const llama_grammar_element *>> stacks;
  8940. pos = vec_rules[start_rule_index].data();
  8941. do {
  8942. std::vector<const llama_grammar_element *> stack;
  8943. if (!llama_grammar_is_end_of_sequence(pos)) {
  8944. // if alternate is nonempty, add to stack
  8945. stack.push_back(pos);
  8946. }
  8947. llama_grammar_advance_stack(vec_rules, stack, stacks);
  8948. while (!llama_grammar_is_end_of_sequence(pos)) {
  8949. // scan to end of alternate def
  8950. pos++;
  8951. }
  8952. if (pos->type == LLAMA_GRETYPE_ALT) {
  8953. // there's another alternate def of this rule to process
  8954. pos++;
  8955. } else {
  8956. break;
  8957. }
  8958. } while (true);
  8959. return new llama_grammar{ std::move(vec_rules), std::move(stacks), {} };
  8960. }
  8961. void llama_grammar_free(struct llama_grammar * grammar) {
  8962. delete grammar;
  8963. }
  8964. struct llama_grammar * llama_grammar_copy(const struct llama_grammar * grammar) {
  8965. llama_grammar * result = new llama_grammar{ grammar->rules, grammar->stacks, grammar->partial_utf8 };
  8966. // redirect elements in stacks to point to new rules
  8967. for (size_t is = 0; is < result->stacks.size(); is++) {
  8968. for (size_t ie = 0; ie < result->stacks[is].size(); ie++) {
  8969. for (size_t ir0 = 0; ir0 < grammar->rules.size(); ir0++) {
  8970. for (size_t ir1 = 0; ir1 < grammar->rules[ir0].size(); ir1++) {
  8971. if (grammar->stacks[is][ie] == &grammar->rules[ir0][ir1]) {
  8972. result->stacks[is][ie] = &result->rules[ir0][ir1];
  8973. }
  8974. }
  8975. }
  8976. }
  8977. }
  8978. return result;
  8979. }
  8980. //
  8981. // sampling
  8982. //
  8983. void llama_set_rng_seed(struct llama_context * ctx, uint32_t seed) {
  8984. if (seed == LLAMA_DEFAULT_SEED) {
  8985. seed = time(NULL);
  8986. }
  8987. ctx->rng.seed(seed);
  8988. }
  8989. void llama_sample_softmax(struct llama_context * ctx, llama_token_data_array * candidates) {
  8990. GGML_ASSERT(candidates->size > 0);
  8991. const int64_t t_start_sample_us = ggml_time_us();
  8992. // Sort the logits in descending order
  8993. if (!candidates->sorted) {
  8994. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  8995. return a.logit > b.logit;
  8996. });
  8997. candidates->sorted = true;
  8998. }
  8999. float max_l = candidates->data[0].logit;
  9000. float cum_sum = 0.0f;
  9001. for (size_t i = 0; i < candidates->size; ++i) {
  9002. float p = expf(candidates->data[i].logit - max_l);
  9003. candidates->data[i].p = p;
  9004. cum_sum += p;
  9005. }
  9006. for (size_t i = 0; i < candidates->size; ++i) {
  9007. candidates->data[i].p /= cum_sum;
  9008. }
  9009. if (ctx) {
  9010. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9011. }
  9012. }
  9013. void llama_sample_top_k(struct llama_context * ctx, llama_token_data_array * candidates, int32_t k, size_t min_keep) {
  9014. // TODO: move bucket sort to separate function so that top_p/tail_free/typical/softmax first is equally fast
  9015. // if (k >= (int32_t)candidates->size) {
  9016. // return;
  9017. // }
  9018. const int64_t t_start_sample_us = ggml_time_us();
  9019. if (k <= 0) {
  9020. k = candidates->size;
  9021. }
  9022. k = std::max(k, (int) min_keep);
  9023. k = std::min(k, (int) candidates->size);
  9024. // Sort scores in descending order
  9025. if (!candidates->sorted) {
  9026. auto comp = [](const llama_token_data & a, const llama_token_data & b) {
  9027. return a.logit > b.logit;
  9028. };
  9029. if (k <= 128) {
  9030. std::partial_sort(candidates->data, candidates->data + k, candidates->data + candidates->size, comp);
  9031. } else {
  9032. constexpr int nbuckets = 128;
  9033. constexpr float bucket_low = -10.0f;
  9034. constexpr float bucket_high = 10.0f;
  9035. constexpr float bucket_scale = nbuckets/(bucket_high - bucket_low);
  9036. constexpr float bucker_inter = -bucket_low * bucket_scale;
  9037. std::vector<int> bucket_idx(candidates->size);
  9038. std::vector<int> histo(nbuckets, 0);
  9039. for (int i = 0; i < (int)candidates->size; ++i) {
  9040. const float val = candidates->data[i].logit;
  9041. int ib = int(bucket_scale * val + bucker_inter); //nbuckets * (val - bucket_low) / (bucket_high - bucket_low);
  9042. ib = std::max(0, std::min(nbuckets-1, ib));
  9043. bucket_idx[i] = ib;
  9044. ++histo[ib];
  9045. }
  9046. int nhave = 0;
  9047. int ib = nbuckets - 1;
  9048. for ( ; ib >= 0; --ib) {
  9049. nhave += histo[ib];
  9050. if (nhave >= k) break;
  9051. }
  9052. std::vector<llama_token_data> tmp_tokens(nhave);
  9053. auto ptr = tmp_tokens.data();
  9054. std::vector<llama_token_data*> bucket_ptrs;
  9055. bucket_ptrs.reserve(nbuckets - ib);
  9056. for (int j = nbuckets - 1; j >= ib; --j) {
  9057. bucket_ptrs.push_back(ptr);
  9058. ptr += histo[j];
  9059. }
  9060. for (int i = 0; i < (int)candidates->size; ++i) {
  9061. int j = bucket_idx[i];
  9062. if (j >= ib) {
  9063. *bucket_ptrs[nbuckets-1-j]++ = candidates->data[i];
  9064. }
  9065. }
  9066. ptr = tmp_tokens.data();
  9067. int ndone = 0;
  9068. for (int j = nbuckets-1; j > ib; --j) {
  9069. std::sort(ptr, ptr + histo[j], comp);
  9070. ptr += histo[j];
  9071. ndone += histo[j];
  9072. }
  9073. std::partial_sort(ptr, ptr + k - ndone, ptr + histo[ib], comp);
  9074. std::memcpy(candidates->data, tmp_tokens.data(), k*sizeof(llama_token_data));
  9075. }
  9076. candidates->sorted = true;
  9077. }
  9078. candidates->size = k;
  9079. if (ctx) {
  9080. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9081. }
  9082. }
  9083. void llama_sample_top_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  9084. if (p >= 1.0f) {
  9085. return;
  9086. }
  9087. llama_sample_softmax(ctx, candidates);
  9088. const int64_t t_start_sample_us = ggml_time_us();
  9089. // Compute the cumulative probabilities
  9090. float cum_sum = 0.0f;
  9091. size_t last_idx = candidates->size;
  9092. for (size_t i = 0; i < candidates->size; ++i) {
  9093. cum_sum += candidates->data[i].p;
  9094. // Check if the running sum is at least p or if we have kept at least min_keep tokens
  9095. // we set the last index to i+1 to indicate that the current iterate should be included in the set
  9096. if (cum_sum >= p && i + 1 >= min_keep) {
  9097. last_idx = i + 1;
  9098. break;
  9099. }
  9100. }
  9101. // Resize the output vector to keep only the top-p tokens
  9102. candidates->size = last_idx;
  9103. if (ctx) {
  9104. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9105. }
  9106. }
  9107. void llama_sample_min_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  9108. if (p <= 0.0f || !candidates->size) {
  9109. return;
  9110. }
  9111. const int64_t t_start_sample_us = ggml_time_us();
  9112. bool min_p_applied = false;
  9113. // if the candidates aren't sorted, try the unsorted implementation first
  9114. if (!candidates->sorted) {
  9115. std::vector<llama_token_data> filtered_tokens;
  9116. float max_logit = -FLT_MAX;
  9117. for (size_t i = 0; i < candidates->size; ++i) {
  9118. max_logit = std::max(max_logit, candidates->data[i].logit);
  9119. }
  9120. const float min_logit = max_logit + logf(p); // min logit for p_i >= p * p_max
  9121. for (size_t i = 0; i < candidates->size; ++i) {
  9122. if (candidates->data[i].logit >= min_logit) {
  9123. filtered_tokens.push_back(candidates->data[i]);
  9124. }
  9125. }
  9126. // if we have enough values the operation was a success
  9127. if (filtered_tokens.size() >= min_keep) {
  9128. memcpy(candidates->data, filtered_tokens.data(), filtered_tokens.size()*sizeof(llama_token_data));
  9129. candidates->size = filtered_tokens.size();
  9130. min_p_applied = true;
  9131. }
  9132. }
  9133. // if the candidates are sorted or the unsorted implementation failed, use this implementation
  9134. if (!min_p_applied) {
  9135. // Sort the logits in descending order
  9136. if (!candidates->sorted) {
  9137. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  9138. return a.logit > b.logit;
  9139. });
  9140. candidates->sorted = true;
  9141. }
  9142. const float min_logit = candidates->data[0].logit + logf(p); // min logit for p_i >= p * p_max
  9143. size_t i = 1; // first token always matches
  9144. for (; i < candidates->size; ++i) {
  9145. if (candidates->data[i].logit < min_logit && i >= min_keep) {
  9146. break; // prob too small
  9147. }
  9148. }
  9149. // Resize the output vector to keep only the matching tokens
  9150. candidates->size = i;
  9151. }
  9152. if (ctx) {
  9153. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9154. }
  9155. }
  9156. void llama_sample_tail_free(struct llama_context * ctx, llama_token_data_array * candidates, float z, size_t min_keep) {
  9157. if (z >= 1.0f || candidates->size <= 2) {
  9158. return;
  9159. }
  9160. llama_sample_softmax(nullptr, candidates);
  9161. const int64_t t_start_sample_us = ggml_time_us();
  9162. // Compute the first and second derivatives
  9163. std::vector<float> first_derivatives(candidates->size - 1);
  9164. std::vector<float> second_derivatives(candidates->size - 2);
  9165. for (size_t i = 0; i < first_derivatives.size(); ++i) {
  9166. first_derivatives[i] = candidates->data[i].p - candidates->data[i + 1].p;
  9167. }
  9168. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  9169. second_derivatives[i] = first_derivatives[i] - first_derivatives[i + 1];
  9170. }
  9171. // Calculate absolute value of second derivatives
  9172. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  9173. second_derivatives[i] = std::abs(second_derivatives[i]);
  9174. }
  9175. // Normalize the second derivatives
  9176. {
  9177. const float second_derivatives_sum = std::accumulate(second_derivatives.begin(), second_derivatives.end(), 0.0f);
  9178. if (second_derivatives_sum > 1e-6f) {
  9179. for (float & value : second_derivatives) {
  9180. value /= second_derivatives_sum;
  9181. }
  9182. } else {
  9183. for (float & value : second_derivatives) {
  9184. value = 1.0f / second_derivatives.size();
  9185. }
  9186. }
  9187. }
  9188. float cum_sum = 0.0f;
  9189. size_t last_idx = candidates->size;
  9190. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  9191. cum_sum += second_derivatives[i];
  9192. // Check if the running sum is greater than z or if we have kept at least min_keep tokens
  9193. if (cum_sum > z && i >= min_keep) {
  9194. last_idx = i;
  9195. break;
  9196. }
  9197. }
  9198. // Resize the output vector to keep only the tokens above the tail location
  9199. candidates->size = last_idx;
  9200. if (ctx) {
  9201. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9202. }
  9203. }
  9204. void llama_sample_typical(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  9205. // Reference implementation:
  9206. // https://github.com/huggingface/transformers/compare/main...cimeister:typical-sampling:typical-pr
  9207. if (p >= 1.0f) {
  9208. return;
  9209. }
  9210. // Compute the softmax of logits and calculate entropy
  9211. llama_sample_softmax(nullptr, candidates);
  9212. const int64_t t_start_sample_us = ggml_time_us();
  9213. float entropy = 0.0f;
  9214. for (size_t i = 0; i < candidates->size; ++i) {
  9215. entropy += -candidates->data[i].p * logf(candidates->data[i].p);
  9216. }
  9217. // Compute the absolute difference between negative log probability and entropy for each candidate
  9218. std::vector<float> shifted_scores;
  9219. for (size_t i = 0; i < candidates->size; ++i) {
  9220. float shifted_score = fabsf(-logf(candidates->data[i].p) - entropy);
  9221. shifted_scores.push_back(shifted_score);
  9222. }
  9223. // Sort tokens based on the shifted_scores and their corresponding indices
  9224. std::vector<size_t> indices(candidates->size);
  9225. std::iota(indices.begin(), indices.end(), 0);
  9226. std::sort(indices.begin(), indices.end(), [&](size_t a, size_t b) {
  9227. return shifted_scores[a] < shifted_scores[b];
  9228. });
  9229. // Compute the cumulative probabilities
  9230. float cum_sum = 0.0f;
  9231. size_t last_idx = indices.size();
  9232. for (size_t i = 0; i < indices.size(); ++i) {
  9233. size_t idx = indices[i];
  9234. cum_sum += candidates->data[idx].p;
  9235. // Check if the running sum is greater than typical or if we have kept at least min_keep tokens
  9236. if (cum_sum > p && i >= min_keep - 1) {
  9237. last_idx = i + 1;
  9238. break;
  9239. }
  9240. }
  9241. // Resize the output vector to keep only the locally typical tokens
  9242. std::vector<llama_token_data> new_candidates;
  9243. for (size_t i = 0; i < last_idx; ++i) {
  9244. size_t idx = indices[i];
  9245. new_candidates.push_back(candidates->data[idx]);
  9246. }
  9247. // Replace the data in candidates with the new_candidates data
  9248. std::copy(new_candidates.begin(), new_candidates.end(), candidates->data);
  9249. candidates->size = new_candidates.size();
  9250. candidates->sorted = false;
  9251. if (ctx) {
  9252. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9253. }
  9254. }
  9255. void llama_sample_entropy(struct llama_context * ctx, llama_token_data_array * candidates_p, float min_temp, float max_temp, float exponent_val) {
  9256. const int64_t t_start_sample_us = ggml_time_us();
  9257. // no need to do anything if there is only one (or zero) candidates
  9258. if(candidates_p->size <= 1) {
  9259. return;
  9260. }
  9261. // Calculate maximum possible entropy
  9262. float max_entropy = -logf(1.0f / candidates_p->size);
  9263. llama_sample_softmax(nullptr, candidates_p);
  9264. // Calculate entropy of the softmax probabilities
  9265. float entropy = 0.0f;
  9266. for (size_t i = 0; i < candidates_p->size; ++i) {
  9267. float prob = candidates_p->data[i].p;
  9268. if (prob > 0.0f) { // Ensure no log(0)
  9269. entropy -= prob * logf(prob);
  9270. }
  9271. }
  9272. // Normalize the entropy (max_entropy cannot be 0 here because we checked candidates_p->size != 1 above)
  9273. float normalized_entropy = entropy / max_entropy;
  9274. // Map the normalized entropy to the desired temperature range using the power function
  9275. float dyn_temp = min_temp + (max_temp - min_temp) * powf(normalized_entropy, exponent_val);
  9276. #ifdef DEBUG
  9277. LLAMA_LOG_INFO("Your text maxtemp value is: %f\n", max_temp);
  9278. LLAMA_LOG_INFO("Entropy: %f\n", entropy);
  9279. LLAMA_LOG_INFO("Max Possible Entropy: %f\n", max_entropy);
  9280. LLAMA_LOG_INFO("Normalized Entropy: %f\n", normalized_entropy);
  9281. LLAMA_LOG_INFO("Exponent: %f\n", exponent_val);
  9282. LLAMA_LOG_INFO("Dynamic Temperature (dyn_temp): %f\n", dyn_temp);
  9283. #endif
  9284. // Apply the dynamically calculated temperature scaling
  9285. for (size_t i = 0; i < candidates_p->size; ++i) {
  9286. candidates_p->data[i].logit /= dyn_temp;
  9287. }
  9288. // Re-compute softmax probabilities after scaling logits with dynamic temperature
  9289. double max_l_double = candidates_p->data[0].logit;
  9290. double cum_sum_double = 0.0;
  9291. for (size_t i = 0; i < candidates_p->size; ++i) {
  9292. double p = exp(candidates_p->data[i].logit - max_l_double);
  9293. candidates_p->data[i].p = p; // Store the scaled probability
  9294. cum_sum_double += p;
  9295. }
  9296. for (size_t i = 0; i < candidates_p->size; ++i) {
  9297. candidates_p->data[i].p /= cum_sum_double; // Re-normalize the probabilities
  9298. }
  9299. #ifdef DEBUG
  9300. // Print the updated top 25 probabilities after temperature scaling
  9301. LLAMA_LOG_INFO("\nUpdated Top 25 Probabilities After Dynamic Temperature Scaling (in percentages):\n");
  9302. for (size_t i = 0; i < 25 && i < candidates_p->size; ++i) {
  9303. LLAMA_LOG_INFO("Token %zu: %f%%\n", i + 1, candidates_p->data[i].p * 100.0f);
  9304. }
  9305. #endif
  9306. if (ctx) {
  9307. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9308. }
  9309. }
  9310. void llama_sample_temp(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  9311. const int64_t t_start_sample_us = ggml_time_us();
  9312. for (size_t i = 0; i < candidates_p->size; ++i) {
  9313. candidates_p->data[i].logit /= temp;
  9314. }
  9315. if (ctx) {
  9316. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9317. }
  9318. }
  9319. void llama_sample_repetition_penalties(
  9320. struct llama_context * ctx,
  9321. llama_token_data_array * candidates,
  9322. const llama_token * last_tokens,
  9323. size_t penalty_last_n,
  9324. float penalty_repeat,
  9325. float penalty_freq,
  9326. float penalty_present) {
  9327. if (penalty_last_n == 0 || (penalty_repeat == 1.0f && penalty_freq == 0.0f && penalty_present == 0.0f)) {
  9328. return;
  9329. }
  9330. const int64_t t_start_sample_us = ggml_time_us();
  9331. // Create a frequency map to count occurrences of each token in last_tokens
  9332. std::unordered_map<llama_token, int> token_count;
  9333. for (size_t i = 0; i < penalty_last_n; ++i) {
  9334. token_count[last_tokens[i]]++;
  9335. }
  9336. // Apply frequency and presence penalties to the candidates
  9337. for (size_t i = 0; i < candidates->size; ++i) {
  9338. const auto token_iter = token_count.find(candidates->data[i].id);
  9339. if (token_iter == token_count.end()) {
  9340. continue;
  9341. }
  9342. const int count = token_iter->second;
  9343. // 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.
  9344. // This is common fix for this problem, which is to multiply by the penalty instead of dividing.
  9345. if (candidates->data[i].logit <= 0) {
  9346. candidates->data[i].logit *= penalty_repeat;
  9347. } else {
  9348. candidates->data[i].logit /= penalty_repeat;
  9349. }
  9350. candidates->data[i].logit -= float(count) * penalty_freq + float(count > 0) * penalty_present;
  9351. }
  9352. candidates->sorted = false;
  9353. if (ctx) {
  9354. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9355. }
  9356. }
  9357. void llama_sample_grammar(struct llama_context * ctx, llama_token_data_array * candidates, const struct llama_grammar * grammar) {
  9358. GGML_ASSERT(ctx);
  9359. const int64_t t_start_sample_us = ggml_time_us();
  9360. bool allow_eos = false;
  9361. for (const auto & stack : grammar->stacks) {
  9362. if (stack.empty()) {
  9363. allow_eos = true;
  9364. break;
  9365. }
  9366. }
  9367. const llama_token eos = llama_token_eos(&ctx->model);
  9368. std::vector<std::pair<std::vector<uint32_t>, llama_partial_utf8>> candidates_decoded;
  9369. candidates_decoded.reserve(candidates->size);
  9370. std::vector<llama_grammar_candidate> candidates_grammar;
  9371. candidates_grammar.reserve(candidates->size);
  9372. for (size_t i = 0; i < candidates->size; ++i) {
  9373. const llama_token id = candidates->data[i].id;
  9374. const std::string piece = llama_token_to_piece(ctx, id);
  9375. if (id == eos) {
  9376. if (!allow_eos) {
  9377. candidates->data[i].logit = -INFINITY;
  9378. }
  9379. } else if (piece.empty() || piece[0] == 0) {
  9380. candidates->data[i].logit = -INFINITY;
  9381. } else {
  9382. candidates_decoded.push_back(decode_utf8(piece, grammar->partial_utf8));
  9383. candidates_grammar.push_back({ i, candidates_decoded.back().first.data(), candidates_decoded.back().second });
  9384. }
  9385. }
  9386. const auto rejects = llama_grammar_reject_candidates(grammar->rules, grammar->stacks, candidates_grammar);
  9387. for (const auto & reject : rejects) {
  9388. candidates->data[reject.index].logit = -INFINITY;
  9389. }
  9390. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9391. }
  9392. static void llama_log_softmax(float * array, size_t size) {
  9393. float max_l = *std::max_element(array, array + size);
  9394. float sum = 0.f;
  9395. for (size_t i = 0; i < size; ++i) {
  9396. float p = expf(array[i] - max_l);
  9397. sum += p;
  9398. array[i] = p;
  9399. }
  9400. for (size_t i = 0; i < size; ++i) {
  9401. array[i] = logf(array[i] / sum);
  9402. }
  9403. }
  9404. void llama_sample_apply_guidance(
  9405. struct llama_context * ctx,
  9406. float * logits,
  9407. float * logits_guidance,
  9408. float scale) {
  9409. GGML_ASSERT(ctx);
  9410. const auto t_start_sample_us = ggml_time_us();
  9411. const auto n_vocab = llama_n_vocab(llama_get_model(ctx));
  9412. llama_log_softmax(logits, n_vocab);
  9413. llama_log_softmax(logits_guidance, n_vocab);
  9414. for (int i = 0; i < n_vocab; ++i) {
  9415. auto & l = logits[i];
  9416. const auto & g = logits_guidance[i];
  9417. l = scale * (l - g) + g;
  9418. }
  9419. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9420. }
  9421. llama_token llama_sample_token_mirostat(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, int32_t m, float * mu) {
  9422. GGML_ASSERT(ctx);
  9423. auto N = float(llama_n_vocab(llama_get_model(ctx)));
  9424. int64_t t_start_sample_us;
  9425. t_start_sample_us = ggml_time_us();
  9426. llama_sample_softmax(nullptr, candidates);
  9427. // Estimate s_hat using the most probable m tokens
  9428. float s_hat = 0.0;
  9429. float sum_ti_bi = 0.0;
  9430. float sum_ti_sq = 0.0;
  9431. for (size_t i = 0; i < size_t(m - 1) && i < candidates->size - 1; ++i) {
  9432. float t_i = logf(float(i + 2) / float(i + 1));
  9433. float b_i = logf(candidates->data[i].p / candidates->data[i + 1].p);
  9434. sum_ti_bi += t_i * b_i;
  9435. sum_ti_sq += t_i * t_i;
  9436. }
  9437. s_hat = sum_ti_bi / sum_ti_sq;
  9438. // Compute k from the estimated s_hat and target surprise value
  9439. float epsilon_hat = s_hat - 1;
  9440. float k = powf((epsilon_hat * powf(2, *mu)) / (1 - powf(N, -epsilon_hat)), 1 / s_hat);
  9441. // Sample the next word X using top-k sampling
  9442. llama_sample_top_k(nullptr, candidates, int(k), 1);
  9443. if (ctx) {
  9444. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9445. }
  9446. llama_token X = llama_sample_token(ctx, candidates);
  9447. t_start_sample_us = ggml_time_us();
  9448. // Compute error as the difference between observed surprise and target surprise value
  9449. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  9450. return candidate.id == X;
  9451. }));
  9452. float observed_surprise = -log2f(candidates->data[X_idx].p);
  9453. float e = observed_surprise - tau;
  9454. // Update mu using the learning rate and error
  9455. *mu = *mu - eta * e;
  9456. if (ctx) {
  9457. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9458. }
  9459. return X;
  9460. }
  9461. llama_token llama_sample_token_mirostat_v2(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, float * mu) {
  9462. int64_t t_start_sample_us;
  9463. t_start_sample_us = ggml_time_us();
  9464. llama_sample_softmax(ctx, candidates);
  9465. // Truncate the words with surprise values greater than mu
  9466. candidates->size = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  9467. return -log2f(candidate.p) > *mu;
  9468. }));
  9469. if (candidates->size == 0) {
  9470. candidates->size = 1;
  9471. }
  9472. if (ctx) {
  9473. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9474. }
  9475. // Normalize the probabilities of the remaining words
  9476. llama_sample_softmax(ctx, candidates);
  9477. // Sample the next word X from the remaining words
  9478. llama_token X = llama_sample_token(ctx, candidates);
  9479. t_start_sample_us = ggml_time_us();
  9480. // Compute error as the difference between observed surprise and target surprise value
  9481. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  9482. return candidate.id == X;
  9483. }));
  9484. float observed_surprise = -log2f(candidates->data[X_idx].p);
  9485. float e = observed_surprise - tau;
  9486. // Update mu using the learning rate and error
  9487. *mu = *mu - eta * e;
  9488. if (ctx) {
  9489. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9490. }
  9491. return X;
  9492. }
  9493. llama_token llama_sample_token_greedy(struct llama_context * ctx, llama_token_data_array * candidates) {
  9494. const int64_t t_start_sample_us = ggml_time_us();
  9495. // Find max element
  9496. auto * max_iter = std::max_element(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  9497. return a.logit < b.logit;
  9498. });
  9499. llama_token result = max_iter->id;
  9500. if (ctx) {
  9501. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9502. ctx->n_sample++;
  9503. }
  9504. return result;
  9505. }
  9506. llama_token llama_sample_token(struct llama_context * ctx, llama_token_data_array * candidates) {
  9507. GGML_ASSERT(ctx);
  9508. const int64_t t_start_sample_us = ggml_time_us();
  9509. llama_sample_softmax(nullptr, candidates);
  9510. std::vector<float> probs;
  9511. probs.reserve(candidates->size);
  9512. for (size_t i = 0; i < candidates->size; ++i) {
  9513. probs.push_back(candidates->data[i].p);
  9514. }
  9515. std::discrete_distribution<> dist(probs.begin(), probs.end());
  9516. auto & rng = ctx->rng;
  9517. int idx = dist(rng);
  9518. llama_token result = candidates->data[idx].id;
  9519. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9520. ctx->n_sample++;
  9521. return result;
  9522. }
  9523. void llama_grammar_accept_token(struct llama_context * ctx, struct llama_grammar * grammar, llama_token token) {
  9524. const int64_t t_start_sample_us = ggml_time_us();
  9525. if (token == llama_token_eos(&ctx->model)) {
  9526. for (const auto & stack : grammar->stacks) {
  9527. if (stack.empty()) {
  9528. return;
  9529. }
  9530. }
  9531. GGML_ASSERT(false);
  9532. }
  9533. const std::string piece = llama_token_to_piece(ctx, token);
  9534. // Note terminating 0 in decoded string
  9535. const auto decoded = decode_utf8(piece, grammar->partial_utf8);
  9536. const auto & code_points = decoded.first;
  9537. for (auto it = code_points.begin(), end = code_points.end() - 1; it != end; ++it) {
  9538. grammar->stacks = llama_grammar_accept(grammar->rules, grammar->stacks, *it);
  9539. }
  9540. grammar->partial_utf8 = decoded.second;
  9541. GGML_ASSERT(!grammar->stacks.empty());
  9542. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9543. }
  9544. //
  9545. // Beam search
  9546. //
  9547. struct llama_beam {
  9548. std::vector<llama_token> tokens;
  9549. float p; // Cumulative beam probability (renormalized relative to all beams)
  9550. bool eob; // Initialize end-of-beam to false. Callback sets this to true.
  9551. // Sort beams by probability. In case of ties, prefer beams at eob.
  9552. bool operator<(const llama_beam & rhs) const {
  9553. return std::make_pair(p, eob) < std::make_pair(rhs.p, rhs.eob);
  9554. }
  9555. // Shift off first n tokens and discard them.
  9556. void shift_tokens(const size_t n) {
  9557. if (n) {
  9558. std::copy(tokens.begin() + n, tokens.end(), tokens.begin());
  9559. tokens.resize(tokens.size() - n);
  9560. }
  9561. }
  9562. llama_beam_view view() const { return {tokens.data(), tokens.size(), p, eob}; }
  9563. };
  9564. // A struct for calculating logit-related info.
  9565. struct llama_logit_info {
  9566. const float * const logits;
  9567. const int n_vocab;
  9568. const float max_l;
  9569. const float normalizer;
  9570. struct sum_exp {
  9571. float max_l;
  9572. float operator()(float sum, float l) const { return sum + std::exp(l - max_l); }
  9573. };
  9574. llama_logit_info(llama_context * ctx)
  9575. : logits(llama_get_logits(ctx))
  9576. , n_vocab(llama_n_vocab(llama_get_model(ctx)))
  9577. , max_l(*std::max_element(logits, logits + n_vocab))
  9578. , normalizer(1.0f / std::accumulate(logits, logits + n_vocab, 0.0f, sum_exp{max_l}))
  9579. { }
  9580. llama_token_data get_token_data(const llama_token token_id) const {
  9581. constexpr auto p = std::numeric_limits<float>::quiet_NaN(); // never used
  9582. return {token_id, logits[token_id], p};
  9583. }
  9584. // Return top k token_data by logit.
  9585. std::vector<llama_token_data> top_k(size_t k) {
  9586. std::vector<llama_token_data> min_heap; // min-heap by logit
  9587. const llama_token k_min = std::min(static_cast<llama_token>(k), n_vocab);
  9588. min_heap.reserve(k_min);
  9589. for (llama_token token_id = 0 ; token_id < k_min ; ++token_id) {
  9590. min_heap.push_back(get_token_data(token_id));
  9591. }
  9592. auto comp = [](const llama_token_data & a, const llama_token_data & b) { return a.logit > b.logit; };
  9593. std::make_heap(min_heap.begin(), min_heap.end(), comp);
  9594. for (llama_token token_id = k_min ; token_id < n_vocab ; ++token_id) {
  9595. if (min_heap.front().logit < logits[token_id]) {
  9596. std::pop_heap(min_heap.begin(), min_heap.end(), comp);
  9597. min_heap.back().id = token_id;
  9598. min_heap.back().logit = logits[token_id];
  9599. std::push_heap(min_heap.begin(), min_heap.end(), comp);
  9600. }
  9601. }
  9602. return min_heap;
  9603. }
  9604. float probability_from_logit(float logit) const {
  9605. return normalizer * std::exp(logit - max_l);
  9606. }
  9607. };
  9608. struct llama_beam_search_data {
  9609. llama_context * ctx;
  9610. size_t n_beams;
  9611. int n_past;
  9612. int n_predict;
  9613. std::vector<llama_beam> beams;
  9614. std::vector<llama_beam> next_beams;
  9615. // Re-calculated on each loop iteration
  9616. size_t common_prefix_length;
  9617. // Used to communicate to/from callback on beams state.
  9618. std::vector<llama_beam_view> beam_views;
  9619. llama_beam_search_data(llama_context * ctx, size_t n_beams, int n_past, int n_predict)
  9620. : ctx(ctx)
  9621. , n_beams(n_beams)
  9622. , n_past(n_past)
  9623. , n_predict(n_predict)
  9624. , beam_views(n_beams) {
  9625. beams.reserve(n_beams);
  9626. next_beams.reserve(n_beams);
  9627. }
  9628. // Collapse beams to a single beam given by index.
  9629. void collapse_beams(const size_t beam_idx) {
  9630. if (0u < beam_idx) {
  9631. std::swap(beams[0], beams[beam_idx]);
  9632. }
  9633. beams.resize(1);
  9634. }
  9635. // Min-heaps are used to efficiently collect the top-k elements (k=n_beams).
  9636. // The repetitive patterns below reflect the 2 stages of heaps:
  9637. // * Gather elements until the vector is full, then call std::make_heap() on it.
  9638. // * If the heap is full and a new element is found that should be included, pop the
  9639. // least element to the back(), replace it with the new, then push it into the heap.
  9640. void fill_next_beams_by_top_probabilities(llama_beam & beam) {
  9641. // Min-heaps use a greater-than comparator.
  9642. const auto comp = [](const llama_beam & a, const llama_beam & b) { return a.p > b.p; };
  9643. if (beam.eob) {
  9644. // beam is at end-of-sentence, so just copy it to next_beams if its probability is high enough.
  9645. if (next_beams.size() < n_beams) {
  9646. next_beams.push_back(std::move(beam));
  9647. if (next_beams.size() == n_beams) {
  9648. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  9649. }
  9650. } else if (next_beams.front().p < beam.p) {
  9651. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  9652. next_beams.back() = std::move(beam);
  9653. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  9654. }
  9655. } else {
  9656. // beam is not at end-of-sentence, so branch with next top_k tokens.
  9657. if (!beam.tokens.empty()) {
  9658. llama_decode(ctx, llama_batch_get_one(beam.tokens.data(), beam.tokens.size(), n_past, 0));
  9659. }
  9660. llama_logit_info logit_info(ctx);
  9661. std::vector<llama_token_data> next_tokens = logit_info.top_k(n_beams);
  9662. size_t i=0;
  9663. if (next_beams.size() < n_beams) {
  9664. for (; next_beams.size() < n_beams ; ++i) {
  9665. llama_beam next_beam = beam;
  9666. next_beam.tokens.push_back(next_tokens[i].id);
  9667. next_beam.p *= logit_info.probability_from_logit(next_tokens[i].logit);
  9668. next_beams.push_back(std::move(next_beam));
  9669. }
  9670. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  9671. } else {
  9672. for (; next_beams.front().p == 0.0f ; ++i) {
  9673. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  9674. next_beams.back() = beam;
  9675. next_beams.back().tokens.push_back(next_tokens[i].id);
  9676. next_beams.back().p *= logit_info.probability_from_logit(next_tokens[i].logit);
  9677. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  9678. }
  9679. }
  9680. for (; i < n_beams ; ++i) {
  9681. const float next_p = beam.p * logit_info.probability_from_logit(next_tokens[i].logit);
  9682. if (next_beams.front().p < next_p) {
  9683. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  9684. next_beams.back() = beam;
  9685. next_beams.back().tokens.push_back(next_tokens[i].id);
  9686. next_beams.back().p = next_p;
  9687. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  9688. }
  9689. }
  9690. }
  9691. }
  9692. // Find common_prefix_length based on beams.
  9693. // Requires beams is not empty.
  9694. size_t find_common_prefix_length() {
  9695. size_t common_prefix_length = beams[0].tokens.size();
  9696. for (size_t i = 1 ; i < beams.size() ; ++i) {
  9697. common_prefix_length = std::min(common_prefix_length, beams[i].tokens.size());
  9698. for (size_t j = 0 ; j < common_prefix_length ; ++j) {
  9699. if (beams[0].tokens[j] != beams[i].tokens[j]) {
  9700. common_prefix_length = j;
  9701. break;
  9702. }
  9703. }
  9704. }
  9705. return common_prefix_length;
  9706. }
  9707. // Construct beams_state to send back to caller via the callback function.
  9708. // Side effect: set common_prefix_length = find_common_prefix_length();
  9709. llama_beams_state get_beams_state(const bool last_call) {
  9710. for (size_t i = 0 ; i < beams.size() ; ++i) {
  9711. beam_views[i] = beams[i].view();
  9712. }
  9713. common_prefix_length = find_common_prefix_length();
  9714. return {beam_views.data(), beams.size(), common_prefix_length, last_call};
  9715. }
  9716. // Loop:
  9717. // * while i < n_predict, AND
  9718. // * any of the beams have not yet reached end-of-beam (eob), AND
  9719. // * the highest probability beam(s) (plural in case of ties) are not at end-of-sentence
  9720. // (since all other beam probabilities can only decrease)
  9721. void loop(const llama_beam_search_callback_fn_t callback, void * const callback_data) {
  9722. beams.push_back({{}, 1.0f, false}); // Start with one empty beam w/ probability = 1.0 and !eob.
  9723. const auto not_eob = [](const llama_beam & beam) { return !beam.eob; };
  9724. for (int i = 0 ; i < n_predict && std::any_of(beams.begin(),beams.end(),not_eob) &&
  9725. !beams[top_beam_index()].eob ; ++i) {
  9726. callback(callback_data, get_beams_state(false)); // Sets common_prefix_length
  9727. update_beams_from_beam_views(); // Update values (p,eob) that callback may have changed.
  9728. if (common_prefix_length) {
  9729. llama_decode(ctx, llama_batch_get_one(beams[0].tokens.data(), common_prefix_length, n_past, 0));
  9730. n_past += common_prefix_length;
  9731. }
  9732. // Zero-out next_beam probabilities to place them last in following min-heap.
  9733. std::for_each(next_beams.begin(), next_beams.end(), [](llama_beam & beam) { beam.p = 0.0f; });
  9734. for (llama_beam & beam : beams) {
  9735. beam.shift_tokens(common_prefix_length);
  9736. fill_next_beams_by_top_probabilities(beam);
  9737. }
  9738. // next_beams become the beams of next/final iteration. Swap them to re-use memory.
  9739. beams.swap(next_beams);
  9740. renormalize_beam_probabilities(beams);
  9741. }
  9742. collapse_beams(top_beam_index());
  9743. callback(callback_data, get_beams_state(true));
  9744. }
  9745. // As beams grow, the cumulative probabilities decrease.
  9746. // Renormalize them to avoid floating point underflow.
  9747. static void renormalize_beam_probabilities(std::vector<llama_beam> & beams) {
  9748. const auto sum_p = [](float sum, llama_beam & beam) { return sum + beam.p; };
  9749. const float inv_sum = 1.0f / std::accumulate(beams.begin(), beams.end(), 0.0f, sum_p);
  9750. std::for_each(beams.begin(), beams.end(), [=](llama_beam & beam) { beam.p *= inv_sum; });
  9751. }
  9752. // Assumes beams is non-empty. Uses llama_beam::operator<() for ordering.
  9753. size_t top_beam_index() {
  9754. return std::max_element(beams.begin(), beams.end()) - beams.begin();
  9755. }
  9756. // Copy (p,eob) for each beam which may have been changed by the callback.
  9757. void update_beams_from_beam_views() {
  9758. for (size_t i = 0 ; i < beams.size() ; ++i) {
  9759. beams[i].p = beam_views[i].p;
  9760. beams[i].eob = beam_views[i].eob;
  9761. }
  9762. }
  9763. };
  9764. void llama_beam_search(llama_context * ctx,
  9765. llama_beam_search_callback_fn_t callback, void * callback_data,
  9766. size_t n_beams, int n_past, int n_predict) {
  9767. assert(ctx);
  9768. const int64_t t_start_sample_us = ggml_time_us();
  9769. llama_beam_search_data beam_search_data(ctx, n_beams, n_past, n_predict);
  9770. beam_search_data.loop(callback, callback_data);
  9771. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  9772. ctx->n_sample++;
  9773. }
  9774. //
  9775. // quantization
  9776. //
  9777. struct quantize_state_internal {
  9778. const llama_model & model;
  9779. const llama_model_quantize_params * params;
  9780. int n_attention_wv = 0;
  9781. int n_ffn_down = 0;
  9782. int n_ffn_gate = 0;
  9783. int n_ffn_up = 0;
  9784. int i_attention_wv = 0;
  9785. int i_ffn_down = 0;
  9786. int i_ffn_gate = 0;
  9787. int i_ffn_up = 0;
  9788. int n_k_quantized = 0;
  9789. int n_fallback = 0;
  9790. bool has_imatrix = false;
  9791. // used to figure out if a model shares tok_embd with the output weight
  9792. bool has_output = false;
  9793. quantize_state_internal(const llama_model & model, const llama_model_quantize_params * params)
  9794. : model(model)
  9795. , params(params)
  9796. {}
  9797. };
  9798. static void llama_tensor_dequantize_internal(
  9799. struct ggml_tensor * tensor, std::vector<no_init<float>> & output, std::vector<std::thread> & workers,
  9800. const size_t nelements, const int nthread
  9801. ) {
  9802. if (output.size() < nelements) {
  9803. output.resize(nelements);
  9804. }
  9805. float * f32_output = (float *) output.data();
  9806. ggml_type_traits_t qtype;
  9807. if (ggml_is_quantized(tensor->type)) {
  9808. qtype = ggml_internal_get_type_traits(tensor->type);
  9809. if (qtype.to_float == NULL) {
  9810. throw std::runtime_error(format("type %s unsupported for integer quantization: no dequantization available", ggml_type_name(tensor->type)));
  9811. }
  9812. } else if (tensor->type != GGML_TYPE_F16) {
  9813. throw std::runtime_error(format("cannot dequantize/convert tensor type %s", ggml_type_name(tensor->type)));
  9814. }
  9815. if (nthread < 2) {
  9816. if (tensor->type == GGML_TYPE_F16) {
  9817. ggml_fp16_to_fp32_row((ggml_fp16_t *)tensor->data, f32_output, nelements);
  9818. } else if (ggml_is_quantized(tensor->type)) {
  9819. qtype.to_float(tensor->data, f32_output, nelements);
  9820. } else {
  9821. GGML_ASSERT(false); // unreachable
  9822. }
  9823. return;
  9824. }
  9825. size_t block_size = tensor->type == GGML_TYPE_F16 ? 1 : (size_t)ggml_blck_size(tensor->type);
  9826. size_t block_size_bytes = ggml_type_size(tensor->type);
  9827. GGML_ASSERT(nelements % block_size == 0);
  9828. size_t nblocks = nelements / block_size;
  9829. size_t blocks_per_thread = nblocks / nthread;
  9830. size_t spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count
  9831. size_t in_buff_offs = 0;
  9832. size_t out_buff_offs = 0;
  9833. for (int tnum = 0; tnum < nthread; tnum++) {
  9834. size_t thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread
  9835. size_t thr_elems = thr_blocks * block_size; // number of elements for this thread
  9836. size_t thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread
  9837. auto compute = [qtype] (ggml_type typ, uint8_t * inbuf, float * outbuf, int nels) {
  9838. if (typ == GGML_TYPE_F16) {
  9839. ggml_fp16_to_fp32_row((ggml_fp16_t *)inbuf, outbuf, nels);
  9840. } else {
  9841. qtype.to_float(inbuf, outbuf, nels);
  9842. }
  9843. };
  9844. workers.emplace_back(compute, tensor->type, (uint8_t *) tensor->data + in_buff_offs, f32_output + out_buff_offs, thr_elems);
  9845. in_buff_offs += thr_block_bytes;
  9846. out_buff_offs += thr_elems;
  9847. }
  9848. for (auto & w : workers) { w.join(); }
  9849. workers.clear();
  9850. }
  9851. static ggml_type llama_tensor_get_type(quantize_state_internal & qs, ggml_type new_type, const ggml_tensor * tensor, llama_ftype ftype) {
  9852. const std::string name = ggml_get_name(tensor);
  9853. // TODO: avoid hardcoded tensor names - use the TN_* constants
  9854. const llm_arch arch = qs.model.arch;
  9855. const auto tn = LLM_TN(arch);
  9856. auto use_more_bits = [](int i_layer, int num_layers) -> bool {
  9857. return i_layer < num_layers/8 || i_layer >= 7*num_layers/8 || (i_layer - num_layers/8)%3 == 2;
  9858. };
  9859. const int n_expert = std::max(1, (int)qs.model.hparams.n_expert);
  9860. auto layer_info = [n_expert] (int i_layer, int n_layer, const char * name) {
  9861. if (n_expert > 1) {
  9862. // Believe it or not, "experts" in the FFN of Mixtral-8x7B are not consecutive, but iccasionally randomly
  9863. // sprinkled in the model. Hence, simply dividing i_ffn_down by n_expert does not work
  9864. // for getting the current layer as I initially thought, and we need to resort to parsing the
  9865. // tensor name.
  9866. n_layer /= n_expert;
  9867. if (sscanf(name, "blk.%d.", &i_layer) != 1) {
  9868. throw std::runtime_error(format("Failed to determine layer for tensor %s", name));
  9869. }
  9870. if (i_layer < 0 || i_layer >= n_layer) {
  9871. throw std::runtime_error(format("Bad layer %d for tensor %s. Must be in [0, %d)", i_layer, name, n_layer));
  9872. }
  9873. }
  9874. return std::make_pair(i_layer, n_layer);
  9875. };
  9876. // for arches that share the same tensor between the token embeddings and the output, we quantize the token embeddings
  9877. // with the quantization of the output tensor
  9878. if (name == tn(LLM_TENSOR_OUTPUT, "weight") || (!qs.has_output && name == tn(LLM_TENSOR_TOKEN_EMBD, "weight"))) {
  9879. int nx = tensor->ne[0];
  9880. if (arch == LLM_ARCH_FALCON || nx % QK_K != 0) {
  9881. new_type = GGML_TYPE_Q8_0;
  9882. }
  9883. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  9884. ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) {
  9885. new_type = GGML_TYPE_Q5_K;
  9886. }
  9887. else if (new_type != GGML_TYPE_Q8_0) {
  9888. new_type = GGML_TYPE_Q6_K;
  9889. }
  9890. } else if (name == "token_embd.weight") {
  9891. if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS ||
  9892. ftype == LLAMA_FTYPE_MOSTLY_IQ1_S) {
  9893. new_type = GGML_TYPE_Q2_K;
  9894. }
  9895. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) {
  9896. new_type = GGML_TYPE_IQ3_S;
  9897. }
  9898. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  9899. new_type = GGML_TYPE_IQ3_S;
  9900. }
  9901. } else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S ||
  9902. ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) {
  9903. if (name.find("attn_v.weight") != std::string::npos) {
  9904. if (qs.model.hparams.n_gqa() >= 4 || qs.model.hparams.n_expert >= 4) new_type = GGML_TYPE_Q4_K;
  9905. else new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  9906. ++qs.i_attention_wv;
  9907. }
  9908. else if (qs.model.hparams.n_expert == 8 && name.find("attn_k.weight") != std::string::npos) {
  9909. new_type = GGML_TYPE_Q4_K;
  9910. }
  9911. else if (name.find("ffn_down") != std::string::npos) {
  9912. if (qs.i_ffn_down < qs.n_ffn_down/8) {
  9913. new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  9914. }
  9915. ++qs.i_ffn_down;
  9916. }
  9917. else if (name.find("attn_output.weight") != std::string::npos) {
  9918. if (qs.model.hparams.n_expert == 8) {
  9919. new_type = GGML_TYPE_Q5_K;
  9920. } else {
  9921. if (ftype == LLAMA_FTYPE_MOSTLY_IQ1_S) new_type = GGML_TYPE_IQ2_XXS;
  9922. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) new_type = GGML_TYPE_IQ3_S;
  9923. }
  9924. }
  9925. } else if (name.find("attn_v.weight") != std::string::npos) {
  9926. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) {
  9927. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  9928. }
  9929. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && qs.model.hparams.n_gqa() >= 4) {
  9930. new_type = GGML_TYPE_Q4_K;
  9931. }
  9932. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  9933. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : !qs.has_imatrix ? GGML_TYPE_IQ3_S : GGML_TYPE_IQ3_XXS;
  9934. }
  9935. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_S && qs.model.hparams.n_gqa() >= 4) {
  9936. new_type = GGML_TYPE_Q4_K;
  9937. }
  9938. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  9939. new_type = GGML_TYPE_Q4_K;
  9940. }
  9941. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_S && qs.model.hparams.n_gqa() >= 4) {
  9942. new_type = GGML_TYPE_Q4_K;
  9943. }
  9944. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  9945. new_type = GGML_TYPE_Q4_K;
  9946. }
  9947. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  9948. new_type = qs.i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  9949. }
  9950. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  9951. else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && qs.model.hparams.n_gqa() >= 4) {
  9952. new_type = GGML_TYPE_Q5_K;
  9953. }
  9954. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
  9955. use_more_bits(qs.i_attention_wv, qs.n_attention_wv)) new_type = GGML_TYPE_Q6_K;
  9956. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && qs.i_attention_wv < 4) new_type = GGML_TYPE_Q5_K;
  9957. else if (QK_K == 64 && (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S) &&
  9958. (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;
  9959. if (qs.model.type == MODEL_70B) {
  9960. // In the 70B model we have 8 heads sharing the same attn_v weights. As a result, the attn_v.weight tensor is
  9961. // 8x smaller compared to attn_q.weight. Hence, we can get a nice boost in quantization accuracy with
  9962. // nearly negligible increase in model size by quantizing this tensor with more bits:
  9963. if (new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K) new_type = GGML_TYPE_Q5_K;
  9964. }
  9965. if (qs.model.hparams.n_expert == 8) {
  9966. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  9967. // TODO: explore better strategies
  9968. new_type = GGML_TYPE_Q8_0;
  9969. }
  9970. ++qs.i_attention_wv;
  9971. } else if (name.find("attn_k.weight") != std::string::npos) {
  9972. if (qs.model.hparams.n_expert == 8) {
  9973. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  9974. // TODO: explore better strategies
  9975. new_type = GGML_TYPE_Q8_0;
  9976. }
  9977. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  9978. new_type = GGML_TYPE_IQ3_XXS;
  9979. }
  9980. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  9981. new_type = GGML_TYPE_IQ2_S;
  9982. }
  9983. } else if (name.find("attn_q.weight") != std::string::npos) {
  9984. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  9985. new_type = GGML_TYPE_IQ3_XXS;
  9986. }
  9987. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  9988. new_type = GGML_TYPE_IQ2_S;
  9989. }
  9990. } else if (name.find("ffn_down") != std::string::npos) {
  9991. auto info = layer_info(qs.i_ffn_down, qs.n_ffn_down, name.c_str());
  9992. int i_layer = info.first, n_layer = info.second;
  9993. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  9994. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S) {
  9995. if (i_layer < n_layer/8) new_type = GGML_TYPE_Q4_K;
  9996. }
  9997. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS && !qs.has_imatrix) {
  9998. new_type = i_layer < n_layer/8 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  9999. }
  10000. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  10001. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q5_K
  10002. : arch != LLM_ARCH_FALCON || use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q4_K
  10003. : GGML_TYPE_Q3_K;
  10004. }
  10005. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M && (i_layer < n_layer/8 ||
  10006. (qs.model.hparams.n_expert == 8 && use_more_bits(i_layer, n_layer)))) {
  10007. new_type = GGML_TYPE_Q4_K;
  10008. }
  10009. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) {
  10010. new_type = arch == LLM_ARCH_FALCON ? GGML_TYPE_Q4_K : GGML_TYPE_Q5_K;
  10011. }
  10012. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  10013. if (arch == LLM_ARCH_FALCON) {
  10014. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q6_K :
  10015. use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  10016. } else {
  10017. if (use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  10018. }
  10019. }
  10020. else if (i_layer < n_layer/8 && (ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && !qs.has_imatrix) {
  10021. new_type = GGML_TYPE_Q5_K;
  10022. }
  10023. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M && use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  10024. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && arch != LLM_ARCH_FALCON && i_layer < n_layer/8) {
  10025. new_type = GGML_TYPE_Q5_K;
  10026. }
  10027. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_0 || ftype == LLAMA_FTYPE_MOSTLY_Q5_0)
  10028. && qs.has_imatrix && i_layer < n_layer/8) {
  10029. // Guard against craziness in the first few ffn_down layers that can happen even with imatrix for Q4_0/Q5_0.
  10030. // We only do it when an imatrix is provided because a) we want to make sure that one can always get the
  10031. // same quantization as before imatrix stuff, and b) Q4_1/Q5_1 do go crazy on ffn_down without an imatrix.
  10032. new_type = ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ? GGML_TYPE_Q4_1 : GGML_TYPE_Q5_1;
  10033. }
  10034. ++qs.i_ffn_down;
  10035. } else if (name.find("attn_output.weight") != std::string::npos) {
  10036. if (arch != LLM_ARCH_FALCON) {
  10037. if (qs.model.hparams.n_expert == 8) {
  10038. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  10039. ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL ||
  10040. ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S ||
  10041. ftype == LLAMA_FTYPE_MOSTLY_IQ3_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) {
  10042. new_type = GGML_TYPE_Q5_K;
  10043. }
  10044. } else {
  10045. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K ) new_type = GGML_TYPE_Q3_K;
  10046. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) new_type = GGML_TYPE_IQ3_S;
  10047. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M ) new_type = GGML_TYPE_Q4_K;
  10048. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L ) new_type = GGML_TYPE_Q5_K;
  10049. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M ) new_type = GGML_TYPE_Q4_K;
  10050. }
  10051. } else {
  10052. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  10053. }
  10054. }
  10055. else if (name.find("attn_qkv.weight") != std::string::npos) {
  10056. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L || ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  10057. new_type = GGML_TYPE_Q4_K;
  10058. }
  10059. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) new_type = GGML_TYPE_Q5_K;
  10060. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) new_type = GGML_TYPE_Q6_K;
  10061. }
  10062. else if (name.find("ffn_gate") != std::string::npos) {
  10063. auto info = layer_info(qs.i_ffn_gate, qs.n_ffn_gate, name.c_str());
  10064. int i_layer = info.first, n_layer = info.second;
  10065. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  10066. new_type = GGML_TYPE_IQ3_XXS;
  10067. }
  10068. ++qs.i_ffn_gate;
  10069. }
  10070. else if (name.find("ffn_up") != std::string::npos) {
  10071. auto info = layer_info(qs.i_ffn_up, qs.n_ffn_up, name.c_str());
  10072. int i_layer = info.first, n_layer = info.second;
  10073. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  10074. new_type = GGML_TYPE_IQ3_XXS;
  10075. }
  10076. ++qs.i_ffn_up;
  10077. }
  10078. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  10079. //}
  10080. // IK: let's remove this, else Q2_K is almost the same as Q3_K_S
  10081. //else if (name.find("ffn_gate") != std::string::npos || name.find("ffn_up") != std::string::npos) {
  10082. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  10083. //}
  10084. // This can be used to reduce the size of the Q5_K_S model.
  10085. // The associated PPL increase is fully in line with the size reduction
  10086. //else {
  10087. // if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_S) new_type = GGML_TYPE_Q4_K;
  10088. //}
  10089. bool convert_incompatible_tensor = false;
  10090. if (new_type == GGML_TYPE_Q2_K || new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K ||
  10091. new_type == GGML_TYPE_Q5_K || new_type == GGML_TYPE_Q6_K || new_type == GGML_TYPE_IQ4_XS ||
  10092. new_type == GGML_TYPE_IQ2_XS || new_type == GGML_TYPE_IQ2_XXS || new_type == GGML_TYPE_IQ2_S ||
  10093. new_type == GGML_TYPE_IQ3_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || new_type == GGML_TYPE_IQ3_S) {
  10094. int nx = tensor->ne[0];
  10095. int ny = tensor->ne[1];
  10096. if (nx % QK_K != 0) {
  10097. 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));
  10098. convert_incompatible_tensor = true;
  10099. } else {
  10100. ++qs.n_k_quantized;
  10101. }
  10102. }
  10103. if (convert_incompatible_tensor) {
  10104. switch (new_type) {
  10105. case GGML_TYPE_IQ2_XXS:
  10106. case GGML_TYPE_IQ2_XS:
  10107. case GGML_TYPE_IQ2_S:
  10108. case GGML_TYPE_IQ3_XXS:
  10109. case GGML_TYPE_IQ3_S:
  10110. case GGML_TYPE_IQ1_S:
  10111. case GGML_TYPE_Q2_K:
  10112. case GGML_TYPE_Q3_K:
  10113. case GGML_TYPE_IQ4_XS: new_type = GGML_TYPE_IQ4_NL; break;
  10114. case GGML_TYPE_Q4_K: new_type = GGML_TYPE_Q5_0; break;
  10115. case GGML_TYPE_Q5_K: new_type = GGML_TYPE_Q5_1; break;
  10116. case GGML_TYPE_Q6_K: new_type = GGML_TYPE_Q8_0; break;
  10117. default: throw std::runtime_error("\nUnsupported tensor size encountered\n");
  10118. }
  10119. LLAMA_LOG_WARN(" - using fallback quantization %s\n", ggml_type_name(new_type));
  10120. ++qs.n_fallback;
  10121. }
  10122. return new_type;
  10123. }
  10124. 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) {
  10125. std::mutex mutex;
  10126. int counter = 0;
  10127. size_t new_size = 0;
  10128. if (nthread < 2) {
  10129. // single-thread
  10130. return ggml_quantize_chunk(new_type, f32_data, new_data, 0, nrows, n_per_row, imatrix);
  10131. }
  10132. auto compute = [&mutex, &counter, &new_size, new_type, f32_data, new_data, chunk_size,
  10133. nrows, n_per_row, imatrix]() {
  10134. const int nrows_per_chunk = chunk_size / n_per_row;
  10135. size_t local_size = 0;
  10136. while (true) {
  10137. std::unique_lock<std::mutex> lock(mutex);
  10138. int first_row = counter; counter += nrows_per_chunk;
  10139. if (first_row >= nrows) {
  10140. if (local_size > 0) {
  10141. new_size += local_size;
  10142. }
  10143. break;
  10144. }
  10145. lock.unlock();
  10146. const int this_nrow = std::min(nrows - first_row, nrows_per_chunk);
  10147. local_size += ggml_quantize_chunk(new_type, f32_data, new_data, first_row * n_per_row, this_nrow, n_per_row, imatrix);
  10148. }
  10149. };
  10150. for (int it = 0; it < nthread - 1; ++it) {
  10151. workers.emplace_back(compute);
  10152. }
  10153. compute();
  10154. for (auto & w : workers) { w.join(); }
  10155. workers.clear();
  10156. return new_size;
  10157. }
  10158. static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) {
  10159. ggml_type default_type;
  10160. llama_ftype ftype = params->ftype;
  10161. switch (params->ftype) {
  10162. case LLAMA_FTYPE_MOSTLY_Q4_0: default_type = GGML_TYPE_Q4_0; break;
  10163. case LLAMA_FTYPE_MOSTLY_Q4_1: default_type = GGML_TYPE_Q4_1; break;
  10164. case LLAMA_FTYPE_MOSTLY_Q5_0: default_type = GGML_TYPE_Q5_0; break;
  10165. case LLAMA_FTYPE_MOSTLY_Q5_1: default_type = GGML_TYPE_Q5_1; break;
  10166. case LLAMA_FTYPE_MOSTLY_Q8_0: default_type = GGML_TYPE_Q8_0; break;
  10167. case LLAMA_FTYPE_MOSTLY_F16: default_type = GGML_TYPE_F16; break;
  10168. case LLAMA_FTYPE_ALL_F32: default_type = GGML_TYPE_F32; break;
  10169. // K-quants
  10170. case LLAMA_FTYPE_MOSTLY_Q2_K_S:
  10171. case LLAMA_FTYPE_MOSTLY_Q2_K: default_type = GGML_TYPE_Q2_K; break;
  10172. case LLAMA_FTYPE_MOSTLY_IQ3_XS: default_type = GGML_TYPE_IQ3_S; break;
  10173. case LLAMA_FTYPE_MOSTLY_Q3_K_S:
  10174. case LLAMA_FTYPE_MOSTLY_Q3_K_M:
  10175. case LLAMA_FTYPE_MOSTLY_Q3_K_L: default_type = GGML_TYPE_Q3_K; break;
  10176. case LLAMA_FTYPE_MOSTLY_Q4_K_S:
  10177. case LLAMA_FTYPE_MOSTLY_Q4_K_M: default_type = GGML_TYPE_Q4_K; break;
  10178. case LLAMA_FTYPE_MOSTLY_Q5_K_S:
  10179. case LLAMA_FTYPE_MOSTLY_Q5_K_M: default_type = GGML_TYPE_Q5_K; break;
  10180. case LLAMA_FTYPE_MOSTLY_Q6_K: default_type = GGML_TYPE_Q6_K; break;
  10181. case LLAMA_FTYPE_MOSTLY_IQ2_XXS: default_type = GGML_TYPE_IQ2_XXS; break;
  10182. case LLAMA_FTYPE_MOSTLY_IQ2_XS: default_type = GGML_TYPE_IQ2_XS; break;
  10183. case LLAMA_FTYPE_MOSTLY_IQ2_S: default_type = GGML_TYPE_IQ2_XS; break;
  10184. case LLAMA_FTYPE_MOSTLY_IQ2_M: default_type = GGML_TYPE_IQ2_S; break;
  10185. case LLAMA_FTYPE_MOSTLY_IQ3_XXS: default_type = GGML_TYPE_IQ3_XXS; break;
  10186. case LLAMA_FTYPE_MOSTLY_IQ1_S: default_type = GGML_TYPE_IQ1_S; break;
  10187. case LLAMA_FTYPE_MOSTLY_IQ4_NL: default_type = GGML_TYPE_IQ4_NL; break;
  10188. case LLAMA_FTYPE_MOSTLY_IQ4_XS: default_type = GGML_TYPE_IQ4_XS; break;
  10189. case LLAMA_FTYPE_MOSTLY_IQ3_S: default_type = GGML_TYPE_IQ3_S; break;
  10190. case LLAMA_FTYPE_MOSTLY_IQ3_M: default_type = GGML_TYPE_IQ3_S; break;
  10191. default: throw std::runtime_error(format("invalid output file type %d\n", ftype));
  10192. }
  10193. int nthread = params->nthread;
  10194. if (nthread <= 0) {
  10195. nthread = std::thread::hardware_concurrency();
  10196. }
  10197. // mmap consistently increases speed Linux, and also increases speed on Windows with
  10198. // hot cache. It may cause a slowdown on macOS, possibly related to free memory.
  10199. #if defined(__linux__) || defined(_WIN32)
  10200. constexpr bool use_mmap = true;
  10201. #else
  10202. constexpr bool use_mmap = false;
  10203. #endif
  10204. llama_model_loader ml(fname_inp, use_mmap, NULL);
  10205. ml.init_mapping(false); // no prefetching?
  10206. llama_model model;
  10207. llm_load_arch(ml, model);
  10208. llm_load_hparams(ml, model);
  10209. struct quantize_state_internal qs(model, params);
  10210. if (params->only_copy) {
  10211. ftype = model.ftype;
  10212. }
  10213. const std::unordered_map<std::string, std::vector<float>> * imatrix_data = nullptr;
  10214. if (params->imatrix) {
  10215. imatrix_data = static_cast<const std::unordered_map<std::string, std::vector<float>>*>(params->imatrix);
  10216. if (imatrix_data) {
  10217. LLAMA_LOG_INFO("================================ Have weights data with %d entries\n",int(imatrix_data->size()));
  10218. qs.has_imatrix = true;
  10219. }
  10220. }
  10221. const size_t align = GGUF_DEFAULT_ALIGNMENT;
  10222. struct gguf_context * ctx_out = gguf_init_empty();
  10223. // copy the KV pairs from the input file
  10224. gguf_set_kv (ctx_out, ml.ctx_gguf);
  10225. gguf_set_val_u32(ctx_out, "general.quantization_version", GGML_QNT_VERSION);
  10226. gguf_set_val_u32(ctx_out, "general.file_type", ftype);
  10227. for (int i = 0; i < ml.n_tensors; ++i) {
  10228. struct ggml_tensor * meta = ml.get_tensor_meta(i);
  10229. const std::string name = ggml_get_name(meta);
  10230. // TODO: avoid hardcoded tensor names - use the TN_* constants
  10231. if (name.find("attn_v.weight") != std::string::npos || name.find("attn_qkv.weight") != std::string::npos) {
  10232. ++qs.n_attention_wv;
  10233. }
  10234. else if (name.find("ffn_down") != std::string::npos) {
  10235. ++qs.n_ffn_down;
  10236. }
  10237. else if (name.find("ffn_gate") != std::string::npos) {
  10238. ++qs.n_ffn_gate;
  10239. }
  10240. else if (name.find("ffn_up") != std::string::npos) {
  10241. ++qs.n_ffn_up;
  10242. }
  10243. else if (name == LLM_TN(model.arch)(LLM_TENSOR_OUTPUT, "weight")) {
  10244. qs.has_output = true;
  10245. }
  10246. }
  10247. if (qs.n_attention_wv != qs.n_ffn_down || (uint32_t)qs.n_attention_wv != model.hparams.n_layer) {
  10248. LLAMA_LOG_WARN("%s ============ Strange model: n_attention_wv = %d, n_ffn_down = %d, hparams.n_layer = %d\n",
  10249. __func__, qs.n_attention_wv, qs.n_ffn_down, model.hparams.n_layer);
  10250. }
  10251. size_t total_size_org = 0;
  10252. size_t total_size_new = 0;
  10253. std::vector<std::thread> workers;
  10254. workers.reserve(nthread);
  10255. int idx = 0;
  10256. std::vector<no_init<uint8_t>> read_data;
  10257. std::vector<no_init<uint8_t>> work;
  10258. std::vector<no_init<float>> f32_conv_buf;
  10259. // populate the original tensors so we get an initial meta data
  10260. for (int i = 0; i < ml.n_tensors; ++i) {
  10261. struct ggml_tensor * meta = ml.get_tensor_meta(i);
  10262. gguf_add_tensor(ctx_out, meta);
  10263. }
  10264. std::ofstream fout(fname_out, std::ios::binary);
  10265. fout.exceptions(std::ofstream::failbit); // fail fast on write errors
  10266. const size_t meta_size = gguf_get_meta_size(ctx_out);
  10267. LLAMA_LOG_INFO("%s: meta size = %zu bytes\n", __func__, meta_size);
  10268. // placeholder for the meta data
  10269. ::zeros(fout, meta_size);
  10270. for (int i = 0; i < ml.n_tensors; ++i) {
  10271. struct ggml_tensor * tensor = ml.get_tensor_meta(i);
  10272. const std::string name = ggml_get_name(tensor);
  10273. if (!ml.use_mmap) {
  10274. if (read_data.size() < ggml_nbytes(tensor)) {
  10275. read_data.resize(ggml_nbytes(tensor));
  10276. }
  10277. tensor->data = read_data.data();
  10278. }
  10279. ml.load_data_for(tensor);
  10280. LLAMA_LOG_INFO("[%4d/%4d] %36s - [%s], type = %6s, ",
  10281. ++idx, ml.n_tensors,
  10282. ggml_get_name(tensor),
  10283. llama_format_tensor_shape(tensor).c_str(),
  10284. ggml_type_name(tensor->type));
  10285. // This used to be a regex, but <regex> has an extreme cost to compile times.
  10286. bool quantize = name.rfind("weight") == name.size() - 6; // ends with 'weight'?
  10287. // quantize only 2D tensors
  10288. quantize &= (ggml_n_dims(tensor) == 2);
  10289. quantize &= params->quantize_output_tensor || name != "output.weight";
  10290. quantize &= !params->only_copy;
  10291. // do not quantize expert gating tensors
  10292. // NOTE: can't use LLM_TN here because the layer number is not known
  10293. quantize &= name.find("ffn_gate_inp.weight") == std::string::npos;
  10294. // do not quantize positional embeddings and token types (BERT)
  10295. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_POS_EMBD, "weight");
  10296. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_TOKEN_TYPES, "weight");
  10297. // do not quantize Mamba's small yet 2D weights
  10298. // NOTE: can't use LLM_TN here because the layer number is not known
  10299. quantize &= name.find("ssm_conv1d.weight") == std::string::npos;
  10300. quantize &= name.find("ssm_x.weight") == std::string::npos;
  10301. quantize &= name.find("ssm_dt.weight") == std::string::npos;
  10302. enum ggml_type new_type;
  10303. void * new_data;
  10304. size_t new_size;
  10305. if (quantize) {
  10306. new_type = default_type;
  10307. // get more optimal quantization type based on the tensor shape, layer, etc.
  10308. if (!params->pure && ggml_is_quantized(default_type)) {
  10309. new_type = llama_tensor_get_type(qs, new_type, tensor, ftype);
  10310. }
  10311. // If we've decided to quantize to the same type the tensor is already
  10312. // in then there's nothing to do.
  10313. quantize = tensor->type != new_type;
  10314. }
  10315. if (!quantize) {
  10316. new_type = tensor->type;
  10317. new_data = tensor->data;
  10318. new_size = ggml_nbytes(tensor);
  10319. LLAMA_LOG_INFO("size = %8.3f MB\n", ggml_nbytes(tensor)/1024.0/1024.0);
  10320. } else {
  10321. const size_t nelements = ggml_nelements(tensor);
  10322. const float * imatrix = nullptr;
  10323. if (imatrix_data) {
  10324. auto it = imatrix_data->find(tensor->name);
  10325. if (it == imatrix_data->end()) {
  10326. LLAMA_LOG_INFO("\n====== %s: did not find weights for %s\n", __func__, tensor->name);
  10327. } else {
  10328. if (it->second.size() == (size_t)tensor->ne[0]) {
  10329. imatrix = it->second.data();
  10330. } else {
  10331. LLAMA_LOG_INFO("\n====== %s: imatrix size %d is different from tensor size %d for %s\n", __func__,
  10332. int(it->second.size()), int(tensor->ne[0]), tensor->name);
  10333. }
  10334. }
  10335. }
  10336. if ((new_type == GGML_TYPE_IQ2_XXS ||
  10337. new_type == GGML_TYPE_IQ2_XS ||
  10338. new_type == GGML_TYPE_IQ2_S ||
  10339. new_type == GGML_TYPE_IQ1_S ||
  10340. (new_type == GGML_TYPE_Q2_K && params->ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && strcmp(tensor->name, "token_embd.weight") != 0)) && !imatrix) {
  10341. LLAMA_LOG_ERROR("\n\n============================================================\n");
  10342. LLAMA_LOG_ERROR("Missing importance matrix for tensor %s in a very low-bit quantization\n", tensor->name);
  10343. LLAMA_LOG_ERROR("The result will be garbage, so bailing out\n");
  10344. LLAMA_LOG_ERROR("============================================================\n\n");
  10345. throw std::runtime_error(format("Missing importance matrix for tensor %s in a very low-bit quantization", tensor->name));
  10346. }
  10347. float * f32_data;
  10348. if (tensor->type == GGML_TYPE_F32) {
  10349. f32_data = (float *) tensor->data;
  10350. } else if (ggml_is_quantized(tensor->type) && !params->allow_requantize) {
  10351. throw std::runtime_error(format("requantizing from type %s is disabled", ggml_type_name(tensor->type)));
  10352. } else {
  10353. llama_tensor_dequantize_internal(tensor, f32_conv_buf, workers, nelements, nthread);
  10354. f32_data = (float *) f32_conv_buf.data();
  10355. }
  10356. LLAMA_LOG_INFO("converting to %s .. ", ggml_type_name(new_type));
  10357. fflush(stdout);
  10358. if (work.size() < nelements * 4) {
  10359. work.resize(nelements * 4); // upper bound on size
  10360. }
  10361. new_data = work.data();
  10362. const int n_per_row = tensor->ne[0];
  10363. const int nrows = nelements / n_per_row;
  10364. static const int min_chunk_size = 32 * 512;
  10365. 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);
  10366. const int nchunk = (nelements + chunk_size - 1)/chunk_size;
  10367. const int nthread_use = nthread > 1 ? std::max(1, std::min(nthread, nchunk)) : 1;
  10368. new_size = llama_tensor_quantize_internal(new_type, f32_data, new_data, chunk_size, nrows, n_per_row, imatrix, workers, nthread_use);
  10369. LLAMA_LOG_INFO("size = %8.2f MiB -> %8.2f MiB\n", ggml_nbytes(tensor)/1024.0/1024.0, new_size/1024.0/1024.0);
  10370. }
  10371. total_size_org += ggml_nbytes(tensor);
  10372. total_size_new += new_size;
  10373. // update the gguf meta data as we go
  10374. gguf_set_tensor_type(ctx_out, name.c_str(), new_type);
  10375. gguf_set_tensor_data(ctx_out, name.c_str(), new_data, new_size);
  10376. // write tensor data + padding
  10377. fout.write((const char *) new_data, new_size);
  10378. zeros(fout, GGML_PAD(new_size, align) - new_size);
  10379. }
  10380. // go back to beginning of file and write the updated meta data
  10381. {
  10382. fout.seekp(0);
  10383. std::vector<uint8_t> data(gguf_get_meta_size(ctx_out));
  10384. gguf_get_meta_data(ctx_out, data.data());
  10385. fout.write((const char *) data.data(), data.size());
  10386. }
  10387. fout.close();
  10388. gguf_free(ctx_out);
  10389. LLAMA_LOG_INFO("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  10390. LLAMA_LOG_INFO("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  10391. if (qs.n_fallback > 0) {
  10392. LLAMA_LOG_WARN("%s: WARNING: %d of %d tensor(s) required fallback quantization\n",
  10393. __func__, qs.n_fallback, qs.n_k_quantized + qs.n_fallback);
  10394. }
  10395. }
  10396. static int llama_apply_lora_from_file_internal(
  10397. const struct llama_model & model, const char * path_lora, float scale, const char * path_base_model, int n_threads
  10398. ) {
  10399. LLAMA_LOG_INFO("%s: applying lora adapter from '%s' - please wait ...\n", __func__, path_lora);
  10400. const int64_t t_start_lora_us = ggml_time_us();
  10401. llama_file fin(path_lora, "rb");
  10402. // verify magic and version
  10403. {
  10404. uint32_t magic = fin.read_u32();
  10405. if (magic != LLAMA_FILE_MAGIC_GGLA) {
  10406. LLAMA_LOG_ERROR("%s: bad file magic\n", __func__);
  10407. return 1;
  10408. }
  10409. uint32_t format_version = fin.read_u32();
  10410. if (format_version != 1) {
  10411. LLAMA_LOG_ERROR("%s: unsupported file version\n", __func__ );
  10412. return 1;
  10413. }
  10414. }
  10415. int32_t lora_r = fin.read_u32();
  10416. int32_t lora_alpha = fin.read_u32();
  10417. float scaling = scale * (float)lora_alpha / (float)lora_r;
  10418. LLAMA_LOG_INFO("%s: r = %d, alpha = %d, scaling = %.2f\n", __func__, lora_r, lora_alpha, scaling);
  10419. // load base model
  10420. std::unique_ptr<llama_model_loader> ml;
  10421. if (path_base_model) {
  10422. LLAMA_LOG_INFO("%s: loading base model from '%s'\n", __func__, path_base_model);
  10423. ml.reset(new llama_model_loader(path_base_model, /*use_mmap*/ true, /*kv_overrides*/ nullptr));
  10424. ml->init_mapping(/*prefetch*/ false); // no prefetching
  10425. }
  10426. struct tensor_meta {
  10427. std::string name;
  10428. ggml_type type;
  10429. int32_t ne[2];
  10430. size_t offset;
  10431. };
  10432. std::map<std::string, tensor_meta> tensor_meta_map;
  10433. // load all tensor meta
  10434. while (true) {
  10435. if (fin.tell() == fin.size) {
  10436. // eof
  10437. break;
  10438. }
  10439. int32_t n_dims;
  10440. int32_t name_len;
  10441. int32_t ftype;
  10442. fin.read_raw(&n_dims, sizeof(n_dims));
  10443. fin.read_raw(&name_len, sizeof(name_len));
  10444. fin.read_raw(&ftype, sizeof(ftype));
  10445. if (n_dims != 1 && n_dims != 2) {
  10446. LLAMA_LOG_ERROR("%s: unsupported tensor dimension %d\n", __func__, n_dims);
  10447. return 1;
  10448. }
  10449. int32_t ne[2] = { 1, 1 };
  10450. for (int i = 0; i < n_dims; ++i) {
  10451. fin.read_raw(&ne[i], sizeof(ne[i]));
  10452. }
  10453. std::string name;
  10454. {
  10455. GGML_ASSERT(name_len < GGML_MAX_NAME);
  10456. char buf[GGML_MAX_NAME];
  10457. fin.read_raw(buf, name_len);
  10458. name = std::string(buf, name_len);
  10459. }
  10460. // check for lora suffix
  10461. std::string lora_suffix;
  10462. if (name.length() > 6) {
  10463. lora_suffix = name.substr(name.length() - 6);
  10464. }
  10465. if (lora_suffix != ".loraA" && lora_suffix != ".loraB") {
  10466. LLAMA_LOG_ERROR("%s: error: '%s' is not a lora tensor\n", __func__, name.c_str());
  10467. return 1;
  10468. }
  10469. // tensor type
  10470. ggml_type wtype;
  10471. switch (ftype) {
  10472. case 0: wtype = GGML_TYPE_F32; break;
  10473. case 1: wtype = GGML_TYPE_F16; break;
  10474. default:
  10475. {
  10476. LLAMA_LOG_ERROR("%s: invalid tensor data type '%d'\n",
  10477. __func__, ftype);
  10478. return 1;
  10479. }
  10480. }
  10481. // data offset
  10482. size_t offset = fin.tell();
  10483. offset = (offset + 31) & -32;
  10484. // skip tensor data
  10485. fin.seek(offset + ggml_row_size(wtype, ne[0]) * ne[1], SEEK_SET);
  10486. tensor_meta_map.emplace(name, tensor_meta{ name, wtype, { ne[0], ne[1] }, offset });
  10487. }
  10488. bool warned = false;
  10489. int n_tensors = 0;
  10490. // apply
  10491. ggml_backend_t backend_cpu = ggml_backend_cpu_init();
  10492. if (backend_cpu == nullptr) {
  10493. LLAMA_LOG_ERROR("%s: error: failed to initialize cpu backend\n", __func__);
  10494. return 1;
  10495. }
  10496. ggml_backend_cpu_set_n_threads(backend_cpu, n_threads);
  10497. std::vector<no_init<uint8_t>> read_buf;
  10498. for (const auto & it : model.tensors_by_name) {
  10499. const std::string & base_name = it.first;
  10500. ggml_tensor * model_t = it.second;
  10501. if (tensor_meta_map.find(base_name + ".loraA") == tensor_meta_map.end() ||
  10502. tensor_meta_map.find(base_name + ".loraB") == tensor_meta_map.end()) {
  10503. continue;
  10504. }
  10505. tensor_meta & metaA = tensor_meta_map.at(base_name + ".loraA");
  10506. tensor_meta & metaB = tensor_meta_map.at(base_name + ".loraB");
  10507. ggml_init_params lora_init_params = {
  10508. /* .mem_size */ ggml_tensor_overhead()*128 + ggml_graph_overhead(),
  10509. /* .mem_buffer */ nullptr,
  10510. /* .no_alloc */ true,
  10511. };
  10512. ggml_context * lora_ctx = ggml_init(lora_init_params);
  10513. if (lora_ctx == nullptr) {
  10514. LLAMA_LOG_ERROR("%s: error: failed to initialize lora context\n", __func__);
  10515. ggml_backend_free(backend_cpu);
  10516. return 1;
  10517. }
  10518. // create tensors
  10519. ggml_tensor * loraA = ggml_new_tensor_2d(lora_ctx, metaA.type, metaA.ne[0], metaA.ne[1]);
  10520. ggml_tensor * loraB = ggml_new_tensor_2d(lora_ctx, metaB.type, metaB.ne[0], metaB.ne[1]);
  10521. ggml_set_name(loraA, metaA.name.c_str());
  10522. ggml_set_name(loraB, metaB.name.c_str());
  10523. ggml_tensor * base_t;
  10524. if (ml) {
  10525. if (gguf_find_tensor(ml->ctx_gguf, base_name.c_str()) < 0) {
  10526. LLAMA_LOG_ERROR("%s: error: tensor '%s' not found in base model\n", __func__, base_name.c_str());
  10527. return 1;
  10528. }
  10529. base_t = ggml_dup_tensor(lora_ctx, ml->get_tensor_meta(base_name.c_str()));
  10530. } else {
  10531. base_t = ggml_dup_tensor(lora_ctx, model_t);
  10532. }
  10533. ggml_set_name(base_t, base_name.c_str());
  10534. // allocate in backend buffer
  10535. ggml_backend_buffer_t lora_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  10536. if (lora_buf == nullptr) {
  10537. LLAMA_LOG_ERROR("%s: error: failed to allocate lora tensors\n", __func__);
  10538. return 1;
  10539. }
  10540. // load tensor data
  10541. auto load_tensor = [&read_buf, &fin](const tensor_meta & tensor_meta, ggml_tensor * tensor) {
  10542. read_buf.resize(ggml_nbytes(tensor));
  10543. fin.seek(tensor_meta.offset, SEEK_SET);
  10544. fin.read_raw(read_buf.data(), ggml_nbytes(tensor));
  10545. ggml_backend_tensor_set(tensor, read_buf.data(), 0, read_buf.size());
  10546. };
  10547. load_tensor(metaA, loraA);
  10548. load_tensor(metaB, loraB);
  10549. // load base model tensor data
  10550. if (ml) {
  10551. ml->load_data_for(base_t);
  10552. } else {
  10553. ggml_backend_tensor_copy(model_t, base_t);
  10554. }
  10555. if (ggml_is_quantized(base_t->type) && !warned) {
  10556. LLAMA_LOG_WARN("%s: warning: using a lora adapter with a quantized model may result in poor quality, "
  10557. "use a f16 or f32 base model with --lora-base\n", __func__);
  10558. warned = true;
  10559. }
  10560. if (base_t->ne[0] != loraA->ne[1] || base_t->ne[1] != loraB->ne[1]) {
  10561. LLAMA_LOG_ERROR("%s: incompatible tensor dimensions (%" PRId64 " and %" PRId64 ");"
  10562. " are you sure that this adapter is for this model?\n", __func__, base_t->ne[0], loraA->ne[1]);
  10563. ggml_free(lora_ctx);
  10564. ggml_backend_buffer_free(lora_buf);
  10565. ggml_backend_free(backend_cpu);
  10566. return 1;
  10567. }
  10568. auto build_lora_graph = [&]() {
  10569. // w = w + BA*s
  10570. ggml_tensor * BA = ggml_mul_mat(lora_ctx, loraA, loraB);
  10571. ggml_set_name(BA, "BA");
  10572. if (scaling != 1.0f) {
  10573. BA = ggml_scale(lora_ctx, BA, scaling);
  10574. ggml_set_name(BA, "BA_scaled");
  10575. }
  10576. ggml_tensor * r;
  10577. r = ggml_add_inplace(lora_ctx, base_t, BA);
  10578. ggml_set_name(r, "r_add");
  10579. if (base_t->type != model_t->type) {
  10580. // convert the result to the model type
  10581. r = ggml_cast(lora_ctx, r, model_t->type);
  10582. ggml_set_name(r, "r_cast");
  10583. }
  10584. return r;
  10585. };
  10586. ggml_cgraph * gf = ggml_new_graph(lora_ctx);
  10587. ggml_tensor * r = build_lora_graph();
  10588. ggml_build_forward_expand(gf, r);
  10589. ggml_backend_buffer_t graph_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  10590. if (graph_buf == nullptr) {
  10591. LLAMA_LOG_ERROR("%s: error: failed to allocate graph tensors\n", __func__);
  10592. ggml_free(lora_ctx);
  10593. ggml_backend_buffer_free(lora_buf);
  10594. ggml_backend_free(backend_cpu);
  10595. return 1;
  10596. }
  10597. ggml_backend_graph_compute(backend_cpu, gf);
  10598. ggml_backend_tensor_set(model_t, r->data, 0, ggml_nbytes(r));
  10599. #if 0
  10600. // TODO: use scheduler with fallback to CPU for less copies between CPU and GPU
  10601. //ggml_backend_sched_t sched = ggml_backend_sched_new(backends.data(), backends.size(), GGML_DEFAULT_GRAPH_SIZE);
  10602. // sched compute
  10603. ggml_build_forward_expand(gf, build_graph());
  10604. ggml_backend_sched_init_measure(sched, gf);
  10605. // create the graph again, since the previous one was destroyed by the measure
  10606. ggml_graph_clear(gf);
  10607. ggml_build_forward_expand(gf, build_graph());
  10608. ggml_backend_sched_graph_compute(sched, gf);
  10609. ggml_backend_sched_free(sched);
  10610. #endif
  10611. ggml_backend_buffer_free(lora_buf);
  10612. ggml_backend_buffer_free(graph_buf);
  10613. ggml_free(lora_ctx);
  10614. n_tensors++;
  10615. if (n_tensors % 4 == 0) {
  10616. LLAMA_LOG_INFO(".");
  10617. }
  10618. }
  10619. ggml_backend_free(backend_cpu);
  10620. const int64_t t_lora_us = ggml_time_us() - t_start_lora_us;
  10621. LLAMA_LOG_INFO(" done (%.2f ms)\n", t_lora_us / 1000.0);
  10622. return 0;
  10623. }
  10624. //
  10625. // interface implementation
  10626. //
  10627. struct llama_model_params llama_model_default_params() {
  10628. struct llama_model_params result = {
  10629. /*.n_gpu_layers =*/ 0,
  10630. /*.split_mode =*/ LLAMA_SPLIT_MODE_LAYER,
  10631. /*.main_gpu =*/ 0,
  10632. /*.tensor_split =*/ nullptr,
  10633. /*.progress_callback =*/ nullptr,
  10634. /*.progress_callback_user_data =*/ nullptr,
  10635. /*.kv_overrides =*/ nullptr,
  10636. /*.vocab_only =*/ false,
  10637. /*.use_mmap =*/ true,
  10638. /*.use_mlock =*/ false,
  10639. };
  10640. #ifdef GGML_USE_METAL
  10641. // note: we usually have plenty of VRAM, so by default offload all layers to the GPU
  10642. result.n_gpu_layers = 999;
  10643. #endif
  10644. return result;
  10645. }
  10646. struct llama_context_params llama_context_default_params() {
  10647. struct llama_context_params result = {
  10648. /*.seed =*/ LLAMA_DEFAULT_SEED,
  10649. /*.n_ctx =*/ 512,
  10650. /*.n_batch =*/ 2048,
  10651. /*.n_ubatch =*/ 512,
  10652. /*.n_seq_max =*/ 1,
  10653. /*.n_threads =*/ GGML_DEFAULT_N_THREADS, // TODO: better default
  10654. /*.n_threads_batch =*/ GGML_DEFAULT_N_THREADS,
  10655. /*.rope_scaling_type =*/ LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED,
  10656. /*.pooling_type =*/ LLAMA_POOLING_TYPE_UNSPECIFIED,
  10657. /*.rope_freq_base =*/ 0.0f,
  10658. /*.rope_freq_scale =*/ 0.0f,
  10659. /*.yarn_ext_factor =*/ -1.0f,
  10660. /*.yarn_attn_factor =*/ 1.0f,
  10661. /*.yarn_beta_fast =*/ 32.0f,
  10662. /*.yarn_beta_slow =*/ 1.0f,
  10663. /*.yarn_orig_ctx =*/ 0,
  10664. /*.defrag_thold =*/ -1.0f,
  10665. /*.cb_eval =*/ nullptr,
  10666. /*.cb_eval_user_data =*/ nullptr,
  10667. /*.type_k =*/ GGML_TYPE_F16,
  10668. /*.type_v =*/ GGML_TYPE_F16,
  10669. /*.logits_all =*/ false,
  10670. /*.embeddings =*/ false,
  10671. /*.offload_kqv =*/ true,
  10672. /*.abort_callback =*/ nullptr,
  10673. /*.abort_callback_data =*/ nullptr,
  10674. };
  10675. return result;
  10676. }
  10677. struct llama_model_quantize_params llama_model_quantize_default_params() {
  10678. struct llama_model_quantize_params result = {
  10679. /*.nthread =*/ 0,
  10680. /*.ftype =*/ LLAMA_FTYPE_MOSTLY_Q5_1,
  10681. /*.allow_requantize =*/ false,
  10682. /*.quantize_output_tensor =*/ true,
  10683. /*.only_copy =*/ false,
  10684. /*.pure =*/ false,
  10685. /*.imatrix =*/ nullptr,
  10686. };
  10687. return result;
  10688. }
  10689. size_t llama_max_devices(void) {
  10690. #if defined(GGML_USE_METAL)
  10691. return 1;
  10692. #elif defined(GGML_USE_CUBLAS)
  10693. return GGML_CUDA_MAX_DEVICES;
  10694. #elif defined(GGML_USE_SYCL)
  10695. return GGML_SYCL_MAX_DEVICES;
  10696. #elif defined(GGML_USE_VULKAN)
  10697. return GGML_VK_MAX_DEVICES;
  10698. #else
  10699. return 1;
  10700. #endif
  10701. }
  10702. bool llama_supports_mmap(void) {
  10703. return llama_mmap::SUPPORTED;
  10704. }
  10705. bool llama_supports_mlock(void) {
  10706. return llama_mlock::SUPPORTED;
  10707. }
  10708. bool llama_supports_gpu_offload(void) {
  10709. #if defined(GGML_USE_CUBLAS) || defined(GGML_USE_CLBLAST) || defined(GGML_USE_METAL) || defined(GGML_USE_VULKAN) || \
  10710. defined(GGML_USE_SYCL) || defined(GGML_USE_KOMPUTE)
  10711. // Defined when llama.cpp is compiled with support for offloading model layers to GPU.
  10712. return true;
  10713. #else
  10714. return false;
  10715. #endif
  10716. }
  10717. void llama_backend_init(void) {
  10718. ggml_time_init();
  10719. // needed to initialize f16 tables
  10720. {
  10721. struct ggml_init_params params = { 0, NULL, false };
  10722. struct ggml_context * ctx = ggml_init(params);
  10723. ggml_free(ctx);
  10724. }
  10725. #ifdef GGML_USE_MPI
  10726. ggml_mpi_backend_init();
  10727. #endif
  10728. }
  10729. void llama_numa_init(enum ggml_numa_strategy numa) {
  10730. if (numa != GGML_NUMA_STRATEGY_DISABLED) {
  10731. ggml_numa_init(numa);
  10732. }
  10733. }
  10734. void llama_backend_free(void) {
  10735. #ifdef GGML_USE_MPI
  10736. ggml_mpi_backend_free();
  10737. #endif
  10738. ggml_quantize_free();
  10739. }
  10740. int64_t llama_time_us(void) {
  10741. return ggml_time_us();
  10742. }
  10743. struct llama_model * llama_load_model_from_file(
  10744. const char * path_model,
  10745. struct llama_model_params params) {
  10746. ggml_time_init();
  10747. llama_model * model = new llama_model;
  10748. unsigned cur_percentage = 0;
  10749. if (params.progress_callback == NULL) {
  10750. params.progress_callback_user_data = &cur_percentage;
  10751. params.progress_callback = [](float progress, void * ctx) {
  10752. unsigned * cur_percentage_p = (unsigned *) ctx;
  10753. unsigned percentage = (unsigned) (100 * progress);
  10754. while (percentage > *cur_percentage_p) {
  10755. *cur_percentage_p = percentage;
  10756. LLAMA_LOG_INFO(".");
  10757. if (percentage >= 100) {
  10758. LLAMA_LOG_INFO("\n");
  10759. }
  10760. }
  10761. return true;
  10762. };
  10763. }
  10764. int status = llama_model_load(path_model, *model, params);
  10765. GGML_ASSERT(status <= 0);
  10766. if (status < 0) {
  10767. if (status == -1) {
  10768. LLAMA_LOG_ERROR("%s: failed to load model\n", __func__);
  10769. } else if (status == -2) {
  10770. LLAMA_LOG_INFO("%s: cancelled model load\n", __func__);
  10771. }
  10772. delete model;
  10773. return nullptr;
  10774. }
  10775. return model;
  10776. }
  10777. void llama_free_model(struct llama_model * model) {
  10778. delete model;
  10779. }
  10780. struct llama_context * llama_new_context_with_model(
  10781. struct llama_model * model,
  10782. struct llama_context_params params) {
  10783. if (!model) {
  10784. LLAMA_LOG_ERROR("%s: model cannot be NULL\n", __func__);
  10785. return nullptr;
  10786. }
  10787. if (params.n_batch == 0 && params.n_ubatch == 0) {
  10788. LLAMA_LOG_ERROR("%s: n_batch and n_ubatch cannot both be zero\n", __func__);
  10789. return nullptr;
  10790. }
  10791. if (params.n_ctx == 0 && model->hparams.n_ctx_train == 0) {
  10792. LLAMA_LOG_ERROR("%s: n_ctx and model->hparams.n_ctx_train cannot both be zero\n", __func__);
  10793. return nullptr;
  10794. }
  10795. llama_context * ctx = new llama_context(*model);
  10796. const auto & hparams = model->hparams;
  10797. auto & cparams = ctx->cparams;
  10798. // TODO: maybe add n_seq_max here too
  10799. cparams.n_threads = params.n_threads;
  10800. cparams.n_threads_batch = params.n_threads_batch;
  10801. cparams.yarn_ext_factor = params.yarn_ext_factor;
  10802. cparams.yarn_attn_factor = params.yarn_attn_factor;
  10803. cparams.yarn_beta_fast = params.yarn_beta_fast;
  10804. cparams.yarn_beta_slow = params.yarn_beta_slow;
  10805. cparams.defrag_thold = params.defrag_thold;
  10806. cparams.embeddings = params.embeddings;
  10807. cparams.offload_kqv = params.offload_kqv;
  10808. cparams.pooling_type = params.pooling_type;
  10809. cparams.n_ctx = params.n_ctx == 0 ? hparams.n_ctx_train : params.n_ctx;
  10810. cparams.rope_freq_base = params.rope_freq_base == 0.0f ? hparams.rope_freq_base_train : params.rope_freq_base;
  10811. cparams.rope_freq_scale = params.rope_freq_scale == 0.0f ? hparams.rope_freq_scale_train : params.rope_freq_scale;
  10812. // with causal attention, the batch size is limited by the context size
  10813. cparams.n_batch = hparams.causal_attn ? std::min(cparams.n_ctx, params.n_batch) : params.n_batch;
  10814. cparams.n_ubatch = std::min(cparams.n_batch, params.n_ubatch == 0 ? params.n_batch : params.n_ubatch);
  10815. cparams.n_yarn_orig_ctx = params.yarn_orig_ctx != 0 ? params.yarn_orig_ctx :
  10816. hparams.n_yarn_orig_ctx != 0 ? hparams.n_yarn_orig_ctx :
  10817. hparams.n_ctx_train;
  10818. cparams.cb_eval = params.cb_eval;
  10819. cparams.cb_eval_user_data = params.cb_eval_user_data;
  10820. auto rope_scaling_type = params.rope_scaling_type;
  10821. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED) {
  10822. rope_scaling_type = hparams.rope_scaling_type_train;
  10823. }
  10824. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_NONE) {
  10825. cparams.rope_freq_scale = 1.0f; // never scale if scaling type is none
  10826. }
  10827. if (cparams.yarn_ext_factor < 0.0f) { // negative indicates 'not set'
  10828. cparams.yarn_ext_factor = rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_YARN ? 1.0f : 0.0f;
  10829. }
  10830. cparams.causal_attn = hparams.causal_attn;
  10831. if (cparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  10832. if (hparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
  10833. cparams.pooling_type = LLAMA_POOLING_TYPE_NONE;
  10834. } else {
  10835. cparams.pooling_type = hparams.pooling_type;
  10836. }
  10837. }
  10838. if (params.seed == LLAMA_DEFAULT_SEED) {
  10839. params.seed = time(NULL);
  10840. }
  10841. LLAMA_LOG_INFO("%s: n_ctx = %u\n", __func__, cparams.n_ctx);
  10842. LLAMA_LOG_INFO("%s: n_batch = %u\n", __func__, cparams.n_batch);
  10843. LLAMA_LOG_INFO("%s: n_ubatch = %u\n", __func__, cparams.n_ubatch);
  10844. LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, cparams.rope_freq_base);
  10845. LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, cparams.rope_freq_scale);
  10846. ctx->abort_callback = params.abort_callback;
  10847. ctx->abort_callback_data = params.abort_callback_data;
  10848. ctx->rng = std::mt19937(params.seed);
  10849. ctx->logits_all = params.logits_all;
  10850. uint32_t kv_size = cparams.n_ctx;
  10851. ggml_type type_k = params.type_k;
  10852. ggml_type type_v = params.type_v;
  10853. // Mamba only needs a constant number of KV cache cells per sequence
  10854. if (model->arch == LLM_ARCH_MAMBA) {
  10855. // Mamba needs at least as many KV cells as there are sequences kept at any time
  10856. kv_size = std::max((uint32_t) 1, params.n_seq_max);
  10857. // it's probably best to keep as much precision as possible for the states
  10858. type_k = GGML_TYPE_F32; // required by ggml_ssm_conv for Mamba's conv_states
  10859. type_v = GGML_TYPE_F32; // required by ggml_ssm_scan for Mamba's ssm_states
  10860. }
  10861. GGML_ASSERT(hparams.n_embd_head_k % ggml_blck_size(type_k) == 0);
  10862. GGML_ASSERT(hparams.n_embd_head_v % ggml_blck_size(type_v) == 0);
  10863. if (!hparams.vocab_only) {
  10864. // initialize backends
  10865. #ifdef GGML_USE_METAL
  10866. if (model->n_gpu_layers > 0) {
  10867. ctx->backend_metal = ggml_backend_metal_init();
  10868. if (ctx->backend_metal == nullptr) {
  10869. LLAMA_LOG_ERROR("%s: failed to initialize Metal backend\n", __func__);
  10870. llama_free(ctx);
  10871. return nullptr;
  10872. }
  10873. ctx->backends.push_back(ctx->backend_metal);
  10874. }
  10875. #elif defined(GGML_USE_CUBLAS)
  10876. if (model->n_gpu_layers > 0) {
  10877. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  10878. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  10879. ggml_backend_t backend = ggml_backend_cuda_init(model->main_gpu);
  10880. if (backend == nullptr) {
  10881. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, model->main_gpu);
  10882. llama_free(ctx);
  10883. return nullptr;
  10884. }
  10885. ctx->backends.push_back(backend);
  10886. } else {
  10887. // LLAMA_SPLIT_MODE_LAYER requires a backend for each GPU
  10888. for (int device = 0; device < ggml_backend_cuda_get_device_count(); ++device) {
  10889. ggml_backend_t backend = ggml_backend_cuda_init(device);
  10890. if (backend == nullptr) {
  10891. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, device);
  10892. llama_free(ctx);
  10893. return nullptr;
  10894. }
  10895. ctx->backends.push_back(backend);
  10896. }
  10897. }
  10898. }
  10899. #elif defined(GGML_USE_VULKAN)
  10900. if (model->n_gpu_layers > 0) {
  10901. for (int device = 0; device < ggml_backend_vk_get_device_count(); ++device) {
  10902. ggml_backend_t backend = ggml_backend_vk_init(device);
  10903. if (backend == nullptr) {
  10904. LLAMA_LOG_ERROR("%s: failed to initialize Vulkan%d backend\n", __func__, device);
  10905. llama_free(ctx);
  10906. return nullptr;
  10907. }
  10908. ctx->backends.push_back(backend);
  10909. }
  10910. }
  10911. #elif defined(GGML_USE_SYCL)
  10912. if (model->n_gpu_layers > 0) {
  10913. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  10914. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  10915. ggml_backend_t backend = ggml_backend_sycl_init(model->main_gpu);
  10916. if (backend == nullptr) {
  10917. int main_gpu_id = ggml_backend_sycl_get_device_id(model->main_gpu);
  10918. LLAMA_LOG_ERROR("%s: failed to initialize SYCL%d (index %d) backend\n", __func__, main_gpu_id, model->main_gpu);
  10919. llama_free(ctx);
  10920. return nullptr;
  10921. }
  10922. ctx->backends.push_back(backend);
  10923. } else {
  10924. // LLAMA_SPLIT_LAYER requires a backend for each GPU
  10925. for (int i = 0; i < ggml_backend_sycl_get_device_count(); ++i) {
  10926. ggml_backend_t backend = ggml_backend_sycl_init(i);
  10927. if (backend == nullptr) {
  10928. int id_list[GGML_SYCL_MAX_DEVICES];
  10929. ggml_sycl_get_gpu_list(id_list, GGML_SYCL_MAX_DEVICES);
  10930. LLAMA_LOG_ERROR("%s: failed to initialize SYCL%d (index %d) backend\n", __func__, id_list[i], i);
  10931. llama_free(ctx);
  10932. return nullptr;
  10933. }
  10934. ctx->backends.push_back(backend);
  10935. }
  10936. }
  10937. }
  10938. #elif defined(GGML_USE_KOMPUTE)
  10939. if (model->n_gpu_layers > 0) {
  10940. auto * backend = ggml_backend_kompute_init(model->main_gpu);
  10941. if (backend == nullptr) {
  10942. LLAMA_LOG_ERROR("%s: failed to initialize Kompute backend\n", __func__);
  10943. llama_free(ctx);
  10944. return nullptr;
  10945. }
  10946. ctx->backends.push_back(backend);
  10947. }
  10948. #endif
  10949. ctx->backend_cpu = ggml_backend_cpu_init();
  10950. if (ctx->backend_cpu == nullptr) {
  10951. LLAMA_LOG_ERROR("%s: failed to initialize CPU backend\n", __func__);
  10952. llama_free(ctx);
  10953. return nullptr;
  10954. }
  10955. ctx->backends.push_back(ctx->backend_cpu);
  10956. if (!llama_kv_cache_init(ctx->kv_self, ctx->model, type_k, type_v, kv_size, cparams.offload_kqv)) {
  10957. LLAMA_LOG_ERROR("%s: llama_kv_cache_init() failed for self-attention cache\n", __func__);
  10958. llama_free(ctx);
  10959. return nullptr;
  10960. }
  10961. {
  10962. size_t memory_size_k = 0;
  10963. size_t memory_size_v = 0;
  10964. for (auto & k : ctx->kv_self.k_l) {
  10965. memory_size_k += ggml_nbytes(k);
  10966. }
  10967. for (auto & v : ctx->kv_self.v_l) {
  10968. memory_size_v += ggml_nbytes(v);
  10969. }
  10970. LLAMA_LOG_INFO("%s: KV self size = %7.2f MiB, K (%s): %7.2f MiB, V (%s): %7.2f MiB\n", __func__,
  10971. (float)(memory_size_k + memory_size_v) / (1024.0f * 1024.0f),
  10972. ggml_type_name(type_k), (float)memory_size_k / (1024.0f * 1024.0f),
  10973. ggml_type_name(type_v), (float)memory_size_v / (1024.0f * 1024.0f));
  10974. }
  10975. // graph outputs buffer
  10976. {
  10977. // resized during inference, reserve maximum
  10978. ctx->logits_size = hparams.n_vocab*cparams.n_batch;
  10979. ctx->embd_size = params.embeddings ? hparams.n_embd*cparams.n_batch : 0;
  10980. const size_t buf_output_size = (ctx->logits_size + ctx->embd_size)*sizeof(float);
  10981. ctx->buf_output = ggml_backend_buft_alloc_buffer(llama_default_buffer_type_cpu(true), buf_output_size);
  10982. if (ctx->buf_output == nullptr) {
  10983. LLAMA_LOG_ERROR("%s: failed to allocate logits buffer\n", __func__);
  10984. llama_free(ctx);
  10985. return nullptr;
  10986. }
  10987. ggml_backend_buffer_clear(ctx->buf_output, 0);
  10988. ctx->logits = (float *) ggml_backend_buffer_get_base(ctx->buf_output);
  10989. if (params.embeddings) {
  10990. ctx->embd = ctx->logits + ctx->logits_size;
  10991. }
  10992. LLAMA_LOG_INFO("%s: %10s output buffer size = %8.2f MiB\n", __func__,
  10993. ggml_backend_buffer_name(ctx->buf_output),
  10994. ggml_backend_buffer_get_size(ctx->buf_output) / 1024.0 / 1024.0);
  10995. }
  10996. // scheduler and compute buffers
  10997. {
  10998. // buffer types used for the compute buffer of each backend
  10999. std::vector<ggml_backend_buffer_type_t> backend_buft;
  11000. for (auto * backend : ctx->backends) {
  11001. if (ggml_backend_is_cpu(backend)) {
  11002. // use host buffers for the CPU backend compute buffer
  11003. backend_buft.push_back(llama_default_buffer_type_cpu(true));
  11004. } else {
  11005. backend_buft.push_back(ggml_backend_get_default_buffer_type(backend));
  11006. }
  11007. }
  11008. // buffer used to store the computation graph and the tensor meta data
  11009. ctx->buf_compute_meta.resize(ggml_tensor_overhead()*LLAMA_MAX_NODES + ggml_graph_overhead_custom(LLAMA_MAX_NODES, false));
  11010. // enabling pipeline parallelism in the scheduler increases memory usage, so it is only done when necessary
  11011. bool pipeline_parallel = llama_get_device_count() > 1 && model->n_gpu_layers > (int)model->hparams.n_layer && model->split_mode == LLAMA_SPLIT_MODE_LAYER;
  11012. #ifndef GGML_USE_CUBLAS
  11013. // pipeline parallelism requires support for async compute and events
  11014. // currently this is only implemented in the CUDA backend
  11015. pipeline_parallel = false;
  11016. #endif
  11017. ctx->sched = ggml_backend_sched_new(ctx->backends.data(), backend_buft.data(), ctx->backends.size(), LLAMA_MAX_NODES, pipeline_parallel);
  11018. if (pipeline_parallel) {
  11019. LLAMA_LOG_INFO("%s: pipeline parallelism enabled (n_copies=%d)\n", __func__, ggml_backend_sched_get_n_copies(ctx->sched));
  11020. }
  11021. // build worst-case graph
  11022. int n_tokens = (int)std::min(cparams.n_ctx, cparams.n_ubatch);
  11023. int n_past = cparams.n_ctx - n_tokens;
  11024. 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
  11025. ggml_cgraph * gf = llama_build_graph(*ctx, llama_batch_get_one(&token, n_tokens, n_past, 0), true);
  11026. // initialize scheduler with the worst-case graph
  11027. if (!ggml_backend_sched_reserve(ctx->sched, gf)) {
  11028. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  11029. llama_free(ctx);
  11030. return nullptr;
  11031. }
  11032. for (size_t i = 0; i < ctx->backends.size(); i++) {
  11033. ggml_backend_t backend = ctx->backends[i];
  11034. ggml_backend_buffer_type_t buft = backend_buft[i];
  11035. size_t size = ggml_backend_sched_get_buffer_size(ctx->sched, backend);
  11036. LLAMA_LOG_INFO("%s: %10s compute buffer size = %8.2f MiB\n", __func__,
  11037. ggml_backend_buft_name(buft),
  11038. size / 1024.0 / 1024.0);
  11039. }
  11040. // note: the number of splits during measure is higher than during inference due to the kv shift
  11041. int n_splits = ggml_backend_sched_get_n_splits(ctx->sched);
  11042. LLAMA_LOG_INFO("%s: graph splits: %d\n", __func__, n_splits);
  11043. }
  11044. }
  11045. #ifdef GGML_USE_MPI
  11046. ctx->ctx_mpi = ggml_mpi_init();
  11047. if (ggml_mpi_rank(ctx->ctx_mpi) > 0) {
  11048. // Enter a blocking eval loop with dummy input, letting rank=0 drive the process
  11049. // TODO: needs fix after #3228
  11050. GGML_ASSERT(false && "not implemented");
  11051. //const std::vector<llama_token> tmp(ctx->model.hparams.n_ctx, llama_token_bos(ctx));
  11052. //while (!llama_eval(ctx, tmp.data(), tmp.size(), 0, 0)) {};
  11053. llama_backend_free();
  11054. exit(1);
  11055. }
  11056. #endif
  11057. return ctx;
  11058. }
  11059. void llama_free(struct llama_context * ctx) {
  11060. delete ctx;
  11061. }
  11062. const llama_model * llama_get_model(const struct llama_context * ctx) {
  11063. return &ctx->model;
  11064. }
  11065. uint32_t llama_n_ctx(const struct llama_context * ctx) {
  11066. return ctx->cparams.n_ctx;
  11067. }
  11068. uint32_t llama_n_batch(const struct llama_context * ctx) {
  11069. return ctx->cparams.n_batch;
  11070. }
  11071. uint32_t llama_n_ubatch(const struct llama_context * ctx) {
  11072. return ctx->cparams.n_ubatch;
  11073. }
  11074. uint32_t llama_n_seq_max(const struct llama_context * ctx) {
  11075. return ctx->kv_self.size;
  11076. }
  11077. enum llama_vocab_type llama_vocab_type(const struct llama_model * model) {
  11078. return model->vocab.type;
  11079. }
  11080. enum llama_rope_type llama_rope_type(const struct llama_model * model) {
  11081. switch (model->arch) {
  11082. // these models do not use RoPE
  11083. case LLM_ARCH_GPT2:
  11084. case LLM_ARCH_GPTJ:
  11085. case LLM_ARCH_GPTNEOX:
  11086. case LLM_ARCH_MPT:
  11087. case LLM_ARCH_REFACT:
  11088. case LLM_ARCH_BLOOM:
  11089. case LLM_ARCH_MAMBA:
  11090. return LLAMA_ROPE_TYPE_NONE;
  11091. // use what we call a normal RoPE, operating on pairs of consecutive head values
  11092. case LLM_ARCH_LLAMA:
  11093. case LLM_ARCH_BAICHUAN:
  11094. case LLM_ARCH_STARCODER:
  11095. case LLM_ARCH_PLAMO:
  11096. case LLM_ARCH_CODESHELL:
  11097. case LLM_ARCH_ORION:
  11098. case LLM_ARCH_INTERNLM2:
  11099. case LLM_ARCH_MINICPM:
  11100. case LLM_ARCH_COMMAND_R:
  11101. return LLAMA_ROPE_TYPE_NORM;
  11102. // the pairs of head values are offset by n_rot/2
  11103. case LLM_ARCH_FALCON:
  11104. case LLM_ARCH_PERSIMMON:
  11105. case LLM_ARCH_BERT:
  11106. case LLM_ARCH_NOMIC_BERT:
  11107. case LLM_ARCH_STABLELM:
  11108. case LLM_ARCH_QWEN:
  11109. case LLM_ARCH_QWEN2:
  11110. case LLM_ARCH_PHI2:
  11111. case LLM_ARCH_GEMMA:
  11112. case LLM_ARCH_STARCODER2:
  11113. return LLAMA_ROPE_TYPE_NEOX;
  11114. // all model arches should be listed explicitly here
  11115. case LLM_ARCH_UNKNOWN:
  11116. GGML_ASSERT(false && "unknown architecture");
  11117. break;
  11118. }
  11119. return LLAMA_ROPE_TYPE_NONE;
  11120. }
  11121. int32_t llama_n_vocab(const struct llama_model * model) {
  11122. return model->hparams.n_vocab;
  11123. }
  11124. int32_t llama_n_ctx_train(const struct llama_model * model) {
  11125. return model->hparams.n_ctx_train;
  11126. }
  11127. int32_t llama_n_embd(const struct llama_model * model) {
  11128. return model->hparams.n_embd;
  11129. }
  11130. int32_t llama_n_layer(const struct llama_model * model) {
  11131. return model->hparams.n_layer;
  11132. }
  11133. float llama_rope_freq_scale_train(const struct llama_model * model) {
  11134. return model->hparams.rope_freq_scale_train;
  11135. }
  11136. int32_t llama_model_meta_val_str(const struct llama_model * model, const char * key, char * buf, size_t buf_size) {
  11137. const auto & it = model->gguf_kv.find(key);
  11138. if (it == model->gguf_kv.end()) {
  11139. if (buf_size > 0) {
  11140. buf[0] = '\0';
  11141. }
  11142. return -1;
  11143. }
  11144. return snprintf(buf, buf_size, "%s", it->second.c_str());
  11145. }
  11146. int32_t llama_model_meta_count(const struct llama_model * model) {
  11147. return (int)model->gguf_kv.size();
  11148. }
  11149. int32_t llama_model_meta_key_by_index(const struct llama_model * model, int i, char * buf, size_t buf_size) {
  11150. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  11151. if (buf_size > 0) {
  11152. buf[0] = '\0';
  11153. }
  11154. return -1;
  11155. }
  11156. auto it = model->gguf_kv.begin();
  11157. std::advance(it, i);
  11158. return snprintf(buf, buf_size, "%s", it->first.c_str());
  11159. }
  11160. int32_t llama_model_meta_val_str_by_index(const struct llama_model * model, int32_t i, char * buf, size_t buf_size) {
  11161. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  11162. if (buf_size > 0) {
  11163. buf[0] = '\0';
  11164. }
  11165. return -1;
  11166. }
  11167. auto it = model->gguf_kv.begin();
  11168. std::advance(it, i);
  11169. return snprintf(buf, buf_size, "%s", it->second.c_str());
  11170. }
  11171. int32_t llama_model_desc(const struct llama_model * model, char * buf, size_t buf_size) {
  11172. return snprintf(buf, buf_size, "%s %s %s",
  11173. llama_model_arch_name(model->arch),
  11174. llama_model_type_name(model->type),
  11175. llama_model_ftype_name(model->ftype).c_str());
  11176. }
  11177. uint64_t llama_model_size(const struct llama_model * model) {
  11178. uint64_t size = 0;
  11179. for (const auto & it : model->tensors_by_name) {
  11180. size += ggml_nbytes(it.second);
  11181. }
  11182. return size;
  11183. }
  11184. uint64_t llama_model_n_params(const struct llama_model * model) {
  11185. uint64_t nparams = 0;
  11186. for (const auto & it : model->tensors_by_name) {
  11187. nparams += ggml_nelements(it.second);
  11188. }
  11189. return nparams;
  11190. }
  11191. struct ggml_tensor * llama_get_model_tensor(struct llama_model * model, const char * name) {
  11192. auto it = std::find_if(model->tensors_by_name.begin(), model->tensors_by_name.end(),
  11193. [name](const std::pair<std::string, struct ggml_tensor *> & it) {
  11194. return it.first == name;
  11195. });
  11196. if (it == model->tensors_by_name.end()) {
  11197. return nullptr;
  11198. }
  11199. return it->second;
  11200. }
  11201. uint32_t llama_model_quantize(
  11202. const char * fname_inp,
  11203. const char * fname_out,
  11204. const llama_model_quantize_params * params) {
  11205. try {
  11206. llama_model_quantize_internal(fname_inp, fname_out, params);
  11207. return 0;
  11208. } catch (const std::exception & err) {
  11209. LLAMA_LOG_ERROR("%s: failed to quantize: %s\n", __func__, err.what());
  11210. return 1;
  11211. }
  11212. }
  11213. 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) {
  11214. try {
  11215. return llama_apply_lora_from_file_internal(*model, path_lora, scale, path_base_model, n_threads);
  11216. } catch (const std::exception & err) {
  11217. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  11218. return 1;
  11219. }
  11220. }
  11221. static bool llama_control_vector_init(struct llama_control_vector & cvec, const llama_model & model) {
  11222. GGML_ASSERT(cvec.tensors.empty());
  11223. GGML_ASSERT(cvec.ctxs.empty());
  11224. GGML_ASSERT(cvec.bufs.empty());
  11225. // count layer buffer types
  11226. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  11227. for (int64_t i = 0; i < model.hparams.n_layer; i++) {
  11228. buft_layer_count[model.buft_layer[i].buft]++;
  11229. }
  11230. // allocate contexts
  11231. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  11232. for (auto & it : buft_layer_count) {
  11233. int n_layers = it.second;
  11234. struct ggml_init_params params = {
  11235. /*.mem_size =*/ n_layers * ggml_tensor_overhead(),
  11236. /*.mem_buffer =*/ NULL,
  11237. /*.no_alloc =*/ true,
  11238. };
  11239. ggml_context * ctx = ggml_init(params);
  11240. if (!ctx) {
  11241. LLAMA_LOG_ERROR("%s: failed to allocate context for control vector\n", __func__);
  11242. return 1;
  11243. }
  11244. ctx_map[it.first] = ctx;
  11245. }
  11246. // make tensors
  11247. cvec.tensors.push_back(nullptr); // there's never a tensor for layer 0
  11248. for (size_t il = 1; il < model.hparams.n_layer; il++) {
  11249. struct ggml_context * ctx = ctx_map.at(model.buft_layer[il].buft);
  11250. ggml_tensor * tensor = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, model.hparams.n_embd);
  11251. cvec.tensors.push_back(tensor);
  11252. }
  11253. // allocate tensors / buffers and zero
  11254. for (auto it : ctx_map) {
  11255. ggml_backend_buffer_type_t buft = it.first;
  11256. ggml_context * ctx = it.second;
  11257. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  11258. if (!buf) {
  11259. LLAMA_LOG_ERROR("%s: failed to allocate buffer for control vector\n", __func__);
  11260. return false;
  11261. }
  11262. ggml_backend_buffer_clear(buf, 0);
  11263. cvec.ctxs.push_back(ctx);
  11264. cvec.bufs.push_back(buf);
  11265. }
  11266. return true;
  11267. }
  11268. 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) {
  11269. const llama_model & model = lctx->model;
  11270. llama_control_vector & cvec = lctx->cvec;
  11271. if (data == nullptr) {
  11272. // disable the current control vector (but leave allocated for later)
  11273. cvec.layer_start = -1;
  11274. cvec.layer_end = -1;
  11275. return 0;
  11276. }
  11277. if (n_embd != (int) model.hparams.n_embd) {
  11278. LLAMA_LOG_ERROR("%s: control vector n_embd does not match model\n", __func__);
  11279. return 1;
  11280. }
  11281. if (cvec.tensors.empty()) {
  11282. if (!llama_control_vector_init(cvec, model)) {
  11283. return 1;
  11284. }
  11285. }
  11286. cvec.layer_start = il_start;
  11287. cvec.layer_end = il_end;
  11288. for (size_t il = 1; il < model.hparams.n_layer; il++) {
  11289. assert(cvec.tensors[il] != nullptr);
  11290. const size_t off = n_embd * (il - 1); // buffer doesn't have data for layer 0, since it's never present
  11291. if (off + n_embd <= len) {
  11292. ggml_backend_tensor_set(cvec.tensors[il], data + off, 0, n_embd * ggml_element_size(cvec.tensors[il]));
  11293. }
  11294. }
  11295. return 0;
  11296. }
  11297. struct llama_kv_cache_view llama_kv_cache_view_init(const struct llama_context * ctx, int32_t n_seq_max) {
  11298. struct llama_kv_cache_view result = {
  11299. /*.n_cells = */ 0,
  11300. /*.n_seq_max = */ n_seq_max,
  11301. /*.token_count = */ 0,
  11302. /*.used_cells = */ llama_get_kv_cache_used_cells(ctx),
  11303. /*.max_contiguous = */ 0,
  11304. /*.max_contiguous_idx = */ -1,
  11305. /*.cells = */ nullptr,
  11306. /*.cells_sequences = */ nullptr,
  11307. };
  11308. return result;
  11309. }
  11310. void llama_kv_cache_view_free(struct llama_kv_cache_view * view) {
  11311. if (view->cells != nullptr) {
  11312. free(view->cells);
  11313. view->cells = nullptr;
  11314. }
  11315. if (view->cells_sequences != nullptr) {
  11316. free(view->cells_sequences);
  11317. view->cells_sequences = nullptr;
  11318. }
  11319. }
  11320. void llama_kv_cache_view_update(const struct llama_context * ctx, struct llama_kv_cache_view * view) {
  11321. if (uint32_t(view->n_cells) < ctx->kv_self.size || view->cells == nullptr) {
  11322. view->n_cells = int32_t(ctx->kv_self.size);
  11323. void * p = realloc(view->cells, sizeof(struct llama_kv_cache_view_cell) * view->n_cells);
  11324. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells");
  11325. view->cells = (struct llama_kv_cache_view_cell *)p;
  11326. p = realloc(view->cells_sequences, sizeof(llama_seq_id) * view->n_seq_max * view->n_cells);
  11327. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells sequences");
  11328. view->cells_sequences = (llama_seq_id *)p;
  11329. }
  11330. const std::vector<llama_kv_cell> & kv_cells = ctx->kv_self.cells;
  11331. llama_kv_cache_view_cell * c_curr = view->cells;
  11332. llama_seq_id * cs_curr = view->cells_sequences;
  11333. int32_t used_cells = 0;
  11334. int32_t token_count = 0;
  11335. int32_t curr_contig_idx = -1;
  11336. uint32_t max_contig = 0;
  11337. int32_t max_contig_idx = -1;
  11338. for (int32_t i = 0; i < int32_t(ctx->kv_self.size); i++, c_curr++, cs_curr += view->n_seq_max) {
  11339. const size_t curr_size = kv_cells[i].seq_id.size();
  11340. token_count += curr_size;
  11341. c_curr->pos = kv_cells[i].pos + kv_cells[i].delta;
  11342. if (curr_size > 0) {
  11343. if (curr_contig_idx >= 0 && uint32_t(i - curr_contig_idx) > max_contig) {
  11344. max_contig = i - curr_contig_idx;
  11345. max_contig_idx = curr_contig_idx;
  11346. }
  11347. curr_contig_idx = -1;
  11348. } else if (curr_contig_idx < 0) {
  11349. curr_contig_idx = i;
  11350. }
  11351. int seq_idx = 0;
  11352. for (const llama_seq_id it : kv_cells[i].seq_id) {
  11353. if (seq_idx >= view->n_seq_max) {
  11354. break;
  11355. }
  11356. cs_curr[seq_idx] = it;
  11357. seq_idx++;
  11358. }
  11359. if (seq_idx != 0) {
  11360. used_cells++;
  11361. }
  11362. for (; seq_idx < view->n_seq_max; seq_idx++) {
  11363. cs_curr[seq_idx] = -1;
  11364. }
  11365. }
  11366. if (curr_contig_idx >= 0 && kv_cells.size() - curr_contig_idx > max_contig) {
  11367. max_contig_idx = curr_contig_idx;
  11368. max_contig = kv_cells.size() - curr_contig_idx;
  11369. }
  11370. view->max_contiguous = max_contig;
  11371. view->max_contiguous_idx = max_contig_idx;
  11372. view->token_count = token_count;
  11373. view->used_cells = used_cells;
  11374. if (uint32_t(used_cells) != ctx->kv_self.used) {
  11375. LLAMA_LOG_ERROR("%s: used cells mismatch. kv_cache says %d but we calculated %d\n",
  11376. __func__, ctx->kv_self.used, used_cells);
  11377. }
  11378. }
  11379. int32_t llama_get_kv_cache_token_count(const struct llama_context * ctx) {
  11380. int result = 0;
  11381. for (uint32_t i = 0; i < ctx->kv_self.size; i++) {
  11382. result += ctx->kv_self.cells[i].seq_id.size();
  11383. }
  11384. return result;
  11385. }
  11386. int32_t llama_get_kv_cache_used_cells(const struct llama_context * ctx) {
  11387. return ctx->kv_self.used;
  11388. }
  11389. void llama_kv_cache_clear(struct llama_context * ctx) {
  11390. llama_kv_cache_clear(ctx->kv_self);
  11391. }
  11392. bool llama_kv_cache_seq_rm(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
  11393. return llama_kv_cache_seq_rm(ctx->kv_self, seq_id, p0, p1);
  11394. }
  11395. 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) {
  11396. if (seq_id_src == seq_id_dst) {
  11397. return;
  11398. }
  11399. llama_kv_cache_seq_cp(ctx->kv_self, seq_id_src, seq_id_dst, p0, p1);
  11400. }
  11401. void llama_kv_cache_seq_keep(struct llama_context * ctx, llama_seq_id seq_id) {
  11402. llama_kv_cache_seq_keep(ctx->kv_self, seq_id);
  11403. }
  11404. void llama_kv_cache_seq_add(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos delta) {
  11405. if (delta == 0) {
  11406. return;
  11407. }
  11408. llama_kv_cache_seq_add(ctx->kv_self, seq_id, p0, p1, delta);
  11409. }
  11410. void llama_kv_cache_seq_div(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) {
  11411. if (d == 1) {
  11412. return;
  11413. }
  11414. llama_kv_cache_seq_div(ctx->kv_self, seq_id, p0, p1, d);
  11415. }
  11416. llama_pos llama_kv_cache_seq_pos_max(struct llama_context * ctx, llama_seq_id seq_id) {
  11417. return llama_kv_cache_seq_pos_max(ctx->kv_self, seq_id);
  11418. }
  11419. void llama_kv_cache_defrag(struct llama_context * ctx) {
  11420. llama_kv_cache_defrag(ctx->kv_self);
  11421. }
  11422. void llama_kv_cache_update(struct llama_context * ctx) {
  11423. llama_kv_cache_update_internal(*ctx);
  11424. }
  11425. // Returns the *maximum* size of the state
  11426. size_t llama_get_state_size(const struct llama_context * ctx) {
  11427. // we don't know size of rng until we actually serialize it. so reserve more than enough memory for its serialized state.
  11428. // for reference, std::mt19937(1337) serializes to 6701 bytes.
  11429. const size_t s_rng_size = sizeof(size_t);
  11430. const size_t s_rng = LLAMA_MAX_RNG_STATE;
  11431. const size_t s_logits_size = sizeof(size_t);
  11432. // assume worst case for logits although only currently set ones are serialized
  11433. const size_t s_logits = ctx->logits_size * sizeof(float);
  11434. const size_t s_embedding_size = sizeof(size_t);
  11435. const size_t s_embedding = ctx->embd_size * sizeof(float);
  11436. const size_t s_kv_buf_size = sizeof(size_t);
  11437. const size_t s_kv_head = sizeof(uint32_t);
  11438. const size_t s_kv_size = sizeof(uint32_t);
  11439. const size_t s_kv_used = sizeof(uint32_t);
  11440. const size_t s_kv = ctx->kv_self.total_size();
  11441. // TODO: assume the max is more than 1 seq_id per KV cell
  11442. const size_t s_kv_cell = sizeof(llama_pos) + sizeof(size_t) + sizeof(llama_seq_id);
  11443. const size_t s_kv_cells = ctx->kv_self.size * s_kv_cell;
  11444. const size_t s_total = (
  11445. + s_rng_size
  11446. + s_rng
  11447. + s_logits_size
  11448. + s_logits
  11449. + s_embedding_size
  11450. + s_embedding
  11451. + s_kv_buf_size
  11452. + s_kv_head
  11453. + s_kv_size
  11454. + s_kv_used
  11455. + s_kv
  11456. + s_kv_cells
  11457. );
  11458. return s_total;
  11459. }
  11460. // llama_context_data
  11461. struct llama_data_context {
  11462. virtual void write(const void * src, size_t size) = 0;
  11463. virtual size_t get_size_written() = 0;
  11464. virtual ~llama_data_context() = default;
  11465. };
  11466. struct llama_data_buffer_context : llama_data_context {
  11467. uint8_t * ptr;
  11468. size_t size_written = 0;
  11469. llama_data_buffer_context(uint8_t * p) : ptr(p) {}
  11470. void write(const void * src, size_t size) override {
  11471. memcpy(ptr, src, size);
  11472. ptr += size;
  11473. size_written += size;
  11474. }
  11475. size_t get_size_written() override {
  11476. return size_written;
  11477. }
  11478. };
  11479. struct llama_data_file_context : llama_data_context {
  11480. llama_file * file;
  11481. size_t size_written = 0;
  11482. llama_data_file_context(llama_file * f) : file(f) {}
  11483. void write(const void * src, size_t size) override {
  11484. file->write_raw(src, size);
  11485. size_written += size;
  11486. }
  11487. size_t get_size_written() override {
  11488. return size_written;
  11489. }
  11490. };
  11491. /** copy state data into either a buffer or file depending on the passed in context
  11492. *
  11493. * file context:
  11494. * llama_file file("/path", "wb");
  11495. * llama_data_file_context data_ctx(&file);
  11496. * llama_copy_state_data(ctx, &data_ctx);
  11497. *
  11498. * buffer context:
  11499. * std::vector<uint8_t> buf(max_size, 0);
  11500. * llama_data_buffer_context data_ctx(&buf.data());
  11501. * llama_copy_state_data(ctx, &data_ctx);
  11502. *
  11503. */
  11504. static void llama_copy_state_data_internal(struct llama_context * ctx, llama_data_context * data_ctx) {
  11505. // copy rng
  11506. {
  11507. std::ostringstream rng_ss;
  11508. rng_ss << ctx->rng;
  11509. const std::string & rng_str = rng_ss.str();
  11510. const size_t rng_size = rng_str.size();
  11511. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  11512. data_ctx->write(&rng_size, sizeof(rng_size));
  11513. data_ctx->write(rng_str.data(), rng_size);
  11514. }
  11515. // copy logits
  11516. {
  11517. const size_t logits_size = ctx->logits_size;
  11518. data_ctx->write(&logits_size, sizeof(logits_size));
  11519. if (logits_size) {
  11520. data_ctx->write(ctx->logits, logits_size * sizeof(float));
  11521. }
  11522. }
  11523. // copy embeddings
  11524. {
  11525. const size_t embeddings_size = ctx->embd_size;
  11526. data_ctx->write(&embeddings_size, sizeof(embeddings_size));
  11527. if (embeddings_size) {
  11528. data_ctx->write(ctx->embd, embeddings_size * sizeof(float));
  11529. }
  11530. }
  11531. // copy kv cache
  11532. {
  11533. const auto & kv_self = ctx->kv_self;
  11534. const auto & hparams = ctx->model.hparams;
  11535. const uint32_t n_layer = hparams.n_layer;
  11536. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  11537. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  11538. const size_t kv_buf_size = kv_self.total_size();
  11539. const uint32_t kv_head = llama_kv_cache_cell_max(kv_self);
  11540. const uint32_t kv_size = kv_self.size;
  11541. const uint32_t kv_used = kv_self.used;
  11542. data_ctx->write(&kv_buf_size, sizeof(kv_buf_size));
  11543. data_ctx->write(&kv_head, sizeof(kv_head));
  11544. data_ctx->write(&kv_size, sizeof(kv_size));
  11545. data_ctx->write(&kv_used, sizeof(kv_used));
  11546. if (kv_buf_size) {
  11547. std::vector<uint8_t> tmp_buf;
  11548. for (int il = 0; il < (int) n_layer; ++il) {
  11549. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_head);
  11550. tmp_buf.resize(k_size);
  11551. ggml_backend_tensor_get(kv_self.k_l[il], tmp_buf.data(), 0, tmp_buf.size());
  11552. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  11553. if (kv_self.recurrent) {
  11554. // v is contiguous for recurrent models
  11555. // TODO: use other tensors for state models than k and v
  11556. const size_t v_size = ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa*kv_head);
  11557. tmp_buf.resize(v_size);
  11558. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), 0, tmp_buf.size());
  11559. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  11560. continue;
  11561. }
  11562. // v is not contiguous, copy row by row
  11563. const size_t v_row_size = ggml_row_size(kv_self.v_l[il]->type, kv_head);
  11564. const size_t v_row_stride = ggml_row_size(kv_self.v_l[il]->type, kv_size);
  11565. tmp_buf.resize(v_row_size);
  11566. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  11567. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), ir*v_row_stride, tmp_buf.size());
  11568. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  11569. }
  11570. }
  11571. }
  11572. for (uint32_t i = 0; i < kv_head; ++i) {
  11573. const auto & cell = kv_self.cells[i];
  11574. const llama_pos pos = cell.pos;
  11575. const size_t seq_id_size = cell.seq_id.size();
  11576. data_ctx->write(&pos, sizeof(pos));
  11577. data_ctx->write(&seq_id_size, sizeof(seq_id_size));
  11578. for (auto seq_id : cell.seq_id) {
  11579. data_ctx->write(&seq_id, sizeof(seq_id));
  11580. }
  11581. }
  11582. }
  11583. }
  11584. size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dst) {
  11585. llama_data_buffer_context data_ctx(dst);
  11586. llama_copy_state_data_internal(ctx, &data_ctx);
  11587. return data_ctx.get_size_written();
  11588. }
  11589. // Sets the state reading from the specified source address
  11590. size_t llama_set_state_data(struct llama_context * ctx, const uint8_t * src) {
  11591. const uint8_t * inp = src;
  11592. // set rng
  11593. {
  11594. size_t rng_size;
  11595. memcpy(&rng_size, inp, sizeof(rng_size)); inp += sizeof(rng_size);
  11596. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  11597. std::string rng_str((const char *)inp, rng_size); inp += rng_size;
  11598. std::istringstream rng_ss(rng_str);
  11599. rng_ss >> ctx->rng;
  11600. GGML_ASSERT(!rng_ss.fail());
  11601. }
  11602. // set logits
  11603. {
  11604. size_t logits_size;
  11605. memcpy(&logits_size, inp, sizeof(logits_size)); inp += sizeof(logits_size);
  11606. GGML_ASSERT(ctx->logits_size >= logits_size);
  11607. if (logits_size) {
  11608. memcpy(ctx->logits, inp, logits_size * sizeof(float));
  11609. inp += logits_size * sizeof(float);
  11610. }
  11611. }
  11612. // set embeddings
  11613. {
  11614. size_t embeddings_size;
  11615. memcpy(&embeddings_size, inp, sizeof(embeddings_size)); inp += sizeof(embeddings_size);
  11616. GGML_ASSERT(ctx->embd_size == embeddings_size);
  11617. if (embeddings_size) {
  11618. memcpy(ctx->embd, inp, embeddings_size * sizeof(float));
  11619. inp += embeddings_size * sizeof(float);
  11620. }
  11621. }
  11622. // set kv cache
  11623. {
  11624. const auto & kv_self = ctx->kv_self;
  11625. const auto & hparams = ctx->model.hparams;
  11626. const uint32_t n_layer = hparams.n_layer;
  11627. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa() + hparams.n_embd_k_s();
  11628. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa() + hparams.n_embd_v_s();
  11629. size_t kv_buf_size;
  11630. uint32_t kv_head;
  11631. uint32_t kv_size;
  11632. uint32_t kv_used;
  11633. memcpy(&kv_buf_size, inp, sizeof(kv_buf_size)); inp += sizeof(kv_buf_size);
  11634. memcpy(&kv_head, inp, sizeof(kv_head)); inp += sizeof(kv_head);
  11635. memcpy(&kv_size, inp, sizeof(kv_size)); inp += sizeof(kv_size);
  11636. memcpy(&kv_used, inp, sizeof(kv_used)); inp += sizeof(kv_used);
  11637. if (kv_buf_size) {
  11638. GGML_ASSERT(kv_self.total_size() == kv_buf_size);
  11639. for (int il = 0; il < (int) n_layer; ++il) {
  11640. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_head);
  11641. ggml_backend_tensor_set(kv_self.k_l[il], inp, 0, k_size);
  11642. inp += k_size;
  11643. if (kv_self.recurrent) {
  11644. // v is contiguous for recurrent models
  11645. // TODO: use other tensors for state models than k and v
  11646. const size_t v_size = ggml_row_size(kv_self.v_l[il]->type, n_embd_v_gqa*kv_head);
  11647. ggml_backend_tensor_set(kv_self.v_l[il], inp, 0, v_size);
  11648. inp += v_size;
  11649. continue;
  11650. }
  11651. // v is not contiguous, copy row by row
  11652. const size_t v_row_size = ggml_row_size(kv_self.v_l[il]->type, kv_head);
  11653. const size_t v_row_stride = ggml_row_size(kv_self.v_l[il]->type, kv_size);
  11654. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  11655. ggml_backend_tensor_set(kv_self.v_l[il], inp, ir*v_row_stride, v_row_size);
  11656. inp += v_row_size;
  11657. }
  11658. }
  11659. }
  11660. GGML_ASSERT(kv_self.size == kv_size);
  11661. ctx->kv_self.head = kv_head;
  11662. ctx->kv_self.size = kv_size;
  11663. ctx->kv_self.used = kv_used;
  11664. ctx->kv_self.cells.resize(kv_size);
  11665. for (uint32_t i = 0; i < kv_head; ++i) {
  11666. llama_pos pos;
  11667. size_t seq_id_size;
  11668. memcpy(&pos, inp, sizeof(pos)); inp += sizeof(pos);
  11669. memcpy(&seq_id_size, inp, sizeof(seq_id_size)); inp += sizeof(seq_id_size);
  11670. ctx->kv_self.cells[i].pos = pos;
  11671. llama_seq_id seq_id;
  11672. for (size_t j = 0; j < seq_id_size; ++j) {
  11673. memcpy(&seq_id, inp, sizeof(seq_id)); inp += sizeof(seq_id);
  11674. ctx->kv_self.cells[i].seq_id.insert(seq_id);
  11675. }
  11676. }
  11677. for (uint32_t i = kv_head; i < kv_size; ++i) {
  11678. ctx->kv_self.cells[i].pos = -1;
  11679. ctx->kv_self.cells[i].seq_id.clear();
  11680. }
  11681. }
  11682. const size_t nread = inp - src;
  11683. const size_t max_size = llama_get_state_size(ctx);
  11684. GGML_ASSERT(nread <= max_size);
  11685. return nread;
  11686. }
  11687. 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) {
  11688. llama_file file(path_session, "rb");
  11689. // sanity checks
  11690. {
  11691. const uint32_t magic = file.read_u32();
  11692. const uint32_t version = file.read_u32();
  11693. if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
  11694. LLAMA_LOG_ERROR("%s : unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
  11695. return false;
  11696. }
  11697. llama_hparams session_hparams;
  11698. file.read_raw(&session_hparams, sizeof(llama_hparams));
  11699. if (session_hparams != ctx->model.hparams) {
  11700. LLAMA_LOG_INFO("%s : model hparams didn't match from session file!\n", __func__);
  11701. return false;
  11702. }
  11703. }
  11704. // load the prompt
  11705. {
  11706. const uint32_t n_token_count = file.read_u32();
  11707. if (n_token_count > n_token_capacity) {
  11708. LLAMA_LOG_ERROR("%s : token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  11709. return false;
  11710. }
  11711. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  11712. *n_token_count_out = n_token_count;
  11713. }
  11714. // restore the context state
  11715. {
  11716. const size_t n_state_size_cur = file.size - file.tell();
  11717. const size_t n_state_size_max = llama_get_state_size(ctx);
  11718. if (n_state_size_cur > n_state_size_max) {
  11719. 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);
  11720. return false;
  11721. }
  11722. std::vector<uint8_t> state_data(n_state_size_max);
  11723. file.read_raw(state_data.data(), n_state_size_cur);
  11724. llama_set_state_data(ctx, state_data.data());
  11725. }
  11726. return true;
  11727. }
  11728. 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) {
  11729. try {
  11730. return llama_load_session_file_internal(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  11731. } catch (const std::exception & err) {
  11732. LLAMA_LOG_ERROR("error loading session file: %s\n", err.what());
  11733. return false;
  11734. }
  11735. }
  11736. bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  11737. llama_file file(path_session, "wb");
  11738. file.write_u32(LLAMA_SESSION_MAGIC);
  11739. file.write_u32(LLAMA_SESSION_VERSION);
  11740. file.write_raw(&ctx->model.hparams, sizeof(llama_hparams));
  11741. // save the prompt
  11742. file.write_u32((uint32_t) n_token_count);
  11743. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  11744. // save the context state using stream saving
  11745. llama_data_file_context data_ctx(&file);
  11746. llama_copy_state_data_internal(ctx, &data_ctx);
  11747. return true;
  11748. }
  11749. void llama_set_n_threads(struct llama_context * ctx, uint32_t n_threads, uint32_t n_threads_batch) {
  11750. ctx->cparams.n_threads = n_threads;
  11751. ctx->cparams.n_threads_batch = n_threads_batch;
  11752. }
  11753. void llama_set_abort_callback(struct llama_context * ctx, bool (*abort_callback)(void * data), void * abort_callback_data) {
  11754. ctx->abort_callback = abort_callback;
  11755. ctx->abort_callback_data = abort_callback_data;
  11756. }
  11757. void llama_set_causal_attn(struct llama_context * ctx, bool causal_attn) {
  11758. ctx->cparams.causal_attn = causal_attn;
  11759. }
  11760. struct llama_batch llama_batch_get_one(
  11761. llama_token * tokens,
  11762. int32_t n_tokens,
  11763. llama_pos pos_0,
  11764. llama_seq_id seq_id) {
  11765. return {
  11766. /*n_tokens =*/ n_tokens,
  11767. /*tokens =*/ tokens,
  11768. /*embd =*/ nullptr,
  11769. /*pos =*/ nullptr,
  11770. /*n_seq_id =*/ nullptr,
  11771. /*seq_id =*/ nullptr,
  11772. /*logits =*/ nullptr,
  11773. /*all_pos_0 =*/ pos_0,
  11774. /*all_pos_1 =*/ 1,
  11775. /*all_seq_id =*/ seq_id,
  11776. };
  11777. }
  11778. struct llama_batch llama_batch_init(int32_t n_tokens_alloc, int32_t embd, int32_t n_seq_max) {
  11779. llama_batch batch = { 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, 0, 0, 0, };
  11780. if (embd) {
  11781. batch.embd = (float *) malloc(sizeof(float) * n_tokens_alloc * embd);
  11782. } else {
  11783. batch.token = (llama_token *) malloc(sizeof(llama_token) * n_tokens_alloc);
  11784. }
  11785. batch.pos = (llama_pos *) malloc(sizeof(llama_pos) * n_tokens_alloc);
  11786. batch.n_seq_id = (int32_t *) malloc(sizeof(int32_t) * n_tokens_alloc);
  11787. batch.seq_id = (llama_seq_id **) malloc(sizeof(llama_seq_id *) * (n_tokens_alloc + 1));
  11788. for (int i = 0; i < n_tokens_alloc; ++i) {
  11789. batch.seq_id[i] = (llama_seq_id *) malloc(sizeof(llama_seq_id) * n_seq_max);
  11790. }
  11791. batch.seq_id[n_tokens_alloc] = nullptr;
  11792. batch.logits = (int8_t *) malloc(sizeof(int8_t) * n_tokens_alloc);
  11793. return batch;
  11794. }
  11795. void llama_batch_free(struct llama_batch batch) {
  11796. if (batch.token) free(batch.token);
  11797. if (batch.embd) free(batch.embd);
  11798. if (batch.pos) free(batch.pos);
  11799. if (batch.n_seq_id) free(batch.n_seq_id);
  11800. if (batch.seq_id) {
  11801. for (int i = 0; batch.seq_id[i] != nullptr; ++i) {
  11802. free(batch.seq_id[i]);
  11803. }
  11804. free(batch.seq_id);
  11805. }
  11806. if (batch.logits) free(batch.logits);
  11807. }
  11808. int32_t llama_decode(
  11809. struct llama_context * ctx,
  11810. struct llama_batch batch) {
  11811. const int ret = llama_decode_internal(*ctx, batch);
  11812. if (ret < 0) {
  11813. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  11814. }
  11815. return ret;
  11816. }
  11817. void llama_synchronize(struct llama_context * ctx) {
  11818. ggml_backend_sched_synchronize(ctx->sched);
  11819. // FIXME: if multiple single tokens are evaluated without a synchronization,
  11820. // the stats will be added to the prompt evaluation stats
  11821. // this should only happen when using batch size 1 to evaluate a batch
  11822. // add the evaluation to the stats
  11823. if (ctx->n_queued_tokens == 1) {
  11824. ctx->t_eval_us += ggml_time_us() - ctx->t_compute_start_us;
  11825. ctx->n_eval++;
  11826. } else if (ctx->n_queued_tokens > 1) {
  11827. ctx->t_p_eval_us += ggml_time_us() - ctx->t_compute_start_us;
  11828. ctx->n_p_eval += ctx->n_queued_tokens;
  11829. }
  11830. // get a more accurate load time, upon first eval
  11831. if (ctx->n_queued_tokens > 0 && !ctx->has_evaluated_once) {
  11832. ctx->t_load_us = ggml_time_us() - ctx->t_start_us;
  11833. ctx->has_evaluated_once = true;
  11834. }
  11835. ctx->n_queued_tokens = 0;
  11836. ctx->t_compute_start_us = 0;
  11837. }
  11838. float * llama_get_logits(struct llama_context * ctx) {
  11839. llama_synchronize(ctx);
  11840. return ctx->logits;
  11841. }
  11842. float * llama_get_logits_ith(struct llama_context * ctx, int32_t i) {
  11843. assert(ctx->logits_valid.at(i));
  11844. llama_synchronize(ctx);
  11845. return ctx->logits + i*ctx->model.hparams.n_vocab;
  11846. }
  11847. float * llama_get_embeddings(struct llama_context * ctx) {
  11848. llama_synchronize(ctx);
  11849. return ctx->embd;
  11850. }
  11851. float * llama_get_embeddings_ith(struct llama_context * ctx, int32_t i) {
  11852. llama_synchronize(ctx);
  11853. return ctx->embd + i*ctx->model.hparams.n_embd;
  11854. }
  11855. float * llama_get_embeddings_seq(struct llama_context * ctx, llama_seq_id seq_id) {
  11856. llama_synchronize(ctx);
  11857. auto it = ctx->embd_seq.find(seq_id);
  11858. if (it == ctx->embd_seq.end()) {
  11859. return nullptr;
  11860. }
  11861. return it->second.data();
  11862. }
  11863. const char * llama_token_get_text(const struct llama_model * model, llama_token token) {
  11864. GGML_ASSERT(model->vocab.type != LLAMA_VOCAB_TYPE_NONE);
  11865. return model->vocab.id_to_token[token].text.c_str();
  11866. }
  11867. float llama_token_get_score(const struct llama_model * model, llama_token token) {
  11868. GGML_ASSERT(model->vocab.type != LLAMA_VOCAB_TYPE_NONE);
  11869. return model->vocab.id_to_token[token].score;
  11870. }
  11871. llama_token_type llama_token_get_type(const struct llama_model * model, llama_token token) {
  11872. GGML_ASSERT(model->vocab.type != LLAMA_VOCAB_TYPE_NONE);
  11873. return model->vocab.id_to_token[token].type;
  11874. }
  11875. llama_token llama_token_bos(const struct llama_model * model) {
  11876. return model->vocab.special_bos_id;
  11877. }
  11878. llama_token llama_token_eos(const struct llama_model * model) {
  11879. return model->vocab.special_eos_id;
  11880. }
  11881. llama_token llama_token_nl(const struct llama_model * model) {
  11882. return model->vocab.linefeed_id;
  11883. }
  11884. int32_t llama_add_bos_token(const struct llama_model * model) {
  11885. return model->vocab.special_add_bos;
  11886. }
  11887. int32_t llama_add_eos_token(const struct llama_model * model) {
  11888. return model->vocab.special_add_eos;
  11889. }
  11890. llama_token llama_token_prefix(const struct llama_model * model) {
  11891. return model->vocab.special_prefix_id;
  11892. }
  11893. llama_token llama_token_middle(const struct llama_model * model) {
  11894. return model->vocab.special_middle_id;
  11895. }
  11896. llama_token llama_token_suffix(const struct llama_model * model) {
  11897. return model->vocab.special_suffix_id;
  11898. }
  11899. llama_token llama_token_eot(const struct llama_model * model) {
  11900. return model->vocab.special_eot_id;
  11901. }
  11902. int32_t llama_tokenize(
  11903. const struct llama_model * model,
  11904. const char * text,
  11905. int32_t text_len,
  11906. llama_token * tokens,
  11907. int32_t n_tokens_max,
  11908. bool add_bos,
  11909. bool special) {
  11910. auto res = llama_tokenize_internal(model->vocab, std::string(text, text_len), add_bos, special);
  11911. if (n_tokens_max < (int) res.size()) {
  11912. // LLAMA_LOG_ERROR("%s: too many tokens\n", __func__);
  11913. return -((int) res.size());
  11914. }
  11915. for (size_t i = 0; i < res.size(); i++) {
  11916. tokens[i] = res[i];
  11917. }
  11918. return res.size();
  11919. }
  11920. static std::string llama_decode_text(const std::string & text) {
  11921. std::string decoded_text;
  11922. auto unicode_sequences = unicode_cpts_from_utf8(text);
  11923. for (auto & unicode_sequence : unicode_sequences) {
  11924. decoded_text += unicode_utf8_to_byte(unicode_cpt_to_utf8(unicode_sequence));
  11925. }
  11926. return decoded_text;
  11927. }
  11928. // does not write null-terminator to buf
  11929. int32_t llama_token_to_piece(const struct llama_model * model, llama_token token, char * buf, int32_t length) {
  11930. if (0 <= token && token < llama_n_vocab(model)) {
  11931. switch (llama_vocab_get_type(model->vocab)) {
  11932. case LLAMA_VOCAB_TYPE_WPM:
  11933. case LLAMA_VOCAB_TYPE_SPM: {
  11934. // NOTE: we accept all unsupported token types,
  11935. // suppressing them like CONTROL tokens.
  11936. if (llama_is_normal_token(model->vocab, token)) {
  11937. std::string result = model->vocab.id_to_token[token].text;
  11938. llama_unescape_whitespace(result);
  11939. if (length < (int) result.length()) {
  11940. return -(int) result.length();
  11941. }
  11942. memcpy(buf, result.c_str(), result.length());
  11943. return result.length();
  11944. } else if (llama_is_user_defined_token(model->vocab, token)) {
  11945. std::string result = model->vocab.id_to_token[token].text;
  11946. if (length < (int) result.length()) {
  11947. return -(int) result.length();
  11948. }
  11949. memcpy(buf, result.c_str(), result.length());
  11950. return result.length();
  11951. } else if (llama_is_unknown_token(model->vocab, token)) { // NOLINT
  11952. if (length < 3) {
  11953. return -3;
  11954. }
  11955. memcpy(buf, "\xe2\x96\x85", 3);
  11956. return 3;
  11957. } else if (llama_is_control_token(model->vocab, token)) {
  11958. ;
  11959. } else if (llama_is_byte_token(model->vocab, token)) {
  11960. if (length < 1) {
  11961. return -1;
  11962. }
  11963. buf[0] = llama_token_to_byte(model->vocab, token);
  11964. return 1;
  11965. }
  11966. break;
  11967. }
  11968. case LLAMA_VOCAB_TYPE_BPE: {
  11969. // NOTE: we accept all unsupported token types,
  11970. // suppressing them like CONTROL tokens.
  11971. if (llama_is_normal_token(model->vocab, token)) {
  11972. std::string result = model->vocab.id_to_token[token].text;
  11973. result = llama_decode_text(result);
  11974. if (length < (int) result.length()) {
  11975. return -(int) result.length();
  11976. }
  11977. memcpy(buf, result.c_str(), result.length());
  11978. return result.length();
  11979. } else if (llama_is_user_defined_token(model->vocab, token)) {
  11980. std::string result = model->vocab.id_to_token[token].text;
  11981. if (length < (int) result.length()) {
  11982. return -(int) result.length();
  11983. }
  11984. memcpy(buf, result.c_str(), result.length());
  11985. return result.length();
  11986. } else if (llama_is_control_token(model->vocab, token)) {
  11987. ;
  11988. }
  11989. break;
  11990. }
  11991. default:
  11992. GGML_ASSERT(false);
  11993. }
  11994. }
  11995. return 0;
  11996. }
  11997. // trim whitespace from the beginning and end of a string
  11998. static std::string trim(const std::string & str) {
  11999. size_t start = 0;
  12000. size_t end = str.size();
  12001. while (start < end && isspace(str[start])) {
  12002. start += 1;
  12003. }
  12004. while (end > start && isspace(str[end - 1])) {
  12005. end -= 1;
  12006. }
  12007. return str.substr(start, end - start);
  12008. }
  12009. // Simple version of "llama_apply_chat_template" that only works with strings
  12010. // This function uses heuristic checks to determine commonly used template. It is not a jinja parser.
  12011. static int32_t llama_chat_apply_template_internal(
  12012. const std::string & tmpl,
  12013. const std::vector<const llama_chat_message *> & chat,
  12014. std::string & dest, bool add_ass) {
  12015. // Taken from the research: https://github.com/ggerganov/llama.cpp/issues/5527
  12016. std::stringstream ss;
  12017. if (tmpl == "chatml" || tmpl.find("<|im_start|>") != std::string::npos) {
  12018. // chatml template
  12019. for (auto message : chat) {
  12020. ss << "<|im_start|>" << message->role << "\n" << message->content << "<|im_end|>\n";
  12021. }
  12022. if (add_ass) {
  12023. ss << "<|im_start|>assistant\n";
  12024. }
  12025. } else if (tmpl == "llama2" || tmpl.find("[INST]") != std::string::npos) {
  12026. // llama2 template and its variants
  12027. // [variant] support system message
  12028. bool support_system_message = tmpl.find("<<SYS>>") != std::string::npos;
  12029. // [variant] space before + after response
  12030. bool space_around_response = tmpl.find("' ' + eos_token") != std::string::npos;
  12031. // [variant] add BOS inside history
  12032. bool add_bos_inside_history = tmpl.find("bos_token + '[INST]") != std::string::npos;
  12033. // [variant] trim spaces from the input message
  12034. bool strip_message = tmpl.find("content.strip()") != std::string::npos;
  12035. // construct the prompt
  12036. bool is_inside_turn = true; // skip BOS at the beginning
  12037. ss << "[INST] ";
  12038. for (auto message : chat) {
  12039. std::string content = strip_message ? trim(message->content) : message->content;
  12040. std::string role(message->role);
  12041. if (!is_inside_turn) {
  12042. is_inside_turn = true;
  12043. ss << (add_bos_inside_history ? "<s>[INST] " : "[INST] ");
  12044. }
  12045. if (role == "system") {
  12046. if (support_system_message) {
  12047. ss << "<<SYS>>\n" << content << "\n<</SYS>>\n\n";
  12048. } else {
  12049. // if the model does not support system message, we still include it in the first message, but without <<SYS>>
  12050. ss << content << "\n";
  12051. }
  12052. } else if (role == "user") {
  12053. ss << content << " [/INST]";
  12054. } else {
  12055. ss << (space_around_response ? " " : "") << content << (space_around_response ? " " : "") << "</s>";
  12056. is_inside_turn = false;
  12057. }
  12058. }
  12059. // llama2 templates seem to not care about "add_generation_prompt"
  12060. } else if (tmpl == "zephyr" || tmpl.find("<|user|>") != std::string::npos) {
  12061. // zephyr template
  12062. for (auto message : chat) {
  12063. ss << "<|" << message->role << "|>" << "\n" << message->content << "<|endoftext|>\n";
  12064. }
  12065. if (add_ass) {
  12066. ss << "<|assistant|>\n";
  12067. }
  12068. } else if (tmpl == "monarch" || tmpl.find("bos_token + message['role']") != std::string::npos) {
  12069. // mlabonne/AlphaMonarch-7B template (the <s> is included inside history)
  12070. for (auto message : chat) {
  12071. std::string bos = (message == chat.front()) ? "" : "<s>"; // skip BOS for first message
  12072. ss << bos << message->role << "\n" << message->content << "</s>\n";
  12073. }
  12074. if (add_ass) {
  12075. ss << "<s>assistant\n";
  12076. }
  12077. } else if (tmpl == "gemma" || tmpl.find("<start_of_turn>") != std::string::npos) {
  12078. // google/gemma-7b-it
  12079. std::string system_prompt = "";
  12080. for (auto message : chat) {
  12081. std::string role(message->role);
  12082. if (role == "system") {
  12083. // there is no system message for gemma, but we will merge it with user prompt, so nothing is broken
  12084. system_prompt = trim(message->content);
  12085. continue;
  12086. }
  12087. // in gemma, "assistant" is "model"
  12088. role = role == "assistant" ? "model" : message->role;
  12089. ss << "<start_of_turn>" << role << "\n";
  12090. if (!system_prompt.empty() && role != "model") {
  12091. ss << system_prompt << "\n\n";
  12092. system_prompt = "";
  12093. }
  12094. ss << trim(message->content) << "<end_of_turn>\n";
  12095. }
  12096. if (add_ass) {
  12097. ss << "<start_of_turn>model\n";
  12098. }
  12099. } else if (tmpl == "orion" || tmpl.find("'\\n\\nAssistant: ' + eos_token") != std::string::npos) {
  12100. // OrionStarAI/Orion-14B-Chat
  12101. std::string system_prompt = "";
  12102. for (auto message : chat) {
  12103. std::string role(message->role);
  12104. if (role == "system") {
  12105. // there is no system message support, we will merge it with user prompt
  12106. system_prompt = message->content;
  12107. continue;
  12108. } else if (role == "user") {
  12109. ss << "Human: ";
  12110. if (!system_prompt.empty()) {
  12111. ss << system_prompt << "\n\n";
  12112. system_prompt = "";
  12113. }
  12114. ss << message->content << "\n\nAssistant: </s>";
  12115. } else {
  12116. ss << message->content << "</s>";
  12117. }
  12118. }
  12119. } else {
  12120. // template not supported
  12121. return -1;
  12122. }
  12123. dest = ss.str();
  12124. return dest.size();
  12125. }
  12126. LLAMA_API int32_t llama_chat_apply_template(
  12127. const struct llama_model * model,
  12128. const char * tmpl,
  12129. const struct llama_chat_message * chat,
  12130. size_t n_msg,
  12131. bool add_ass,
  12132. char * buf,
  12133. int32_t length) {
  12134. std::string curr_tmpl(tmpl == nullptr ? "" : tmpl);
  12135. if (tmpl == nullptr) {
  12136. GGML_ASSERT(model != nullptr);
  12137. // load template from model
  12138. std::vector<char> model_template(2048, 0); // longest known template is about 1200 bytes
  12139. std::string template_key = "tokenizer.chat_template";
  12140. int32_t res = llama_model_meta_val_str(model, template_key.c_str(), model_template.data(), model_template.size());
  12141. if (res < 0) {
  12142. // worst case: there is no information about template, we will use chatml by default
  12143. curr_tmpl = "chatml"; // see llama_chat_apply_template_internal
  12144. } else {
  12145. curr_tmpl = std::string(model_template.data(), model_template.size());
  12146. }
  12147. }
  12148. // format the chat to string
  12149. std::vector<const llama_chat_message *> chat_vec;
  12150. chat_vec.resize(n_msg);
  12151. for (size_t i = 0; i < n_msg; i++) {
  12152. chat_vec[i] = &chat[i];
  12153. }
  12154. std::string formatted_chat;
  12155. int32_t res = llama_chat_apply_template_internal(curr_tmpl, chat_vec, formatted_chat, add_ass);
  12156. if (res < 0) {
  12157. return res;
  12158. }
  12159. if (buf && length > 0) {
  12160. strncpy(buf, formatted_chat.c_str(), length);
  12161. }
  12162. return res;
  12163. }
  12164. struct llama_timings llama_get_timings(struct llama_context * ctx) {
  12165. struct llama_timings result = {
  12166. /*.t_start_ms =*/ 1e-3 * ctx->t_start_us,
  12167. /*.t_end_ms =*/ 1.00 * ggml_time_ms(),
  12168. /*.t_load_ms =*/ 1e-3 * ctx->t_load_us,
  12169. /*.t_sample_ms =*/ 1e-3 * ctx->t_sample_us,
  12170. /*.t_p_eval_ms =*/ 1e-3 * ctx->t_p_eval_us,
  12171. /*.t_eval_ms =*/ 1e-3 * ctx->t_eval_us,
  12172. /*.n_sample =*/ std::max(1, ctx->n_sample),
  12173. /*.n_p_eval =*/ std::max(1, ctx->n_p_eval),
  12174. /*.n_eval =*/ std::max(1, ctx->n_eval),
  12175. };
  12176. return result;
  12177. }
  12178. void llama_print_timings(struct llama_context * ctx) {
  12179. const llama_timings timings = llama_get_timings(ctx);
  12180. LLAMA_LOG_INFO("\n");
  12181. LLAMA_LOG_INFO("%s: load time = %10.2f ms\n", __func__, timings.t_load_ms);
  12182. LLAMA_LOG_INFO("%s: sample time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  12183. __func__, timings.t_sample_ms, timings.n_sample, timings.t_sample_ms / timings.n_sample, 1e3 / timings.t_sample_ms * timings.n_sample);
  12184. LLAMA_LOG_INFO("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  12185. __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);
  12186. LLAMA_LOG_INFO("%s: eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  12187. __func__, timings.t_eval_ms, timings.n_eval, timings.t_eval_ms / timings.n_eval, 1e3 / timings.t_eval_ms * timings.n_eval);
  12188. 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));
  12189. }
  12190. void llama_reset_timings(struct llama_context * ctx) {
  12191. ctx->t_start_us = ggml_time_us();
  12192. ctx->t_sample_us = ctx->n_sample = 0;
  12193. ctx->t_eval_us = ctx->n_eval = 0;
  12194. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  12195. }
  12196. const char * llama_print_system_info(void) {
  12197. static std::string s;
  12198. s = "";
  12199. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  12200. s += "AVX_VNNI = " + std::to_string(ggml_cpu_has_avx_vnni()) + " | ";
  12201. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  12202. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  12203. s += "AVX512_VBMI = " + std::to_string(ggml_cpu_has_avx512_vbmi()) + " | ";
  12204. s += "AVX512_VNNI = " + std::to_string(ggml_cpu_has_avx512_vnni()) + " | ";
  12205. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  12206. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  12207. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  12208. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  12209. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  12210. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  12211. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  12212. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  12213. s += "SSSE3 = " + std::to_string(ggml_cpu_has_ssse3()) + " | ";
  12214. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  12215. s += "MATMUL_INT8 = " + std::to_string(ggml_cpu_has_matmul_int8()) + " | ";
  12216. return s.c_str();
  12217. }
  12218. void llama_dump_timing_info_yaml(FILE * stream, const llama_context * ctx) {
  12219. fprintf(stream, "\n");
  12220. fprintf(stream, "###########\n");
  12221. fprintf(stream, "# Timings #\n");
  12222. fprintf(stream, "###########\n");
  12223. fprintf(stream, "\n");
  12224. fprintf(stream, "mst_eval: %.2f # ms / token during generation\n",
  12225. 1.0e-3 * ctx->t_eval_us / ctx->n_eval);
  12226. fprintf(stream, "mst_p_eval: %.2f # ms / token during prompt processing\n",
  12227. 1.0e-3 * ctx->t_p_eval_us / ctx->n_p_eval);
  12228. fprintf(stream, "mst_sample: %.2f # ms / token during sampling\n",
  12229. 1.0e-3 * ctx->t_sample_us / ctx->n_sample);
  12230. fprintf(stream, "n_eval: %d # number of tokens generated (excluding the first one)\n", ctx->n_eval);
  12231. fprintf(stream, "n_p_eval: %d # number of tokens processed in batches at the beginning\n", ctx->n_p_eval);
  12232. fprintf(stream, "n_sample: %d # number of sampled tokens\n", ctx->n_sample);
  12233. fprintf(stream, "t_eval_us: %" PRId64 " # total microseconds spent generating tokens\n", ctx->t_eval_us);
  12234. fprintf(stream, "t_load_us: %" PRId64 " # total microseconds spent loading the model\n", ctx->t_load_us);
  12235. fprintf(stream, "t_p_eval_us: %" PRId64 " # total microseconds spent prompt processing\n", ctx->t_p_eval_us);
  12236. fprintf(stream, "t_sample_us: %" PRId64 " # total microseconds spent sampling\n", ctx->t_sample_us);
  12237. fprintf(stream, "ts_eval: %.2f # tokens / second during generation\n",
  12238. 1.0e6 * ctx->n_eval / ctx->t_eval_us);
  12239. fprintf(stream, "ts_p_eval: %.2f # tokens / second during prompt processing\n",
  12240. 1.0e6 * ctx->n_p_eval / ctx->t_p_eval_us);
  12241. fprintf(stream, "ts_sample: %.2f # tokens / second during sampling\n",
  12242. 1.0e6 * ctx->n_sample / ctx->t_sample_us);
  12243. }
  12244. // For internal test use
  12245. const std::vector<std::pair<std::string, struct ggml_tensor *>> & llama_internal_get_tensor_map(
  12246. struct llama_context * ctx
  12247. ) {
  12248. return ctx->model.tensors_by_name;
  12249. }
  12250. void llama_log_set(ggml_log_callback log_callback, void * user_data) {
  12251. g_state.log_callback = log_callback ? log_callback : llama_log_callback_default;
  12252. g_state.log_callback_user_data = user_data;
  12253. #ifdef GGML_USE_METAL
  12254. ggml_backend_metal_log_set_callback(g_state.log_callback, g_state.log_callback_user_data);
  12255. #endif
  12256. }
  12257. static void llama_log_internal_v(ggml_log_level level, const char * format, va_list args) {
  12258. va_list args_copy;
  12259. va_copy(args_copy, args);
  12260. char buffer[128];
  12261. int len = vsnprintf(buffer, 128, format, args);
  12262. if (len < 128) {
  12263. g_state.log_callback(level, buffer, g_state.log_callback_user_data);
  12264. } else {
  12265. char* buffer2 = new char[len+1];
  12266. vsnprintf(buffer2, len+1, format, args_copy);
  12267. buffer2[len] = 0;
  12268. g_state.log_callback(level, buffer2, g_state.log_callback_user_data);
  12269. delete[] buffer2;
  12270. }
  12271. va_end(args_copy);
  12272. }
  12273. static void llama_log_internal(ggml_log_level level, const char * format, ...) {
  12274. va_list args;
  12275. va_start(args, format);
  12276. llama_log_internal_v(level, format, args);
  12277. va_end(args);
  12278. }
  12279. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data) {
  12280. (void) level;
  12281. (void) user_data;
  12282. fputs(text, stderr);
  12283. fflush(stderr);
  12284. }