llama.cpp 451 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723
  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 <forward_list>
  65. #include <fstream>
  66. #include <functional>
  67. #include <initializer_list>
  68. #include <map>
  69. #include <memory>
  70. #include <mutex>
  71. #include <numeric>
  72. #include <queue>
  73. #include <random>
  74. #include <regex>
  75. #include <set>
  76. #include <sstream>
  77. #include <thread>
  78. #include <type_traits>
  79. #include <unordered_map>
  80. #if defined(_MSC_VER)
  81. #pragma warning(disable: 4244 4267) // possible loss of data
  82. #endif
  83. #ifdef __GNUC__
  84. #ifdef __MINGW32__
  85. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(gnu_printf, __VA_ARGS__)))
  86. #else
  87. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(printf, __VA_ARGS__)))
  88. #endif
  89. #else
  90. #define LLAMA_ATTRIBUTE_FORMAT(...)
  91. #endif
  92. #define LLAMA_MAX_NODES 8192
  93. #define LLAMA_MAX_EXPERTS 8
  94. //
  95. // logging
  96. //
  97. LLAMA_ATTRIBUTE_FORMAT(2, 3)
  98. static void llama_log_internal (ggml_log_level level, const char* format, ...);
  99. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data);
  100. #define LLAMA_LOG_INFO(...) llama_log_internal(GGML_LOG_LEVEL_INFO , __VA_ARGS__)
  101. #define LLAMA_LOG_WARN(...) llama_log_internal(GGML_LOG_LEVEL_WARN , __VA_ARGS__)
  102. #define LLAMA_LOG_ERROR(...) llama_log_internal(GGML_LOG_LEVEL_ERROR, __VA_ARGS__)
  103. //
  104. // helpers
  105. //
  106. static size_t utf8_len(char src) {
  107. const size_t lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4 };
  108. uint8_t highbits = static_cast<uint8_t>(src) >> 4;
  109. return lookup[highbits];
  110. }
  111. static void replace_all(std::string & s, const std::string & search, const std::string & replace) {
  112. std::string result;
  113. for (size_t pos = 0; ; pos += search.length()) {
  114. auto new_pos = s.find(search, pos);
  115. if (new_pos == std::string::npos) {
  116. result += s.substr(pos, s.size() - pos);
  117. break;
  118. }
  119. result += s.substr(pos, new_pos - pos) + replace;
  120. pos = new_pos;
  121. }
  122. s = std::move(result);
  123. }
  124. static bool is_float_close(float a, float b, float abs_tol) {
  125. // Check for non-negative tolerance
  126. if (abs_tol < 0.0) {
  127. throw std::invalid_argument("Tolerance must be non-negative");
  128. }
  129. // Exact equality check
  130. if (a == b) {
  131. return true;
  132. }
  133. // Check for infinities
  134. if (std::isinf(a) || std::isinf(b)) {
  135. return false;
  136. }
  137. // Regular comparison using the provided absolute tolerance
  138. return std::fabs(b - a) <= abs_tol;
  139. }
  140. static void zeros(std::ofstream & file, size_t n) {
  141. char zero = 0;
  142. for (size_t i = 0; i < n; ++i) {
  143. file.write(&zero, 1);
  144. }
  145. }
  146. LLAMA_ATTRIBUTE_FORMAT(1, 2)
  147. static std::string format(const char * fmt, ...) {
  148. va_list ap;
  149. va_list ap2;
  150. va_start(ap, fmt);
  151. va_copy(ap2, ap);
  152. int size = vsnprintf(NULL, 0, fmt, ap);
  153. GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
  154. std::vector<char> buf(size + 1);
  155. int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
  156. GGML_ASSERT(size2 == size);
  157. va_end(ap2);
  158. va_end(ap);
  159. return std::string(buf.data(), size);
  160. }
  161. //
  162. // gguf constants (sync with gguf.py)
  163. //
  164. enum llm_arch {
  165. LLM_ARCH_LLAMA,
  166. LLM_ARCH_FALCON,
  167. LLM_ARCH_BAICHUAN,
  168. LLM_ARCH_GPT2,
  169. LLM_ARCH_GPTJ,
  170. LLM_ARCH_GPTNEOX,
  171. LLM_ARCH_MPT,
  172. LLM_ARCH_STARCODER,
  173. LLM_ARCH_PERSIMMON,
  174. LLM_ARCH_REFACT,
  175. LLM_ARCH_BLOOM,
  176. LLM_ARCH_STABLELM,
  177. LLM_ARCH_QWEN,
  178. LLM_ARCH_QWEN2,
  179. LLM_ARCH_PHI2,
  180. LLM_ARCH_PLAMO,
  181. LLM_ARCH_CODESHELL,
  182. LLM_ARCH_ORION,
  183. LLM_ARCH_INTERNLM2,
  184. LLM_ARCH_UNKNOWN,
  185. };
  186. static std::map<llm_arch, const char *> LLM_ARCH_NAMES = {
  187. { LLM_ARCH_LLAMA, "llama" },
  188. { LLM_ARCH_FALCON, "falcon" },
  189. { LLM_ARCH_GPT2, "gpt2" },
  190. { LLM_ARCH_GPTJ, "gptj" },
  191. { LLM_ARCH_GPTNEOX, "gptneox" },
  192. { LLM_ARCH_MPT, "mpt" },
  193. { LLM_ARCH_BAICHUAN, "baichuan" },
  194. { LLM_ARCH_STARCODER, "starcoder" },
  195. { LLM_ARCH_PERSIMMON, "persimmon" },
  196. { LLM_ARCH_REFACT, "refact" },
  197. { LLM_ARCH_BLOOM, "bloom" },
  198. { LLM_ARCH_STABLELM, "stablelm" },
  199. { LLM_ARCH_QWEN, "qwen" },
  200. { LLM_ARCH_QWEN2, "qwen2" },
  201. { LLM_ARCH_PHI2, "phi2" },
  202. { LLM_ARCH_PLAMO, "plamo" },
  203. { LLM_ARCH_CODESHELL, "codeshell" },
  204. { LLM_ARCH_ORION, "orion" },
  205. { LLM_ARCH_INTERNLM2, "internlm2" },
  206. };
  207. enum llm_kv {
  208. LLM_KV_GENERAL_ARCHITECTURE,
  209. LLM_KV_GENERAL_QUANTIZATION_VERSION,
  210. LLM_KV_GENERAL_ALIGNMENT,
  211. LLM_KV_GENERAL_NAME,
  212. LLM_KV_GENERAL_AUTHOR,
  213. LLM_KV_GENERAL_URL,
  214. LLM_KV_GENERAL_DESCRIPTION,
  215. LLM_KV_GENERAL_LICENSE,
  216. LLM_KV_GENERAL_SOURCE_URL,
  217. LLM_KV_GENERAL_SOURCE_HF_REPO,
  218. LLM_KV_CONTEXT_LENGTH,
  219. LLM_KV_EMBEDDING_LENGTH,
  220. LLM_KV_BLOCK_COUNT,
  221. LLM_KV_FEED_FORWARD_LENGTH,
  222. LLM_KV_USE_PARALLEL_RESIDUAL,
  223. LLM_KV_TENSOR_DATA_LAYOUT,
  224. LLM_KV_EXPERT_COUNT,
  225. LLM_KV_EXPERT_USED_COUNT,
  226. LLM_KV_ATTENTION_HEAD_COUNT,
  227. LLM_KV_ATTENTION_HEAD_COUNT_KV,
  228. LLM_KV_ATTENTION_MAX_ALIBI_BIAS,
  229. LLM_KV_ATTENTION_CLAMP_KQV,
  230. LLM_KV_ATTENTION_KEY_LENGTH,
  231. LLM_KV_ATTENTION_VALUE_LENGTH,
  232. LLM_KV_ATTENTION_LAYERNORM_EPS,
  233. LLM_KV_ATTENTION_LAYERNORM_RMS_EPS,
  234. LLM_KV_ROPE_DIMENSION_COUNT,
  235. LLM_KV_ROPE_FREQ_BASE,
  236. LLM_KV_ROPE_SCALE_LINEAR,
  237. LLM_KV_ROPE_SCALING_TYPE,
  238. LLM_KV_ROPE_SCALING_FACTOR,
  239. LLM_KV_ROPE_SCALING_ORIG_CTX_LEN,
  240. LLM_KV_ROPE_SCALING_FINETUNED,
  241. LLM_KV_TOKENIZER_MODEL,
  242. LLM_KV_TOKENIZER_LIST,
  243. LLM_KV_TOKENIZER_TOKEN_TYPE,
  244. LLM_KV_TOKENIZER_SCORES,
  245. LLM_KV_TOKENIZER_MERGES,
  246. LLM_KV_TOKENIZER_BOS_ID,
  247. LLM_KV_TOKENIZER_EOS_ID,
  248. LLM_KV_TOKENIZER_UNK_ID,
  249. LLM_KV_TOKENIZER_SEP_ID,
  250. LLM_KV_TOKENIZER_PAD_ID,
  251. LLM_KV_TOKENIZER_ADD_BOS,
  252. LLM_KV_TOKENIZER_ADD_EOS,
  253. LLM_KV_TOKENIZER_ADD_PREFIX,
  254. LLM_KV_TOKENIZER_HF_JSON,
  255. LLM_KV_TOKENIZER_RWKV,
  256. };
  257. static std::map<llm_kv, const char *> LLM_KV_NAMES = {
  258. { LLM_KV_GENERAL_ARCHITECTURE, "general.architecture" },
  259. { LLM_KV_GENERAL_QUANTIZATION_VERSION, "general.quantization_version" },
  260. { LLM_KV_GENERAL_ALIGNMENT, "general.alignment" },
  261. { LLM_KV_GENERAL_NAME, "general.name" },
  262. { LLM_KV_GENERAL_AUTHOR, "general.author" },
  263. { LLM_KV_GENERAL_URL, "general.url" },
  264. { LLM_KV_GENERAL_DESCRIPTION, "general.description" },
  265. { LLM_KV_GENERAL_LICENSE, "general.license" },
  266. { LLM_KV_GENERAL_SOURCE_URL, "general.source.url" },
  267. { LLM_KV_GENERAL_SOURCE_HF_REPO, "general.source.huggingface.repository" },
  268. { LLM_KV_CONTEXT_LENGTH, "%s.context_length" },
  269. { LLM_KV_EMBEDDING_LENGTH, "%s.embedding_length" },
  270. { LLM_KV_BLOCK_COUNT, "%s.block_count" },
  271. { LLM_KV_FEED_FORWARD_LENGTH, "%s.feed_forward_length" },
  272. { LLM_KV_USE_PARALLEL_RESIDUAL, "%s.use_parallel_residual" },
  273. { LLM_KV_TENSOR_DATA_LAYOUT, "%s.tensor_data_layout" },
  274. { LLM_KV_EXPERT_COUNT, "%s.expert_count" },
  275. { LLM_KV_EXPERT_USED_COUNT, "%s.expert_used_count" },
  276. { LLM_KV_ATTENTION_HEAD_COUNT, "%s.attention.head_count" },
  277. { LLM_KV_ATTENTION_HEAD_COUNT_KV, "%s.attention.head_count_kv" },
  278. { LLM_KV_ATTENTION_MAX_ALIBI_BIAS, "%s.attention.max_alibi_bias" },
  279. { LLM_KV_ATTENTION_CLAMP_KQV, "%s.attention.clamp_kqv" },
  280. { LLM_KV_ATTENTION_KEY_LENGTH, "%s.attention.key_length" },
  281. { LLM_KV_ATTENTION_VALUE_LENGTH, "%s.attention.value_length" },
  282. { LLM_KV_ATTENTION_LAYERNORM_EPS, "%s.attention.layer_norm_epsilon" },
  283. { LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, "%s.attention.layer_norm_rms_epsilon" },
  284. { LLM_KV_ROPE_DIMENSION_COUNT, "%s.rope.dimension_count" },
  285. { LLM_KV_ROPE_FREQ_BASE, "%s.rope.freq_base" },
  286. { LLM_KV_ROPE_SCALE_LINEAR, "%s.rope.scale_linear" },
  287. { LLM_KV_ROPE_SCALING_TYPE, "%s.rope.scaling.type" },
  288. { LLM_KV_ROPE_SCALING_FACTOR, "%s.rope.scaling.factor" },
  289. { LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, "%s.rope.scaling.original_context_length" },
  290. { LLM_KV_ROPE_SCALING_FINETUNED, "%s.rope.scaling.finetuned" },
  291. { LLM_KV_TOKENIZER_MODEL, "tokenizer.ggml.model" },
  292. { LLM_KV_TOKENIZER_LIST, "tokenizer.ggml.tokens" },
  293. { LLM_KV_TOKENIZER_TOKEN_TYPE, "tokenizer.ggml.token_type" },
  294. { LLM_KV_TOKENIZER_SCORES, "tokenizer.ggml.scores" },
  295. { LLM_KV_TOKENIZER_MERGES, "tokenizer.ggml.merges" },
  296. { LLM_KV_TOKENIZER_BOS_ID, "tokenizer.ggml.bos_token_id" },
  297. { LLM_KV_TOKENIZER_EOS_ID, "tokenizer.ggml.eos_token_id" },
  298. { LLM_KV_TOKENIZER_UNK_ID, "tokenizer.ggml.unknown_token_id" },
  299. { LLM_KV_TOKENIZER_SEP_ID, "tokenizer.ggml.seperator_token_id" },
  300. { LLM_KV_TOKENIZER_PAD_ID, "tokenizer.ggml.padding_token_id" },
  301. { LLM_KV_TOKENIZER_ADD_BOS, "tokenizer.ggml.add_bos_token" },
  302. { LLM_KV_TOKENIZER_ADD_EOS, "tokenizer.ggml.add_eos_token" },
  303. { LLM_KV_TOKENIZER_ADD_PREFIX, "tokenizer.ggml.add_space_prefix" },
  304. { LLM_KV_TOKENIZER_HF_JSON, "tokenizer.huggingface.json" },
  305. { LLM_KV_TOKENIZER_RWKV, "tokenizer.rwkv.world" },
  306. };
  307. struct LLM_KV {
  308. LLM_KV(llm_arch arch) : arch(arch) {}
  309. llm_arch arch;
  310. std::string operator()(llm_kv kv) const {
  311. return ::format(LLM_KV_NAMES[kv], LLM_ARCH_NAMES[arch]);
  312. }
  313. };
  314. enum llm_tensor {
  315. LLM_TENSOR_TOKEN_EMBD,
  316. LLM_TENSOR_TOKEN_EMBD_NORM,
  317. LLM_TENSOR_POS_EMBD,
  318. LLM_TENSOR_OUTPUT,
  319. LLM_TENSOR_OUTPUT_NORM,
  320. LLM_TENSOR_ROPE_FREQS,
  321. LLM_TENSOR_ATTN_Q,
  322. LLM_TENSOR_ATTN_K,
  323. LLM_TENSOR_ATTN_V,
  324. LLM_TENSOR_ATTN_QKV,
  325. LLM_TENSOR_ATTN_OUT,
  326. LLM_TENSOR_ATTN_NORM,
  327. LLM_TENSOR_ATTN_NORM_2,
  328. LLM_TENSOR_ATTN_ROT_EMBD,
  329. LLM_TENSOR_FFN_GATE_INP,
  330. LLM_TENSOR_FFN_NORM,
  331. LLM_TENSOR_FFN_GATE,
  332. LLM_TENSOR_FFN_DOWN,
  333. LLM_TENSOR_FFN_UP,
  334. LLM_TENSOR_FFN_ACT,
  335. LLM_TENSOR_FFN_DOWN_EXP,
  336. LLM_TENSOR_FFN_GATE_EXP,
  337. LLM_TENSOR_FFN_UP_EXP,
  338. LLM_TENSOR_ATTN_Q_NORM,
  339. LLM_TENSOR_ATTN_K_NORM,
  340. };
  341. static std::map<llm_arch, std::map<llm_tensor, std::string>> LLM_TENSOR_NAMES = {
  342. {
  343. LLM_ARCH_LLAMA,
  344. {
  345. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  346. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  347. { LLM_TENSOR_OUTPUT, "output" },
  348. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  349. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  350. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  351. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  352. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  353. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  354. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  355. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  356. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  357. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  358. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  359. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  360. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  361. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  362. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  363. },
  364. },
  365. {
  366. LLM_ARCH_BAICHUAN,
  367. {
  368. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  369. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  370. { LLM_TENSOR_OUTPUT, "output" },
  371. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  372. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  373. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  374. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  375. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  376. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  377. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  378. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  379. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  380. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  381. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  382. },
  383. },
  384. {
  385. LLM_ARCH_FALCON,
  386. {
  387. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  388. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  389. { LLM_TENSOR_OUTPUT, "output" },
  390. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  391. { LLM_TENSOR_ATTN_NORM_2, "blk.%d.attn_norm_2" },
  392. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  393. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  394. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  395. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  396. },
  397. },
  398. {
  399. LLM_ARCH_GPT2,
  400. {
  401. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  402. { LLM_TENSOR_POS_EMBD, "position_embd" },
  403. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  404. { LLM_TENSOR_OUTPUT, "output" },
  405. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  406. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  407. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  408. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  409. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  410. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  411. },
  412. },
  413. {
  414. LLM_ARCH_GPTJ,
  415. {
  416. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  417. },
  418. },
  419. {
  420. LLM_ARCH_GPTNEOX,
  421. {
  422. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  423. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  424. { LLM_TENSOR_OUTPUT, "output" },
  425. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  426. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  427. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  428. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  429. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  430. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  431. },
  432. },
  433. {
  434. LLM_ARCH_PERSIMMON,
  435. {
  436. { LLM_TENSOR_TOKEN_EMBD, "token_embd"},
  437. { LLM_TENSOR_OUTPUT_NORM, "output_norm"},
  438. { LLM_TENSOR_OUTPUT, "output"},
  439. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm"},
  440. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv"},
  441. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output"},
  442. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm"},
  443. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm"},
  444. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm"},
  445. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down"},
  446. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up"},
  447. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd"},
  448. },
  449. },
  450. {
  451. LLM_ARCH_MPT,
  452. {
  453. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  454. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  455. { LLM_TENSOR_OUTPUT, "output" },
  456. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  457. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  458. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  459. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  460. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  461. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  462. { LLM_TENSOR_FFN_ACT, "blk.%d.ffn.act" },
  463. },
  464. },
  465. {
  466. LLM_ARCH_STARCODER,
  467. {
  468. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  469. { LLM_TENSOR_POS_EMBD, "position_embd" },
  470. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  471. { LLM_TENSOR_OUTPUT, "output" },
  472. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  473. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  474. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  475. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  476. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  477. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  478. },
  479. },
  480. {
  481. LLM_ARCH_REFACT,
  482. {
  483. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  484. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  485. { LLM_TENSOR_OUTPUT, "output" },
  486. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  487. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  488. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  489. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  490. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  491. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  492. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  493. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  494. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  495. },
  496. },
  497. {
  498. LLM_ARCH_BLOOM,
  499. {
  500. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  501. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  502. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  503. { LLM_TENSOR_OUTPUT, "output" },
  504. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  505. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  506. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  507. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  508. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  509. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  510. },
  511. },
  512. {
  513. LLM_ARCH_STABLELM,
  514. {
  515. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  516. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  517. { LLM_TENSOR_OUTPUT, "output" },
  518. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  519. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  520. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  521. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  522. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  523. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  524. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  525. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  526. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  527. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  528. },
  529. },
  530. {
  531. LLM_ARCH_QWEN,
  532. {
  533. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  534. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  535. { LLM_TENSOR_OUTPUT, "output" },
  536. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  537. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  538. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  539. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  540. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  541. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  542. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  543. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  544. },
  545. },
  546. {
  547. LLM_ARCH_QWEN2,
  548. {
  549. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  550. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  551. { LLM_TENSOR_OUTPUT, "output" },
  552. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  553. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  554. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  555. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  556. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  557. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  558. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  559. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  560. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  561. },
  562. },
  563. {
  564. LLM_ARCH_PHI2,
  565. {
  566. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  567. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  568. { LLM_TENSOR_OUTPUT, "output" },
  569. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  570. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  571. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  572. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  573. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  574. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  575. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  576. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  577. },
  578. },
  579. {
  580. LLM_ARCH_PLAMO,
  581. {
  582. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  583. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  584. { LLM_TENSOR_OUTPUT, "output" },
  585. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  586. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  587. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  588. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  589. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  590. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  591. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  592. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  593. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  594. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  595. },
  596. },
  597. {
  598. LLM_ARCH_CODESHELL,
  599. {
  600. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  601. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  602. { LLM_TENSOR_OUTPUT, "output" },
  603. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  604. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  605. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  606. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  607. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  608. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  609. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  610. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  611. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  612. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  613. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  614. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  615. },
  616. },
  617. {
  618. LLM_ARCH_ORION,
  619. {
  620. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  621. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  622. { LLM_TENSOR_OUTPUT, "output" },
  623. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  624. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  625. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  626. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  627. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  628. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  629. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  630. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  631. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  632. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  633. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  634. },
  635. },
  636. {
  637. LLM_ARCH_INTERNLM2,
  638. {
  639. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  640. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  641. { LLM_TENSOR_OUTPUT, "output" },
  642. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  643. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  644. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  645. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  646. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  647. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  648. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  649. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  650. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  651. },
  652. },
  653. {
  654. LLM_ARCH_UNKNOWN,
  655. {
  656. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  657. },
  658. },
  659. };
  660. static llm_arch llm_arch_from_string(const std::string & name) {
  661. for (const auto & kv : LLM_ARCH_NAMES) { // NOLINT
  662. if (kv.second == name) {
  663. return kv.first;
  664. }
  665. }
  666. return LLM_ARCH_UNKNOWN;
  667. }
  668. // helper to handle gguf constants
  669. // usage:
  670. //
  671. // const auto tn = LLM_TN(LLM_ARCH_LLAMA);
  672. //
  673. // std::string name = tn(LLM_TENSOR_OUTPUT); -> "output"
  674. // std::string name = tn(LLM_TENSOR_TOKEN_EMBD, "bias"); -> "token_embd.bias"
  675. // std::string name = tn(LLM_TENSOR_ATTN_NORM, "weight", 3); -> "blk.3.attn_norm.weight"
  676. //
  677. struct LLM_TN {
  678. LLM_TN(llm_arch arch) : arch(arch) {}
  679. llm_arch arch;
  680. std::string operator()(llm_tensor tensor) const {
  681. return LLM_TENSOR_NAMES[arch].at(tensor);
  682. }
  683. std::string operator()(llm_tensor tensor, const std::string & suffix) const {
  684. return LLM_TENSOR_NAMES[arch].at(tensor) + "." + suffix;
  685. }
  686. std::string operator()(llm_tensor tensor, int bid) const {
  687. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid);
  688. }
  689. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid) const {
  690. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid) + "." + suffix;
  691. }
  692. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid, int xid) const {
  693. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid, xid) + "." + suffix;
  694. }
  695. };
  696. //
  697. // gguf helpers
  698. //
  699. static std::map<int32_t, const char *> LLAMA_ROPE_SCALING_TYPES = {
  700. { LLAMA_ROPE_SCALING_NONE, "none" },
  701. { LLAMA_ROPE_SCALING_LINEAR, "linear" },
  702. { LLAMA_ROPE_SCALING_YARN, "yarn" },
  703. };
  704. static int32_t llama_rope_scaling_type_from_string(const std::string & name) {
  705. for (const auto & kv : LLAMA_ROPE_SCALING_TYPES) {
  706. if (kv.second == name) {
  707. return kv.first;
  708. }
  709. }
  710. return LLAMA_ROPE_SCALING_UNSPECIFIED;
  711. }
  712. static std::string gguf_data_to_str(enum gguf_type type, const void * data, int i) {
  713. switch (type) {
  714. case GGUF_TYPE_UINT8: return std::to_string(((const uint8_t *)data)[i]);
  715. case GGUF_TYPE_INT8: return std::to_string(((const int8_t *)data)[i]);
  716. case GGUF_TYPE_UINT16: return std::to_string(((const uint16_t *)data)[i]);
  717. case GGUF_TYPE_INT16: return std::to_string(((const int16_t *)data)[i]);
  718. case GGUF_TYPE_UINT32: return std::to_string(((const uint32_t *)data)[i]);
  719. case GGUF_TYPE_INT32: return std::to_string(((const int32_t *)data)[i]);
  720. case GGUF_TYPE_UINT64: return std::to_string(((const uint64_t *)data)[i]);
  721. case GGUF_TYPE_INT64: return std::to_string(((const int64_t *)data)[i]);
  722. case GGUF_TYPE_FLOAT32: return std::to_string(((const float *)data)[i]);
  723. case GGUF_TYPE_FLOAT64: return std::to_string(((const double *)data)[i]);
  724. case GGUF_TYPE_BOOL: return ((const bool *)data)[i] ? "true" : "false";
  725. default: return format("unknown type %d", type);
  726. }
  727. }
  728. static std::string gguf_kv_to_str(const struct gguf_context * ctx_gguf, int i) {
  729. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  730. switch (type) {
  731. case GGUF_TYPE_STRING:
  732. return gguf_get_val_str(ctx_gguf, i);
  733. case GGUF_TYPE_ARRAY:
  734. {
  735. const enum gguf_type arr_type = gguf_get_arr_type(ctx_gguf, i);
  736. int arr_n = gguf_get_arr_n(ctx_gguf, i);
  737. const void * data = gguf_get_arr_data(ctx_gguf, i);
  738. std::stringstream ss;
  739. ss << "[";
  740. for (int j = 0; j < arr_n; j++) {
  741. if (arr_type == GGUF_TYPE_STRING) {
  742. std::string val = gguf_get_arr_str(ctx_gguf, i, j);
  743. // escape quotes
  744. replace_all(val, "\\", "\\\\");
  745. replace_all(val, "\"", "\\\"");
  746. ss << '"' << val << '"';
  747. } else if (arr_type == GGUF_TYPE_ARRAY) {
  748. ss << "???";
  749. } else {
  750. ss << gguf_data_to_str(arr_type, data, j);
  751. }
  752. if (j < arr_n - 1) {
  753. ss << ", ";
  754. }
  755. }
  756. ss << "]";
  757. return ss.str();
  758. }
  759. default:
  760. return gguf_data_to_str(type, gguf_get_val_data(ctx_gguf, i), 0);
  761. }
  762. }
  763. //
  764. // ggml helpers
  765. //
  766. static void ggml_graph_compute_helper(std::vector<uint8_t> & buf, ggml_cgraph * graph, int n_threads) {
  767. struct ggml_cplan plan = ggml_graph_plan(graph, n_threads);
  768. if (plan.work_size > 0) {
  769. buf.resize(plan.work_size);
  770. plan.work_data = buf.data();
  771. }
  772. ggml_graph_compute(graph, &plan);
  773. }
  774. //
  775. // llama helpers
  776. //
  777. #if defined(_WIN32)
  778. static std::string llama_format_win_err(DWORD err) {
  779. LPSTR buf;
  780. size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  781. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, NULL);
  782. if (!size) {
  783. return "FormatMessageA failed";
  784. }
  785. std::string ret(buf, size);
  786. LocalFree(buf);
  787. return ret;
  788. }
  789. #endif
  790. template <typename T>
  791. struct no_init {
  792. T value;
  793. no_init() { /* do nothing */ }
  794. };
  795. struct llama_file {
  796. // use FILE * so we don't have to re-open the file to mmap
  797. FILE * fp;
  798. size_t size;
  799. llama_file(const char * fname, const char * mode) {
  800. fp = std::fopen(fname, mode);
  801. if (fp == NULL) {
  802. throw std::runtime_error(format("failed to open %s: %s", fname, strerror(errno)));
  803. }
  804. seek(0, SEEK_END);
  805. size = tell();
  806. seek(0, SEEK_SET);
  807. }
  808. size_t tell() const {
  809. #ifdef _WIN32
  810. __int64 ret = _ftelli64(fp);
  811. #else
  812. long ret = std::ftell(fp);
  813. #endif
  814. GGML_ASSERT(ret != -1); // this really shouldn't fail
  815. return (size_t) ret;
  816. }
  817. void seek(size_t offset, int whence) const {
  818. #ifdef _WIN32
  819. int ret = _fseeki64(fp, (__int64) offset, whence);
  820. #else
  821. int ret = std::fseek(fp, (long) offset, whence);
  822. #endif
  823. GGML_ASSERT(ret == 0); // same
  824. }
  825. void read_raw(void * ptr, size_t len) const {
  826. if (len == 0) {
  827. return;
  828. }
  829. errno = 0;
  830. std::size_t ret = std::fread(ptr, len, 1, fp);
  831. if (ferror(fp)) {
  832. throw std::runtime_error(format("read error: %s", strerror(errno)));
  833. }
  834. if (ret != 1) {
  835. throw std::runtime_error("unexpectedly reached end of file");
  836. }
  837. }
  838. uint32_t read_u32() const {
  839. uint32_t ret;
  840. read_raw(&ret, sizeof(ret));
  841. return ret;
  842. }
  843. void write_raw(const void * ptr, size_t len) const {
  844. if (len == 0) {
  845. return;
  846. }
  847. errno = 0;
  848. size_t ret = std::fwrite(ptr, len, 1, fp);
  849. if (ret != 1) {
  850. throw std::runtime_error(format("write error: %s", strerror(errno)));
  851. }
  852. }
  853. void write_u32(std::uint32_t val) const {
  854. write_raw(&val, sizeof(val));
  855. }
  856. ~llama_file() {
  857. if (fp) {
  858. std::fclose(fp);
  859. }
  860. }
  861. };
  862. struct llama_mmap {
  863. void * addr;
  864. size_t size;
  865. llama_mmap(const llama_mmap &) = delete;
  866. #ifdef _POSIX_MAPPED_FILES
  867. static constexpr bool SUPPORTED = true;
  868. // list of mapped fragments (first_offset, last_offset)
  869. std::vector<std::pair<size_t, size_t>> mapped_fragments;
  870. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1 /* -1 = max value */, bool numa = false) {
  871. size = file->size;
  872. int fd = fileno(file->fp);
  873. int flags = MAP_SHARED;
  874. // prefetch/readahead impairs performance on NUMA systems
  875. if (numa) { prefetch = 0; }
  876. #ifdef __linux__
  877. // advise the kernel to read the file sequentially (increases readahead)
  878. if (posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL)) {
  879. LLAMA_LOG_WARN("warning: posix_fadvise(.., POSIX_FADV_SEQUENTIAL) failed: %s\n",
  880. strerror(errno));
  881. }
  882. if (prefetch) { flags |= MAP_POPULATE; }
  883. #endif
  884. addr = mmap(NULL, file->size, PROT_READ, flags, fd, 0);
  885. if (addr == MAP_FAILED) { // NOLINT
  886. throw std::runtime_error(format("mmap failed: %s", strerror(errno)));
  887. }
  888. if (prefetch > 0) {
  889. // advise the kernel to preload the mapped memory
  890. if (posix_madvise(addr, std::min(file->size, prefetch), POSIX_MADV_WILLNEED)) {
  891. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_WILLNEED) failed: %s\n",
  892. strerror(errno));
  893. }
  894. }
  895. if (numa) {
  896. // advise the kernel not to use readahead
  897. // (because the next page might not belong on the same node)
  898. if (posix_madvise(addr, file->size, POSIX_MADV_RANDOM)) {
  899. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_RANDOM) failed: %s\n",
  900. strerror(errno));
  901. }
  902. }
  903. // initialize list of mapped_fragments
  904. mapped_fragments.emplace_back(0, file->size);
  905. }
  906. static void align_range(size_t * first, size_t * last, size_t page_size) {
  907. // align first to the next page
  908. size_t offset_in_page = *first & (page_size - 1);
  909. size_t offset_to_page = offset_in_page == 0 ? 0 : page_size - offset_in_page;
  910. *first += offset_to_page;
  911. // align last to the previous page
  912. *last = *last & ~(page_size - 1);
  913. if (*last <= *first) {
  914. *last = *first;
  915. }
  916. }
  917. // partially unmap the file in the range [first, last)
  918. void unmap_fragment(size_t first, size_t last) {
  919. // note: this function must not be called multiple times with overlapping ranges
  920. // otherwise, there is a risk of invalidating addresses that have been repurposed for other mappings
  921. int page_size = sysconf(_SC_PAGESIZE);
  922. align_range(&first, &last, page_size);
  923. size_t len = last - first;
  924. if (len == 0) {
  925. return;
  926. }
  927. GGML_ASSERT(first % page_size == 0);
  928. GGML_ASSERT(last % page_size == 0);
  929. GGML_ASSERT(last > first);
  930. void * next_page_start = (uint8_t *) addr + first;
  931. // unmap the range
  932. if (munmap(next_page_start, len)) {
  933. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  934. }
  935. // update the list of mapped fragments to avoid unmapping the same range again in the destructor
  936. std::vector<std::pair<size_t, size_t>> new_mapped_fragments;
  937. for (const auto & frag : mapped_fragments) {
  938. if (frag.first < first && frag.second > last) {
  939. // the range is in the middle of the fragment, split it
  940. new_mapped_fragments.emplace_back(frag.first, first);
  941. new_mapped_fragments.emplace_back(last, frag.second);
  942. } else if (frag.first < first && frag.second > first) {
  943. // the range starts in the middle of the fragment
  944. new_mapped_fragments.emplace_back(frag.first, first);
  945. } else if (frag.first < last && frag.second > last) {
  946. // the range ends in the middle of the fragment
  947. new_mapped_fragments.emplace_back(last, frag.second);
  948. } else if (frag.first >= first && frag.second <= last) {
  949. // the range covers the entire fragment
  950. } else {
  951. // the range is outside the fragment
  952. new_mapped_fragments.push_back(frag);
  953. }
  954. }
  955. mapped_fragments = std::move(new_mapped_fragments);
  956. }
  957. ~llama_mmap() {
  958. for (const auto & frag : mapped_fragments) {
  959. if (munmap((char *) addr + frag.first, frag.second - frag.first)) {
  960. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  961. }
  962. }
  963. }
  964. #elif defined(_WIN32)
  965. static constexpr bool SUPPORTED = true;
  966. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1, bool numa = false) {
  967. GGML_UNUSED(numa);
  968. size = file->size;
  969. HANDLE hFile = (HANDLE) _get_osfhandle(_fileno(file->fp));
  970. HANDLE hMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
  971. if (hMapping == NULL) {
  972. DWORD error = GetLastError();
  973. throw std::runtime_error(format("CreateFileMappingA failed: %s", llama_format_win_err(error).c_str()));
  974. }
  975. addr = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
  976. DWORD error = GetLastError();
  977. CloseHandle(hMapping);
  978. if (addr == NULL) {
  979. throw std::runtime_error(format("MapViewOfFile failed: %s", llama_format_win_err(error).c_str()));
  980. }
  981. if (prefetch > 0) {
  982. #if _WIN32_WINNT >= 0x602
  983. // PrefetchVirtualMemory is only present on Windows 8 and above, so we dynamically load it
  984. BOOL (WINAPI *pPrefetchVirtualMemory) (HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG);
  985. HMODULE hKernel32 = GetModuleHandleW(L"kernel32.dll");
  986. // may fail on pre-Windows 8 systems
  987. pPrefetchVirtualMemory = reinterpret_cast<decltype(pPrefetchVirtualMemory)> (GetProcAddress(hKernel32, "PrefetchVirtualMemory"));
  988. if (pPrefetchVirtualMemory) {
  989. // advise the kernel to preload the mapped memory
  990. WIN32_MEMORY_RANGE_ENTRY range;
  991. range.VirtualAddress = addr;
  992. range.NumberOfBytes = (SIZE_T) std::min(size, prefetch);
  993. if (!pPrefetchVirtualMemory(GetCurrentProcess(), 1, &range, 0)) {
  994. LLAMA_LOG_WARN("warning: PrefetchVirtualMemory failed: %s\n",
  995. llama_format_win_err(GetLastError()).c_str());
  996. }
  997. }
  998. #else
  999. throw std::runtime_error("PrefetchVirtualMemory unavailable");
  1000. #endif
  1001. }
  1002. }
  1003. void unmap_fragment(size_t first, size_t last) {
  1004. // not supported
  1005. GGML_UNUSED(first);
  1006. GGML_UNUSED(last);
  1007. }
  1008. ~llama_mmap() {
  1009. if (!UnmapViewOfFile(addr)) {
  1010. LLAMA_LOG_WARN("warning: UnmapViewOfFile failed: %s\n",
  1011. llama_format_win_err(GetLastError()).c_str());
  1012. }
  1013. }
  1014. #else
  1015. static constexpr bool SUPPORTED = false;
  1016. llama_mmap(struct llama_file * file, size_t prefetch = -1, bool numa = false) {
  1017. GGML_UNUSED(file);
  1018. GGML_UNUSED(prefetch);
  1019. GGML_UNUSED(numa);
  1020. throw std::runtime_error("mmap not supported");
  1021. }
  1022. void unmap_fragment(size_t first, size_t last) {
  1023. GGML_UNUSED(first);
  1024. GGML_UNUSED(last);
  1025. throw std::runtime_error("mmap not supported");
  1026. }
  1027. #endif
  1028. };
  1029. // Represents some region of memory being locked using mlock or VirtualLock;
  1030. // will automatically unlock on destruction.
  1031. struct llama_mlock {
  1032. void * addr = NULL;
  1033. size_t size = 0;
  1034. bool failed_already = false;
  1035. llama_mlock() {}
  1036. llama_mlock(const llama_mlock &) = delete;
  1037. ~llama_mlock() {
  1038. if (size) {
  1039. raw_unlock(addr, size);
  1040. }
  1041. }
  1042. void init(void * ptr) {
  1043. GGML_ASSERT(addr == NULL && size == 0); // NOLINT
  1044. addr = ptr;
  1045. }
  1046. void grow_to(size_t target_size) {
  1047. GGML_ASSERT(addr);
  1048. if (failed_already) {
  1049. return;
  1050. }
  1051. size_t granularity = lock_granularity();
  1052. target_size = (target_size + granularity - 1) & ~(granularity - 1);
  1053. if (target_size > size) {
  1054. if (raw_lock((uint8_t *) addr + size, target_size - size)) {
  1055. size = target_size;
  1056. } else {
  1057. failed_already = true;
  1058. }
  1059. }
  1060. }
  1061. #ifdef _POSIX_MEMLOCK_RANGE
  1062. static constexpr bool SUPPORTED = true;
  1063. static size_t lock_granularity() {
  1064. return (size_t) sysconf(_SC_PAGESIZE);
  1065. }
  1066. #ifdef __APPLE__
  1067. #define MLOCK_SUGGESTION \
  1068. "Try increasing the sysctl values 'vm.user_wire_limit' and 'vm.global_user_wire_limit' and/or " \
  1069. "decreasing 'vm.global_no_user_wire_amount'. Also try increasing RLIMIT_MEMLOCK (ulimit -l).\n"
  1070. #else
  1071. #define MLOCK_SUGGESTION \
  1072. "Try increasing RLIMIT_MEMLOCK ('ulimit -l' as root).\n"
  1073. #endif
  1074. bool raw_lock(const void * addr, size_t size) const {
  1075. if (!mlock(addr, size)) {
  1076. return true;
  1077. }
  1078. char* errmsg = std::strerror(errno);
  1079. bool suggest = (errno == ENOMEM);
  1080. // Check if the resource limit is fine after all
  1081. struct rlimit lock_limit;
  1082. if (suggest && getrlimit(RLIMIT_MEMLOCK, &lock_limit)) {
  1083. suggest = false;
  1084. }
  1085. if (suggest && (lock_limit.rlim_max > lock_limit.rlim_cur + size)) {
  1086. suggest = false;
  1087. }
  1088. LLAMA_LOG_WARN("warning: failed to mlock %zu-byte buffer (after previously locking %zu bytes): %s\n%s",
  1089. size, this->size, errmsg, suggest ? MLOCK_SUGGESTION : "");
  1090. return false;
  1091. }
  1092. #undef MLOCK_SUGGESTION
  1093. static void raw_unlock(void * addr, size_t size) {
  1094. if (munlock(addr, size)) {
  1095. LLAMA_LOG_WARN("warning: failed to munlock buffer: %s\n", std::strerror(errno));
  1096. }
  1097. }
  1098. #elif defined(_WIN32)
  1099. static constexpr bool SUPPORTED = true;
  1100. static size_t lock_granularity() {
  1101. SYSTEM_INFO si;
  1102. GetSystemInfo(&si);
  1103. return (size_t) si.dwPageSize;
  1104. }
  1105. bool raw_lock(void * ptr, size_t len) const {
  1106. for (int tries = 1; ; tries++) {
  1107. if (VirtualLock(ptr, len)) {
  1108. return true;
  1109. }
  1110. if (tries == 2) {
  1111. LLAMA_LOG_WARN("warning: failed to VirtualLock %zu-byte buffer (after previously locking %zu bytes): %s\n",
  1112. len, size, llama_format_win_err(GetLastError()).c_str());
  1113. return false;
  1114. }
  1115. // It failed but this was only the first try; increase the working
  1116. // set size and try again.
  1117. SIZE_T min_ws_size, max_ws_size;
  1118. if (!GetProcessWorkingSetSize(GetCurrentProcess(), &min_ws_size, &max_ws_size)) {
  1119. LLAMA_LOG_WARN("warning: GetProcessWorkingSetSize failed: %s\n",
  1120. llama_format_win_err(GetLastError()).c_str());
  1121. return false;
  1122. }
  1123. // Per MSDN: "The maximum number of pages that a process can lock
  1124. // is equal to the number of pages in its minimum working set minus
  1125. // a small overhead."
  1126. // Hopefully a megabyte is enough overhead:
  1127. size_t increment = len + 1048576;
  1128. // The minimum must be <= the maximum, so we need to increase both:
  1129. min_ws_size += increment;
  1130. max_ws_size += increment;
  1131. if (!SetProcessWorkingSetSize(GetCurrentProcess(), min_ws_size, max_ws_size)) {
  1132. LLAMA_LOG_WARN("warning: SetProcessWorkingSetSize failed: %s\n",
  1133. llama_format_win_err(GetLastError()).c_str());
  1134. return false;
  1135. }
  1136. }
  1137. }
  1138. static void raw_unlock(void * ptr, size_t len) {
  1139. if (!VirtualUnlock(ptr, len)) {
  1140. LLAMA_LOG_WARN("warning: failed to VirtualUnlock buffer: %s\n",
  1141. llama_format_win_err(GetLastError()).c_str());
  1142. }
  1143. }
  1144. #else
  1145. static constexpr bool SUPPORTED = false;
  1146. static size_t lock_granularity() {
  1147. return (size_t) 65536;
  1148. }
  1149. bool raw_lock(const void * addr, size_t len) const {
  1150. LLAMA_LOG_WARN("warning: mlock not supported on this system\n");
  1151. return false;
  1152. }
  1153. static void raw_unlock(const void * addr, size_t len) {}
  1154. #endif
  1155. };
  1156. static std::string llama_token_to_piece(const struct llama_context * ctx, llama_token token) {
  1157. std::vector<char> result(8, 0);
  1158. const int n_tokens = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1159. if (n_tokens < 0) {
  1160. result.resize(-n_tokens);
  1161. int check = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1162. GGML_ASSERT(check == -n_tokens);
  1163. }
  1164. else {
  1165. result.resize(n_tokens);
  1166. }
  1167. return std::string(result.data(), result.size());
  1168. }
  1169. static ggml_backend_buffer_type_t llama_default_buffer_type_cpu(bool host_buffer) {
  1170. ggml_backend_buffer_type_t buft = nullptr;
  1171. #if defined(GGML_USE_CUBLAS)
  1172. // host buffers should only be used when data is expected to be copied to/from the GPU
  1173. if (host_buffer) {
  1174. buft = ggml_backend_cuda_host_buffer_type();
  1175. }
  1176. #elif defined(GGML_USE_SYCL)
  1177. buft = ggml_backend_sycl_host_buffer_type();
  1178. #elif defined(GGML_USE_CPU_HBM)
  1179. buft = ggml_backend_cpu_hbm_buffer_type();
  1180. #elif defined(GGML_USE_VULKAN)
  1181. if (host_buffer) {
  1182. buft = ggml_backend_vk_host_buffer_type();
  1183. }
  1184. #endif
  1185. if (buft == nullptr) {
  1186. buft = ggml_backend_cpu_buffer_type();
  1187. }
  1188. return buft;
  1189. GGML_UNUSED(host_buffer);
  1190. }
  1191. static ggml_backend_buffer_type_t llama_default_buffer_type_offload(int gpu) {
  1192. ggml_backend_buffer_type_t buft = nullptr;
  1193. #ifdef GGML_USE_METAL
  1194. buft = ggml_backend_metal_buffer_type();
  1195. #elif defined(GGML_USE_CUBLAS)
  1196. buft = ggml_backend_cuda_buffer_type(gpu);
  1197. #elif defined(GGML_USE_VULKAN)
  1198. buft = ggml_backend_vk_buffer_type();
  1199. #elif defined(GGML_USE_SYCL)
  1200. buft = ggml_backend_sycl_buffer_type(gpu);
  1201. #elif defined(GGML_USE_CLBLAST)
  1202. buft = ggml_backend_opencl_buffer_type();
  1203. #elif defined(GGML_USE_KOMPUTE)
  1204. buft = ggml_backend_kompute_buffer_type(gpu);
  1205. if (buft == nullptr) {
  1206. LLAMA_LOG_WARN("%s: cannot use GPU %d, check `vulkaninfo --summary`\n", __func__, gpu);
  1207. }
  1208. #endif
  1209. if (buft == nullptr) {
  1210. buft = llama_default_buffer_type_cpu(true);
  1211. }
  1212. return buft;
  1213. GGML_UNUSED(gpu);
  1214. }
  1215. static ggml_backend_buffer_type_t llama_default_buffer_type_split(int fallback_gpu, const float * tensor_split) {
  1216. ggml_backend_buffer_type_t buft = nullptr;
  1217. #ifdef GGML_USE_CUBLAS
  1218. if (ggml_backend_cuda_get_device_count() > 1) {
  1219. buft = ggml_backend_cuda_split_buffer_type(tensor_split);
  1220. }
  1221. #endif
  1222. if (buft == nullptr) {
  1223. buft = llama_default_buffer_type_offload(fallback_gpu);
  1224. }
  1225. return buft;
  1226. GGML_UNUSED(tensor_split);
  1227. }
  1228. //
  1229. // globals
  1230. //
  1231. struct llama_state {
  1232. llama_state() {
  1233. #ifdef GGML_USE_METAL
  1234. ggml_backend_metal_log_set_callback(log_callback, log_callback_user_data);
  1235. #endif
  1236. }
  1237. // We save the log callback globally
  1238. ggml_log_callback log_callback = llama_log_callback_default;
  1239. void * log_callback_user_data = nullptr;
  1240. };
  1241. static llama_state g_state;
  1242. // available llama models
  1243. enum e_model {
  1244. MODEL_UNKNOWN,
  1245. MODEL_0_5B,
  1246. MODEL_1B,
  1247. MODEL_3B,
  1248. MODEL_4B,
  1249. MODEL_7B,
  1250. MODEL_8B,
  1251. MODEL_13B,
  1252. MODEL_14B,
  1253. MODEL_15B,
  1254. MODEL_20B,
  1255. MODEL_30B,
  1256. MODEL_34B,
  1257. MODEL_40B,
  1258. MODEL_65B,
  1259. MODEL_70B,
  1260. MODEL_SMALL,
  1261. MODEL_MEDIUM,
  1262. MODEL_LARGE,
  1263. MODEL_XL,
  1264. };
  1265. static const size_t kiB = 1024;
  1266. static const size_t MiB = 1024*kiB;
  1267. static const size_t GiB = 1024*MiB;
  1268. struct llama_hparams {
  1269. bool vocab_only;
  1270. bool rope_finetuned;
  1271. uint32_t n_vocab;
  1272. uint32_t n_ctx_train; // context size the model was trained on
  1273. uint32_t n_embd;
  1274. uint32_t n_head;
  1275. uint32_t n_head_kv;
  1276. uint32_t n_layer;
  1277. uint32_t n_rot;
  1278. 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
  1279. uint32_t n_embd_head_v; // dimension of values (d_v) aka n_embd_head
  1280. uint32_t n_ff;
  1281. uint32_t n_expert = 0;
  1282. uint32_t n_expert_used = 0;
  1283. float f_norm_eps;
  1284. float f_norm_rms_eps;
  1285. float rope_freq_base_train;
  1286. float rope_freq_scale_train;
  1287. uint32_t n_yarn_orig_ctx;
  1288. int32_t rope_scaling_type_train;
  1289. float f_clamp_kqv;
  1290. float f_max_alibi_bias;
  1291. bool operator!=(const llama_hparams & other) const {
  1292. if (this->vocab_only != other.vocab_only) return true;
  1293. if (this->n_vocab != other.n_vocab) return true;
  1294. if (this->n_ctx_train != other.n_ctx_train) return true;
  1295. if (this->n_embd != other.n_embd) return true;
  1296. if (this->n_head != other.n_head) return true;
  1297. if (this->n_head_kv != other.n_head_kv) return true;
  1298. if (this->n_layer != other.n_layer) return true;
  1299. if (this->n_rot != other.n_rot) return true;
  1300. if (this->n_embd_head_k != other.n_embd_head_k) return true;
  1301. if (this->n_embd_head_v != other.n_embd_head_v) return true;
  1302. if (this->n_ff != other.n_ff) return true;
  1303. if (this->n_expert != other.n_expert) return true;
  1304. if (this->n_expert_used != other.n_expert_used) return true;
  1305. if (this->rope_finetuned != other.rope_finetuned) return true;
  1306. if (this->n_yarn_orig_ctx != other.n_yarn_orig_ctx) return true;
  1307. const float EPSILON = 1e-9f;
  1308. if (!is_float_close(this->f_norm_eps, other.f_norm_eps, EPSILON)) return true;
  1309. if (!is_float_close(this->f_norm_rms_eps, other.f_norm_rms_eps, EPSILON)) return true;
  1310. if (!is_float_close(this->rope_freq_base_train, other.rope_freq_base_train, EPSILON)) return true;
  1311. if (!is_float_close(this->rope_freq_scale_train, other.rope_freq_scale_train, EPSILON)) return true;
  1312. return false;
  1313. }
  1314. uint32_t n_gqa() const {
  1315. return n_head/n_head_kv;
  1316. }
  1317. uint32_t n_embd_k_gqa() const { // dimension of key embeddings across all k-v heads
  1318. return n_embd_head_k * n_head_kv;
  1319. }
  1320. uint32_t n_embd_v_gqa() const { // dimension of value embeddings across all k-v heads
  1321. return n_embd_head_v * n_head_kv;
  1322. }
  1323. };
  1324. struct llama_cparams {
  1325. uint32_t n_ctx; // context size used during inference
  1326. uint32_t n_batch;
  1327. uint32_t n_threads; // number of threads to use for generation
  1328. uint32_t n_threads_batch; // number of threads to use for batch processing
  1329. float rope_freq_base;
  1330. float rope_freq_scale;
  1331. uint32_t n_yarn_orig_ctx;
  1332. // These hyperparameters are not exposed in GGUF, because all
  1333. // existing YaRN models use the same values for them.
  1334. float yarn_ext_factor;
  1335. float yarn_attn_factor;
  1336. float yarn_beta_fast;
  1337. float yarn_beta_slow;
  1338. bool mul_mat_q;
  1339. bool offload_kqv;
  1340. ggml_backend_sched_eval_callback cb_eval;
  1341. void * cb_eval_user_data;
  1342. };
  1343. struct llama_layer {
  1344. // normalization
  1345. struct ggml_tensor * attn_norm;
  1346. struct ggml_tensor * attn_norm_b;
  1347. struct ggml_tensor * attn_norm_2;
  1348. struct ggml_tensor * attn_norm_2_b;
  1349. struct ggml_tensor * attn_q_norm;
  1350. struct ggml_tensor * attn_q_norm_b;
  1351. struct ggml_tensor * attn_k_norm;
  1352. struct ggml_tensor * attn_k_norm_b;
  1353. // attention
  1354. struct ggml_tensor * wq;
  1355. struct ggml_tensor * wk;
  1356. struct ggml_tensor * wv;
  1357. struct ggml_tensor * wo;
  1358. struct ggml_tensor * wqkv;
  1359. // attention bias
  1360. struct ggml_tensor * bq;
  1361. struct ggml_tensor * bk;
  1362. struct ggml_tensor * bv;
  1363. struct ggml_tensor * bo;
  1364. struct ggml_tensor * bqkv;
  1365. // normalization
  1366. struct ggml_tensor * ffn_norm;
  1367. struct ggml_tensor * ffn_norm_b;
  1368. // ff
  1369. struct ggml_tensor * ffn_gate; // w1
  1370. struct ggml_tensor * ffn_down; // w2
  1371. struct ggml_tensor * ffn_up; // w3
  1372. // ff MoE
  1373. struct ggml_tensor * ffn_gate_inp;
  1374. struct ggml_tensor * ffn_gate_exp[LLAMA_MAX_EXPERTS];
  1375. struct ggml_tensor * ffn_down_exp[LLAMA_MAX_EXPERTS];
  1376. struct ggml_tensor * ffn_up_exp [LLAMA_MAX_EXPERTS];
  1377. // ff bias
  1378. struct ggml_tensor * ffn_down_b; // b2
  1379. struct ggml_tensor * ffn_up_b; // b3
  1380. struct ggml_tensor * ffn_act;
  1381. };
  1382. struct llama_kv_cell {
  1383. llama_pos pos = -1;
  1384. llama_pos delta = 0;
  1385. std::set<llama_seq_id> seq_id;
  1386. bool has_seq_id(const llama_seq_id & id) const {
  1387. return seq_id.find(id) != seq_id.end();
  1388. }
  1389. };
  1390. // ring-buffer of cached KV data
  1391. struct llama_kv_cache {
  1392. bool has_shift = false;
  1393. // Note: The value of head isn't only used to optimize searching
  1394. // for a free KV slot. llama_decode_internal also uses it, so it
  1395. // cannot be freely changed after a slot has been allocated.
  1396. uint32_t head = 0;
  1397. uint32_t size = 0;
  1398. uint32_t used = 0; // used cells (i.e. at least one seq_id)
  1399. // computed before each graph build
  1400. uint32_t n = 0;
  1401. std::vector<llama_kv_cell> cells;
  1402. std::vector<struct ggml_tensor *> k_l; // per layer
  1403. std::vector<struct ggml_tensor *> v_l;
  1404. std::vector<struct ggml_context *> ctxs;
  1405. std::vector<ggml_backend_buffer_t> bufs;
  1406. size_t total_size() const {
  1407. size_t size = 0;
  1408. for (ggml_backend_buffer_t buf : bufs) {
  1409. size += ggml_backend_buffer_get_size(buf);
  1410. }
  1411. return size;
  1412. }
  1413. ~llama_kv_cache() {
  1414. for (struct ggml_context * ctx : ctxs) {
  1415. ggml_free(ctx);
  1416. }
  1417. for (ggml_backend_buffer_t buf : bufs) {
  1418. ggml_backend_buffer_free(buf);
  1419. }
  1420. }
  1421. };
  1422. struct llama_vocab {
  1423. using id = int32_t;
  1424. using token = std::string;
  1425. using ttype = llama_token_type;
  1426. struct token_data {
  1427. token text;
  1428. float score;
  1429. ttype type;
  1430. };
  1431. enum llama_vocab_type type = LLAMA_VOCAB_TYPE_SPM;
  1432. std::unordered_map<token, id> token_to_id;
  1433. std::vector<token_data> id_to_token;
  1434. std::unordered_map<token, id> special_tokens_cache;
  1435. std::map<std::pair<std::string, std::string>, int> bpe_ranks;
  1436. // default LLaMA special tokens
  1437. id special_bos_id = 1;
  1438. id special_eos_id = 2;
  1439. id special_unk_id = 0;
  1440. id special_sep_id = -1;
  1441. id special_pad_id = -1;
  1442. int special_add_bos = -1; // -1 unknown, 1 add, 0 don't add.
  1443. int special_add_eos = -1; // -1 unknown, 1 add, 0 don't add.
  1444. id linefeed_id = 13;
  1445. id special_prefix_id = 32007;
  1446. id special_middle_id = 32009;
  1447. id special_suffix_id = 32008;
  1448. id special_eot_id = 32010;
  1449. bool add_space_prefix = true;
  1450. int find_bpe_rank(const std::string & token_left, const std::string & token_right) const {
  1451. GGML_ASSERT(token_left.find(' ') == std::string::npos);
  1452. GGML_ASSERT(token_left.find('\n') == std::string::npos);
  1453. GGML_ASSERT(token_right.find(' ') == std::string::npos);
  1454. GGML_ASSERT(token_right.find('\n') == std::string::npos);
  1455. auto it = bpe_ranks.find(std::make_pair(token_left, token_right));
  1456. if (it == bpe_ranks.end()) {
  1457. return -1;
  1458. }
  1459. return it->second;
  1460. }
  1461. };
  1462. struct llama_model {
  1463. e_model type = MODEL_UNKNOWN;
  1464. llm_arch arch = LLM_ARCH_UNKNOWN;
  1465. llama_ftype ftype = LLAMA_FTYPE_ALL_F32;
  1466. std::string name = "n/a";
  1467. llama_hparams hparams = {};
  1468. llama_vocab vocab;
  1469. struct ggml_tensor * tok_embd;
  1470. struct ggml_tensor * pos_embd;
  1471. struct ggml_tensor * tok_norm;
  1472. struct ggml_tensor * tok_norm_b;
  1473. struct ggml_tensor * output_norm;
  1474. struct ggml_tensor * output_norm_b;
  1475. struct ggml_tensor * output;
  1476. struct ggml_tensor * output_b;
  1477. std::vector<llama_layer> layers;
  1478. llama_split_mode split_mode;
  1479. int main_gpu;
  1480. int n_gpu_layers;
  1481. // gguf metadata
  1482. std::unordered_map<std::string, std::string> gguf_kv;
  1483. // layer -> buffer type mapping
  1484. struct layer_buft {
  1485. layer_buft() : buft_matrix(nullptr), buft(nullptr) {}
  1486. layer_buft(ggml_backend_buffer_type_t matrix) : buft_matrix(matrix), buft(matrix) {}
  1487. layer_buft(ggml_backend_buffer_type_t matrix, ggml_backend_buffer_type_t other) : buft_matrix(matrix), buft(other) {}
  1488. ggml_backend_buffer_type_t buft_matrix; // matrices only - used by split buffers and backends that support only matrix multiplication
  1489. ggml_backend_buffer_type_t buft; // everything else
  1490. };
  1491. layer_buft buft_input;
  1492. layer_buft buft_output;
  1493. std::vector<layer_buft> buft_layer;
  1494. // contexts where the model tensors metadata is stored
  1495. std::vector<struct ggml_context *> ctxs;
  1496. // the model memory buffers for the tensor data
  1497. std::vector<ggml_backend_buffer_t> bufs;
  1498. // model memory mapped file
  1499. std::unique_ptr<llama_mmap> mapping;
  1500. // objects representing data potentially being locked in memory
  1501. std::vector<std::unique_ptr<llama_mlock>> mlock_bufs;
  1502. llama_mlock mlock_mmap;
  1503. // for quantize-stats only
  1504. std::vector<std::pair<std::string, struct ggml_tensor *>> tensors_by_name;
  1505. int64_t t_load_us = 0;
  1506. int64_t t_start_us = 0;
  1507. ~llama_model() {
  1508. for (struct ggml_context * ctx : ctxs) {
  1509. ggml_free(ctx);
  1510. }
  1511. for (ggml_backend_buffer_t buf : bufs) {
  1512. ggml_backend_buffer_free(buf);
  1513. }
  1514. }
  1515. };
  1516. struct llama_context {
  1517. llama_context(const llama_model & model) : model(model), t_start_us(model.t_start_us), t_load_us(model.t_load_us) {}
  1518. ~llama_context() {
  1519. ggml_backend_sched_free(sched);
  1520. for (ggml_backend_t backend : backends) {
  1521. ggml_backend_free(backend);
  1522. }
  1523. ggml_backend_buffer_free(buf_input);
  1524. ggml_free(ctx_input);
  1525. }
  1526. llama_cparams cparams;
  1527. std::vector<ggml_backend_t> backends;
  1528. #ifdef GGML_USE_METAL
  1529. ggml_backend_t backend_metal = nullptr;
  1530. #endif
  1531. ggml_backend_t backend_cpu = nullptr;
  1532. const llama_model & model;
  1533. // key + value cache for the self attention
  1534. struct llama_kv_cache kv_self;
  1535. std::mt19937 rng;
  1536. bool has_evaluated_once = false;
  1537. int64_t t_start_us;
  1538. int64_t t_load_us;
  1539. int64_t t_sample_us = 0;
  1540. int64_t t_p_eval_us = 0;
  1541. int64_t t_eval_us = 0;
  1542. int32_t n_sample = 0; // number of tokens sampled
  1543. int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1)
  1544. int32_t n_eval = 0; // number of eval calls
  1545. // decode output (2-dimensional array: [n_tokens][n_vocab])
  1546. std::vector<float> logits;
  1547. #ifndef NDEBUG
  1548. // guard against access to unset logits
  1549. std::vector<bool> logits_valid;
  1550. #endif
  1551. bool logits_all = false;
  1552. // input embedding (1-dimensional array: [n_embd])
  1553. std::vector<float> embedding;
  1554. // memory buffers used to evaluate the model
  1555. std::vector<uint8_t> buf_compute_meta;
  1556. ggml_backend_sched_t sched = nullptr;
  1557. // allocator for the input tensors
  1558. ggml_tallocr * alloc = nullptr;
  1559. // input tensors
  1560. ggml_backend_buffer_t buf_input = nullptr;
  1561. ggml_context * ctx_input = nullptr;
  1562. struct ggml_tensor * inp_tokens; // I32 [n_batch]
  1563. struct ggml_tensor * inp_embd; // F32 [n_embd, n_batch]
  1564. struct ggml_tensor * inp_pos; // I32 [n_batch]
  1565. struct ggml_tensor * inp_KQ_mask; // F32 [n_ctx, n_batch]
  1566. struct ggml_tensor * inp_K_shift; // I32 [n_ctx]
  1567. #ifdef GGML_USE_MPI
  1568. ggml_mpi_context * ctx_mpi = NULL;
  1569. #endif
  1570. };
  1571. //
  1572. // kv cache helpers
  1573. //
  1574. static bool llama_kv_cache_init(
  1575. struct llama_kv_cache & cache,
  1576. const llama_model & model,
  1577. ggml_type ktype,
  1578. ggml_type vtype,
  1579. uint32_t n_ctx,
  1580. bool offload) {
  1581. const struct llama_hparams & hparams = model.hparams;
  1582. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  1583. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  1584. const int64_t n_layer = hparams.n_layer;
  1585. cache.has_shift = false;
  1586. cache.head = 0;
  1587. cache.size = n_ctx;
  1588. cache.used = 0;
  1589. cache.cells.clear();
  1590. cache.cells.resize(n_ctx);
  1591. #ifdef GGML_USE_CLBLAST
  1592. offload = false;
  1593. #endif
  1594. // count used buffer types
  1595. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  1596. if (offload) {
  1597. for (int64_t i = 0; i < n_layer; ++i) {
  1598. buft_layer_count[model.buft_layer[i].buft]++;
  1599. }
  1600. } else {
  1601. buft_layer_count[llama_default_buffer_type_cpu(true)] = n_layer;
  1602. }
  1603. // create a context for each buffer type
  1604. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  1605. for (auto & it : buft_layer_count) {
  1606. int n_layers = it.second;
  1607. struct ggml_init_params params = {
  1608. /*.mem_size =*/ 2u*n_layers*ggml_tensor_overhead(),
  1609. /*.mem_buffer =*/ NULL,
  1610. /*.no_alloc =*/ true,
  1611. };
  1612. ggml_context * ctx = ggml_init(params);
  1613. if (!ctx) {
  1614. LLAMA_LOG_ERROR("%s: failed to allocate context for kv cache\n", __func__);
  1615. return false;
  1616. }
  1617. ctx_map[it.first] = ctx;
  1618. cache.ctxs.push_back(ctx);
  1619. }
  1620. cache.k_l.reserve(n_layer);
  1621. cache.v_l.reserve(n_layer);
  1622. for (int i = 0; i < (int) n_layer; i++) {
  1623. struct ggml_context * ctx = offload ? ctx_map.at(model.buft_layer[i].buft) : cache.ctxs.front();
  1624. ggml_tensor * k = ggml_new_tensor_1d(ctx, ktype, n_embd_k_gqa*n_ctx);
  1625. ggml_tensor * v = ggml_new_tensor_1d(ctx, vtype, n_embd_v_gqa*n_ctx);
  1626. ggml_format_name(k, "cache_k_l%d", i);
  1627. ggml_format_name(v, "cache_v_l%d", i);
  1628. cache.k_l.push_back(k);
  1629. cache.v_l.push_back(v);
  1630. }
  1631. // allocate tensors and initialize the buffers to avoid NaNs in the padding
  1632. for (auto it : ctx_map) {
  1633. ggml_backend_buffer_type_t buft = it.first;
  1634. ggml_context * ctx = it.second;
  1635. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  1636. if (!buf) {
  1637. LLAMA_LOG_ERROR("%s: failed to allocate buffer for kv cache\n", __func__);
  1638. return false;
  1639. }
  1640. ggml_backend_buffer_clear(buf, 0);
  1641. 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);
  1642. cache.bufs.push_back(buf);
  1643. }
  1644. return true;
  1645. }
  1646. // find an empty slot of size "n_tokens" in the cache
  1647. // updates the cache head
  1648. // Note: On success, it's important that cache.head points
  1649. // to the first cell of the slot.
  1650. static bool llama_kv_cache_find_slot(
  1651. struct llama_kv_cache & cache,
  1652. const struct llama_batch & batch) {
  1653. const uint32_t n_ctx = cache.size;
  1654. const uint32_t n_tokens = batch.n_tokens;
  1655. if (n_tokens > n_ctx) {
  1656. LLAMA_LOG_ERROR("%s: n_tokens=%d > n_ctx=%d\n", __func__, n_tokens, n_ctx);
  1657. return false;
  1658. }
  1659. uint32_t n_tested = 0;
  1660. while (true) {
  1661. if (cache.head + n_tokens > n_ctx) {
  1662. n_tested += n_ctx - cache.head;
  1663. cache.head = 0;
  1664. continue;
  1665. }
  1666. bool found = true;
  1667. for (uint32_t i = 0; i < n_tokens; i++) {
  1668. if (cache.cells[cache.head + i].pos >= 0) {
  1669. found = false;
  1670. cache.head += i + 1;
  1671. n_tested += i + 1;
  1672. break;
  1673. }
  1674. }
  1675. if (found) {
  1676. break;
  1677. }
  1678. if (n_tested >= n_ctx) {
  1679. //LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens);
  1680. return false;
  1681. }
  1682. }
  1683. for (uint32_t i = 0; i < n_tokens; i++) {
  1684. cache.cells[cache.head + i].pos = batch.pos[i];
  1685. for (int32_t j = 0; j < batch.n_seq_id[i]; j++) {
  1686. cache.cells[cache.head + i].seq_id.insert(batch.seq_id[i][j]);
  1687. }
  1688. }
  1689. cache.used += n_tokens;
  1690. return true;
  1691. }
  1692. // find how many cells are currently in use
  1693. static int32_t llama_kv_cache_cell_max(const struct llama_kv_cache & cache) {
  1694. for (uint32_t i = cache.size - 1; i > 0; --i) {
  1695. if (cache.cells[i].pos >= 0 && !cache.cells[i].seq_id.empty()) {
  1696. return i + 1;
  1697. }
  1698. }
  1699. return 0;
  1700. }
  1701. static void llama_kv_cache_clear(struct llama_kv_cache & cache) {
  1702. for (int32_t i = 0; i < (int32_t) cache.size; ++i) {
  1703. cache.cells[i].pos = -1;
  1704. cache.cells[i].seq_id.clear();
  1705. }
  1706. cache.head = 0;
  1707. cache.used = 0;
  1708. }
  1709. static void llama_kv_cache_seq_rm(
  1710. struct llama_kv_cache & cache,
  1711. llama_seq_id seq_id,
  1712. llama_pos p0,
  1713. llama_pos p1) {
  1714. uint32_t new_head = cache.size;
  1715. if (p0 < 0) p0 = 0;
  1716. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1717. for (uint32_t i = 0; i < cache.size; ++i) {
  1718. if (cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1719. if (seq_id < 0) {
  1720. cache.cells[i].seq_id.clear();
  1721. } else if (cache.cells[i].has_seq_id(seq_id)) {
  1722. cache.cells[i].seq_id.erase(seq_id);
  1723. } else {
  1724. continue;
  1725. }
  1726. if (cache.cells[i].seq_id.empty()) {
  1727. // keep count of the number of used cells
  1728. if (cache.cells[i].pos >= 0) cache.used--;
  1729. cache.cells[i].pos = -1;
  1730. if (new_head == cache.size) new_head = i;
  1731. }
  1732. }
  1733. }
  1734. // If we freed up a slot, set head to it so searching can start there.
  1735. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  1736. }
  1737. static void llama_kv_cache_seq_cp(
  1738. struct llama_kv_cache & cache,
  1739. llama_seq_id seq_id_src,
  1740. llama_seq_id seq_id_dst,
  1741. llama_pos p0,
  1742. llama_pos p1) {
  1743. if (p0 < 0) p0 = 0;
  1744. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1745. cache.head = 0;
  1746. for (uint32_t i = 0; i < cache.size; ++i) {
  1747. if (cache.cells[i].has_seq_id(seq_id_src) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1748. cache.cells[i].seq_id.insert(seq_id_dst);
  1749. }
  1750. }
  1751. }
  1752. static void llama_kv_cache_seq_keep(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  1753. uint32_t new_head = cache.size;
  1754. for (uint32_t i = 0; i < cache.size; ++i) {
  1755. if (!cache.cells[i].has_seq_id(seq_id)) {
  1756. if (cache.cells[i].pos >= 0) cache.used--;
  1757. cache.cells[i].pos = -1;
  1758. cache.cells[i].seq_id.clear();
  1759. if (new_head == cache.size) new_head = i;
  1760. } else {
  1761. cache.cells[i].seq_id.clear();
  1762. cache.cells[i].seq_id.insert(seq_id);
  1763. }
  1764. }
  1765. // If we freed up a slot, set head to it so searching can start there.
  1766. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  1767. }
  1768. static void llama_kv_cache_seq_shift(
  1769. struct llama_kv_cache & cache,
  1770. llama_seq_id seq_id,
  1771. llama_pos p0,
  1772. llama_pos p1,
  1773. llama_pos delta) {
  1774. uint32_t new_head = cache.size;
  1775. if (p0 < 0) p0 = 0;
  1776. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1777. for (uint32_t i = 0; i < cache.size; ++i) {
  1778. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1779. cache.has_shift = true;
  1780. cache.cells[i].pos += delta;
  1781. cache.cells[i].delta += delta;
  1782. if (cache.cells[i].pos < 0) {
  1783. if (!cache.cells[i].seq_id.empty()) cache.used--;
  1784. cache.cells[i].pos = -1;
  1785. cache.cells[i].seq_id.clear();
  1786. if (new_head == cache.size) new_head = i;
  1787. }
  1788. }
  1789. }
  1790. // If we freed up a slot, set head to it so searching can start there.
  1791. // Otherwise we just start the next search from the beginning.
  1792. cache.head = new_head != cache.size ? new_head : 0;
  1793. }
  1794. static void llama_kv_cache_seq_div(
  1795. struct llama_kv_cache & cache,
  1796. llama_seq_id seq_id,
  1797. llama_pos p0,
  1798. llama_pos p1,
  1799. int d) {
  1800. if (p0 < 0) p0 = 0;
  1801. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1802. for (uint32_t i = 0; i < cache.size; ++i) {
  1803. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1804. cache.has_shift = true;
  1805. {
  1806. llama_pos p_old = cache.cells[i].pos;
  1807. cache.cells[i].pos /= d;
  1808. cache.cells[i].delta += cache.cells[i].pos - p_old;
  1809. }
  1810. }
  1811. }
  1812. }
  1813. //
  1814. // model loading and saving
  1815. //
  1816. enum llama_fver {
  1817. GGUF_FILE_VERSION_V1 = 1,
  1818. GGUF_FILE_VERSION_V2 = 2,
  1819. GGUF_FILE_VERSION_V3 = 3,
  1820. };
  1821. static const char * llama_file_version_name(llama_fver version) {
  1822. switch (version) {
  1823. case GGUF_FILE_VERSION_V1: return "GGUF V1 (support until nov 2023)";
  1824. case GGUF_FILE_VERSION_V2: return "GGUF V2";
  1825. case GGUF_FILE_VERSION_V3: return "GGUF V3 (latest)";
  1826. }
  1827. return "unknown";
  1828. }
  1829. static std::string llama_format_tensor_shape(const std::vector<int64_t> & ne) {
  1830. char buf[256];
  1831. snprintf(buf, sizeof(buf), "%5" PRId64, ne.at(0));
  1832. for (size_t i = 1; i < ne.size(); i++) {
  1833. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, ne.at(i));
  1834. }
  1835. return buf;
  1836. }
  1837. static std::string llama_format_tensor_shape(const struct ggml_tensor * t) {
  1838. char buf[256];
  1839. snprintf(buf, sizeof(buf), "%5" PRId64, t->ne[0]);
  1840. for (int i = 1; i < GGML_MAX_DIMS; i++) {
  1841. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, t->ne[i]);
  1842. }
  1843. return buf;
  1844. }
  1845. namespace GGUFMeta {
  1846. template <typename T, gguf_type gt_, T (*gfun)(const gguf_context *, const int)>
  1847. struct GKV_Base_Type {
  1848. static constexpr gguf_type gt = gt_;
  1849. static T getter(const gguf_context * ctx, const int kid) {
  1850. return gfun(ctx, kid);
  1851. }
  1852. };
  1853. template<typename T> struct GKV_Base;
  1854. template<> struct GKV_Base<bool >: GKV_Base_Type<bool, GGUF_TYPE_BOOL, gguf_get_val_bool> {};
  1855. template<> struct GKV_Base<uint8_t >: GKV_Base_Type<uint8_t, GGUF_TYPE_UINT8, gguf_get_val_u8 > {};
  1856. template<> struct GKV_Base<uint16_t >: GKV_Base_Type<uint16_t, GGUF_TYPE_UINT16, gguf_get_val_u16 > {};
  1857. template<> struct GKV_Base<uint32_t >: GKV_Base_Type<uint32_t, GGUF_TYPE_UINT32, gguf_get_val_u32 > {};
  1858. template<> struct GKV_Base<uint64_t >: GKV_Base_Type<uint64_t, GGUF_TYPE_UINT64, gguf_get_val_u64 > {};
  1859. template<> struct GKV_Base<int8_t >: GKV_Base_Type<int8_t, GGUF_TYPE_INT8, gguf_get_val_i8 > {};
  1860. template<> struct GKV_Base<int16_t >: GKV_Base_Type<int16_t, GGUF_TYPE_INT16, gguf_get_val_i16 > {};
  1861. template<> struct GKV_Base<int32_t >: GKV_Base_Type<int32_t, GGUF_TYPE_INT32, gguf_get_val_i32 > {};
  1862. template<> struct GKV_Base<int64_t >: GKV_Base_Type<int64_t, GGUF_TYPE_INT64, gguf_get_val_i64 > {};
  1863. template<> struct GKV_Base<float >: GKV_Base_Type<float, GGUF_TYPE_FLOAT32, gguf_get_val_f32 > {};
  1864. template<> struct GKV_Base<double >: GKV_Base_Type<double, GGUF_TYPE_FLOAT64, gguf_get_val_f64 > {};
  1865. template<> struct GKV_Base<const char *>: GKV_Base_Type<const char *, GGUF_TYPE_STRING, gguf_get_val_str > {};
  1866. template<> struct GKV_Base<std::string> {
  1867. static constexpr gguf_type gt = GGUF_TYPE_STRING;
  1868. static std::string getter(const gguf_context * ctx, const int kid) {
  1869. return gguf_get_val_str(ctx, kid);
  1870. }
  1871. };
  1872. struct ArrayInfo{
  1873. const gguf_type gt;
  1874. const size_t length;
  1875. const void * data;
  1876. };
  1877. template<> struct GKV_Base<ArrayInfo> {
  1878. public:
  1879. static constexpr gguf_type gt = GGUF_TYPE_ARRAY;
  1880. static ArrayInfo getter(const gguf_context *ctx, const int k) {
  1881. return ArrayInfo {
  1882. gguf_get_arr_type(ctx, k),
  1883. size_t(gguf_get_arr_n(ctx, k)),
  1884. gguf_get_arr_data(ctx, k),
  1885. };
  1886. }
  1887. };
  1888. template<typename T>
  1889. class GKV: public GKV_Base<T> {
  1890. GKV() = delete;
  1891. public:
  1892. static T get_kv(const gguf_context * ctx, const int k) {
  1893. const enum gguf_type kt = gguf_get_kv_type(ctx, k);
  1894. if (kt != GKV::gt) {
  1895. throw std::runtime_error(format("key %s has wrong type %s but expected type %s",
  1896. gguf_get_key(ctx, k), gguf_type_name(kt), gguf_type_name(GKV::gt)));
  1897. }
  1898. return GKV::getter(ctx, k);
  1899. }
  1900. static const char * override_type_to_str(const llama_model_kv_override_type ty) {
  1901. switch (ty) {
  1902. case LLAMA_KV_OVERRIDE_BOOL: return "bool";
  1903. case LLAMA_KV_OVERRIDE_INT: return "int";
  1904. case LLAMA_KV_OVERRIDE_FLOAT: return "float";
  1905. }
  1906. return "unknown";
  1907. }
  1908. static bool validate_override(const llama_model_kv_override_type expected_type, const struct llama_model_kv_override *override) {
  1909. if (!override) { return false; }
  1910. if (override->tag == expected_type) {
  1911. LLAMA_LOG_INFO("%s: Using metadata override (%5s) '%s' = ",
  1912. __func__, override_type_to_str(override->tag), override->key);
  1913. switch (override->tag) {
  1914. case LLAMA_KV_OVERRIDE_BOOL: {
  1915. LLAMA_LOG_INFO("%s\n", override->bool_value ? "true" : "false");
  1916. } break;
  1917. case LLAMA_KV_OVERRIDE_INT: {
  1918. LLAMA_LOG_INFO("%" PRId64 "\n", override->int_value);
  1919. } break;
  1920. case LLAMA_KV_OVERRIDE_FLOAT: {
  1921. LLAMA_LOG_INFO("%.6f\n", override->float_value);
  1922. } break;
  1923. default:
  1924. // Shouldn't be possible to end up here, but just in case...
  1925. throw std::runtime_error(
  1926. format("Unsupported attempt to override %s type for metadata key %s\n",
  1927. override_type_to_str(override->tag), override->key));
  1928. }
  1929. return true;
  1930. }
  1931. LLAMA_LOG_WARN("%s: Warning: Bad metadata override type for key '%s', expected %s but got %s\n",
  1932. __func__, override->key, override_type_to_str(expected_type), override_type_to_str(override->tag));
  1933. return false;
  1934. }
  1935. template<typename OT>
  1936. static typename std::enable_if<std::is_same<OT, bool>::value, bool>::type
  1937. try_override(OT & target, const struct llama_model_kv_override *override) {
  1938. if (validate_override(LLAMA_KV_OVERRIDE_BOOL, override)) {
  1939. target = override->bool_value;
  1940. return true;
  1941. }
  1942. return false;
  1943. }
  1944. template<typename OT>
  1945. static typename std::enable_if<!std::is_same<OT, bool>::value && std::is_integral<OT>::value, bool>::type
  1946. try_override(OT & target, const struct llama_model_kv_override *override) {
  1947. if (validate_override(LLAMA_KV_OVERRIDE_INT, override)) {
  1948. target = override->int_value;
  1949. return true;
  1950. }
  1951. return false;
  1952. }
  1953. template<typename OT>
  1954. static typename std::enable_if<std::is_floating_point<OT>::value, bool>::type
  1955. try_override(T & target, const struct llama_model_kv_override *override) {
  1956. if (validate_override(LLAMA_KV_OVERRIDE_FLOAT, override)) {
  1957. target = override->float_value;
  1958. return true;
  1959. }
  1960. return false;
  1961. }
  1962. template<typename OT>
  1963. static typename std::enable_if<std::is_same<OT, std::string>::value, bool>::type
  1964. try_override(T & target, const struct llama_model_kv_override *override) {
  1965. (void)target;
  1966. (void)override;
  1967. if (!override) { return false; }
  1968. // Currently, we should never end up here so it would be a bug if we do.
  1969. throw std::runtime_error(format("Unsupported attempt to override string type for metadata key %s\n",
  1970. override ? override->key : "NULL"));
  1971. }
  1972. static bool set(const gguf_context * ctx, const int k, T & target, const struct llama_model_kv_override *override = nullptr) {
  1973. if (try_override<T>(target, override)) {
  1974. return true;
  1975. }
  1976. if (k < 0) { return false; }
  1977. target = get_kv(ctx, k);
  1978. return true;
  1979. }
  1980. static bool set(const gguf_context * ctx, const char * key, T & target, const struct llama_model_kv_override *override = nullptr) {
  1981. return set(ctx, gguf_find_key(ctx, key), target, override);
  1982. }
  1983. static bool set(const gguf_context * ctx, const std::string & key, T & target, const struct llama_model_kv_override *override = nullptr) {
  1984. return set(ctx, key.c_str(), target, override);
  1985. }
  1986. };
  1987. }
  1988. struct llama_model_loader {
  1989. int n_kv = 0;
  1990. int n_tensors = 0;
  1991. int n_created = 0;
  1992. int64_t n_elements = 0;
  1993. size_t n_bytes = 0;
  1994. bool use_mmap = false;
  1995. llama_file file;
  1996. llama_ftype ftype;
  1997. llama_fver fver;
  1998. std::unique_ptr<llama_mmap> mapping;
  1999. std::unordered_map<std::string, struct llama_model_kv_override> kv_overrides;
  2000. struct gguf_context * ctx_gguf = NULL;
  2001. struct ggml_context * ctx_meta = NULL;
  2002. std::string arch_name;
  2003. LLM_KV llm_kv = LLM_KV(LLM_ARCH_UNKNOWN);
  2004. llama_model_loader(const std::string & fname, bool use_mmap, const struct llama_model_kv_override * param_overrides_p) : file(fname.c_str(), "rb") {
  2005. int trace = 0;
  2006. if (getenv("LLAMA_TRACE")) {
  2007. trace = atoi(getenv("LLAMA_TRACE"));
  2008. }
  2009. struct gguf_init_params params = {
  2010. /*.no_alloc = */ true,
  2011. /*.ctx = */ &ctx_meta,
  2012. };
  2013. if (param_overrides_p != nullptr) {
  2014. for (const struct llama_model_kv_override *p = param_overrides_p; p->key[0] != 0; p++) {
  2015. kv_overrides.insert({std::string(p->key), *p});
  2016. }
  2017. }
  2018. ctx_gguf = gguf_init_from_file(fname.c_str(), params);
  2019. if (!ctx_gguf) {
  2020. throw std::runtime_error(format("%s: failed to load model from %s\n", __func__, fname.c_str()));
  2021. }
  2022. get_key(llm_kv(LLM_KV_GENERAL_ARCHITECTURE), arch_name, false);
  2023. llm_kv = LLM_KV(llm_arch_from_string(arch_name));
  2024. n_kv = gguf_get_n_kv(ctx_gguf);
  2025. n_tensors = gguf_get_n_tensors(ctx_gguf);
  2026. fver = (enum llama_fver ) gguf_get_version(ctx_gguf);
  2027. for (int i = 0; i < n_tensors; i++) {
  2028. const char * name = gguf_get_tensor_name(ctx_gguf, i);
  2029. struct ggml_tensor * t = ggml_get_tensor(ctx_meta, name);
  2030. n_elements += ggml_nelements(t);
  2031. n_bytes += ggml_nbytes(t);
  2032. }
  2033. LLAMA_LOG_INFO("%s: loaded meta data with %d key-value pairs and %d tensors from %s (version %s)\n",
  2034. __func__, n_kv, n_tensors, fname.c_str(), llama_file_version_name(fver));
  2035. // determine file type based on the number of tensors for each quantization and print meta data
  2036. // TODO: make optional
  2037. {
  2038. std::map<enum ggml_type, uint32_t> n_type;
  2039. uint32_t n_type_max = 0;
  2040. enum ggml_type type_max = GGML_TYPE_F32;
  2041. for (int i = 0; i < n_tensors; i++) {
  2042. enum ggml_type type = gguf_get_tensor_type(ctx_gguf, i);
  2043. n_type[type]++;
  2044. if (n_type_max < n_type[type]) {
  2045. n_type_max = n_type[type];
  2046. type_max = type;
  2047. }
  2048. if (trace > 0) {
  2049. struct ggml_tensor * meta = ggml_get_tensor(ctx_meta, gguf_get_tensor_name(ctx_gguf, i));
  2050. 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());
  2051. }
  2052. }
  2053. switch (type_max) {
  2054. case GGML_TYPE_F32: ftype = LLAMA_FTYPE_ALL_F32; break;
  2055. case GGML_TYPE_F16: ftype = LLAMA_FTYPE_MOSTLY_F16; break;
  2056. case GGML_TYPE_Q4_0: ftype = LLAMA_FTYPE_MOSTLY_Q4_0; break;
  2057. case GGML_TYPE_Q4_1: ftype = LLAMA_FTYPE_MOSTLY_Q4_1; break;
  2058. case GGML_TYPE_Q5_0: ftype = LLAMA_FTYPE_MOSTLY_Q5_0; break;
  2059. case GGML_TYPE_Q5_1: ftype = LLAMA_FTYPE_MOSTLY_Q5_1; break;
  2060. case GGML_TYPE_Q8_0: ftype = LLAMA_FTYPE_MOSTLY_Q8_0; break;
  2061. case GGML_TYPE_Q2_K: ftype = LLAMA_FTYPE_MOSTLY_Q2_K; break;
  2062. case GGML_TYPE_Q3_K: ftype = LLAMA_FTYPE_MOSTLY_Q3_K_M; break;
  2063. case GGML_TYPE_Q4_K: ftype = LLAMA_FTYPE_MOSTLY_Q4_K_M; break;
  2064. case GGML_TYPE_Q5_K: ftype = LLAMA_FTYPE_MOSTLY_Q5_K_M; break;
  2065. case GGML_TYPE_Q6_K: ftype = LLAMA_FTYPE_MOSTLY_Q6_K; break;
  2066. case GGML_TYPE_IQ2_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XXS; break;
  2067. case GGML_TYPE_IQ2_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XS; break;
  2068. case GGML_TYPE_IQ3_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ3_XXS; break;
  2069. default:
  2070. {
  2071. LLAMA_LOG_WARN("%s: unknown type %s\n", __func__, ggml_type_name(type_max));
  2072. ftype = LLAMA_FTYPE_ALL_F32;
  2073. } break;
  2074. }
  2075. // this is a way to mark that we have "guessed" the file type
  2076. ftype = (llama_ftype) (ftype | LLAMA_FTYPE_GUESSED);
  2077. {
  2078. const int kid = gguf_find_key(ctx_gguf, "general.file_type");
  2079. if (kid >= 0) {
  2080. ftype = (llama_ftype) gguf_get_val_u32(ctx_gguf, kid);
  2081. }
  2082. }
  2083. LLAMA_LOG_INFO("%s: Dumping metadata keys/values. Note: KV overrides do not apply in this output.\n", __func__);
  2084. for (int i = 0; i < n_kv; i++) {
  2085. const char * name = gguf_get_key(ctx_gguf, i);
  2086. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  2087. const std::string type_name =
  2088. type == GGUF_TYPE_ARRAY
  2089. ? 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))
  2090. : gguf_type_name(type);
  2091. std::string value = gguf_kv_to_str(ctx_gguf, i);
  2092. const size_t MAX_VALUE_LEN = 40;
  2093. if (value.size() > MAX_VALUE_LEN) {
  2094. value = format("%s...", value.substr(0, MAX_VALUE_LEN - 3).c_str());
  2095. }
  2096. replace_all(value, "\n", "\\n");
  2097. LLAMA_LOG_INFO("%s: - kv %3d: %42s %-16s = %s\n", __func__, i, name, type_name.c_str(), value.c_str());
  2098. }
  2099. // print type counts
  2100. for (auto & kv : n_type) {
  2101. if (kv.second == 0) {
  2102. continue;
  2103. }
  2104. LLAMA_LOG_INFO("%s: - type %4s: %4d tensors\n", __func__, ggml_type_name(kv.first), kv.second);
  2105. }
  2106. }
  2107. if (!llama_mmap::SUPPORTED) {
  2108. LLAMA_LOG_WARN("%s: mmap is not supported on this platform\n", __func__);
  2109. use_mmap = false;
  2110. }
  2111. this->use_mmap = use_mmap;
  2112. }
  2113. ~llama_model_loader() {
  2114. if (ctx_gguf) {
  2115. gguf_free(ctx_gguf);
  2116. }
  2117. if (ctx_meta) {
  2118. ggml_free(ctx_meta);
  2119. }
  2120. }
  2121. template<typename T>
  2122. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2123. get_arr_n(const std::string & key, T & result, const bool required = true) {
  2124. const int kid = gguf_find_key(ctx_gguf, key.c_str());
  2125. if (kid < 0) {
  2126. if (required) {
  2127. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2128. }
  2129. return false;
  2130. }
  2131. struct GGUFMeta::ArrayInfo arr_info =
  2132. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(ctx_gguf, kid);
  2133. result = arr_info.length;
  2134. return true;
  2135. }
  2136. template<typename T>
  2137. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2138. get_arr_n(const enum llm_kv kid, T & result, const bool required = true) {
  2139. return get_arr_n(llm_kv(kid), result, required);
  2140. }
  2141. template<typename T>
  2142. bool get_key(const std::string & key, T & result, const bool required = true) {
  2143. auto it = kv_overrides.find(key);
  2144. const struct llama_model_kv_override * override =
  2145. it != kv_overrides.end() ? &it->second : nullptr;
  2146. const bool found = GGUFMeta::GKV<T>::set(ctx_gguf, key, result, override);
  2147. if (required && !found) {
  2148. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2149. }
  2150. return found;
  2151. }
  2152. template<typename T>
  2153. bool get_key(const enum llm_kv kid, T & result, const bool required = true) {
  2154. return get_key(llm_kv(kid), result, required);
  2155. }
  2156. std::string get_arch_name() const {
  2157. return arch_name;
  2158. }
  2159. enum llm_arch get_arch() const {
  2160. return llm_kv.arch;
  2161. }
  2162. const char * get_tensor_name(int i) const {
  2163. return gguf_get_tensor_name(ctx_gguf, i);
  2164. }
  2165. struct ggml_tensor * get_tensor_meta(const char * name) const {
  2166. return ggml_get_tensor(ctx_meta, name);
  2167. }
  2168. struct ggml_tensor * get_tensor_meta(int i) const {
  2169. return get_tensor_meta(get_tensor_name(i));
  2170. }
  2171. struct ggml_tensor * create_tensor_for(struct ggml_context * ctx, struct ggml_tensor * meta) {
  2172. struct ggml_tensor * tensor = ggml_dup_tensor(ctx, meta);
  2173. ggml_set_name(tensor, ggml_get_name(meta));
  2174. n_created++;
  2175. return tensor;
  2176. }
  2177. struct ggml_tensor * create_tensor(struct ggml_context * ctx, const std::string & name, const std::vector<int64_t> & ne, bool required = true) {
  2178. struct ggml_tensor * cur = ggml_get_tensor(ctx_meta, name.c_str());
  2179. if (cur == NULL) {
  2180. if (!required) {
  2181. return NULL;
  2182. }
  2183. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
  2184. }
  2185. {
  2186. bool is_ok = true;
  2187. for (size_t i = 0; i < ne.size(); ++i) {
  2188. if (ne[i] != cur->ne[i]) {
  2189. is_ok = false;
  2190. break;
  2191. }
  2192. }
  2193. if (!is_ok) {
  2194. throw std::runtime_error(
  2195. format("%s: tensor '%s' has wrong shape; expected %s, got %s",
  2196. __func__, name.c_str(),
  2197. llama_format_tensor_shape(ne).c_str(),
  2198. llama_format_tensor_shape(cur).c_str()));
  2199. }
  2200. }
  2201. return create_tensor_for(ctx, cur);
  2202. }
  2203. void done_getting_tensors() const {
  2204. if (n_created != n_tensors) {
  2205. throw std::runtime_error(format("%s: wrong number of tensors; expected %d, got %d", __func__, n_tensors, n_created));
  2206. }
  2207. }
  2208. size_t file_offset(const char * name) const {
  2209. const int idx = gguf_find_tensor(ctx_gguf, name);
  2210. if (idx < 0) {
  2211. throw std::runtime_error(format("%s: tensor '%s' not found in the file", __func__, name));
  2212. }
  2213. return gguf_get_data_offset(ctx_gguf) + gguf_get_tensor_offset(ctx_gguf, idx);
  2214. }
  2215. void init_mapping(bool prefetch = true, llama_mlock * lmlock = nullptr) {
  2216. // prefetch the whole file - all the data is needed anyway
  2217. if (use_mmap) {
  2218. mapping.reset(new llama_mmap(&file, prefetch ? -1 : 0, ggml_is_numa()));
  2219. }
  2220. // compute the total size of all tensors for progress reporting
  2221. for (int i = 0; i < gguf_get_n_tensors(ctx_gguf); i++) {
  2222. struct ggml_tensor * cur = ggml_get_tensor(ctx_meta, gguf_get_tensor_name(ctx_gguf, i));
  2223. size_data += ggml_nbytes(cur);
  2224. }
  2225. if (use_mmap && mapping) {
  2226. if (lmlock) {
  2227. lmlock->init(mapping->addr);
  2228. }
  2229. mmap_used_first = mapping->size;
  2230. }
  2231. }
  2232. void get_mapping_range(size_t * first, size_t * last, ggml_context * ctx) const {
  2233. GGML_ASSERT(mapping);
  2234. *first = mapping->size;
  2235. *last = 0;
  2236. for (ggml_tensor * tensor = ggml_get_first_tensor(ctx); tensor; tensor = ggml_get_next_tensor(ctx, tensor)) {
  2237. const size_t offs = file_offset(ggml_get_name(tensor));
  2238. *first = std::min(*first, offs);
  2239. *last = std::max(*last, offs + ggml_nbytes(tensor));
  2240. }
  2241. }
  2242. // for backwards compatibility, does not support ggml-backend
  2243. void load_data_for(struct ggml_tensor * cur) const {
  2244. const size_t offs = file_offset(ggml_get_name(cur));
  2245. if (use_mmap && mapping) {
  2246. if (cur->data == nullptr) {
  2247. cur->data = (uint8_t *)mapping->addr + offs;
  2248. } else {
  2249. memcpy(cur->data, (uint8_t *)mapping->addr + offs, ggml_nbytes(cur));
  2250. }
  2251. } else {
  2252. GGML_ASSERT(cur->data != nullptr);
  2253. file.seek(offs, SEEK_SET);
  2254. file.read_raw(cur->data, ggml_nbytes(cur));
  2255. }
  2256. }
  2257. size_t size_done = 0;
  2258. size_t size_data = 0;
  2259. size_t mmap_used_first = -1;
  2260. size_t mmap_used_last = 0;
  2261. // Returns false if cancelled by progress_callback
  2262. 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) {
  2263. GGML_ASSERT(size_data != 0 && "call init_mapping() first");
  2264. std::vector<no_init<uint8_t>> read_buf;
  2265. for (int i = 0; i < gguf_get_n_tensors(ctx_gguf); i++) {
  2266. struct ggml_tensor * cur = ggml_get_tensor(ctx, gguf_get_tensor_name(ctx_gguf, i));
  2267. if (!cur) {
  2268. // some tensors may be allocated in a different context
  2269. continue;
  2270. }
  2271. if (progress_callback) {
  2272. if (!progress_callback((float) size_done / size_data, progress_callback_user_data)) {
  2273. return false;
  2274. }
  2275. }
  2276. const size_t offs = file_offset(ggml_get_name(cur));
  2277. if (use_mmap && mapping) {
  2278. if (buf_mmap && cur->data == nullptr) {
  2279. ggml_backend_tensor_alloc(buf_mmap, cur, (uint8_t *) mapping->addr + offs);
  2280. if (lmlock) {
  2281. lmlock->grow_to(offs + ggml_nbytes(cur));
  2282. }
  2283. mmap_used_first = std::min(mmap_used_first, offs);
  2284. mmap_used_last = std::max(mmap_used_last, offs + ggml_nbytes(cur));
  2285. } else {
  2286. ggml_backend_tensor_set(cur, (uint8_t *) mapping->addr + offs, 0, ggml_nbytes(cur));
  2287. }
  2288. } else {
  2289. if (ggml_backend_buffer_is_host(cur->buffer)) {
  2290. file.seek(offs, SEEK_SET);
  2291. file.read_raw(cur->data, ggml_nbytes(cur));
  2292. } else {
  2293. read_buf.resize(ggml_nbytes(cur));
  2294. file.seek(offs, SEEK_SET);
  2295. file.read_raw(read_buf.data(), ggml_nbytes(cur));
  2296. ggml_backend_tensor_set(cur, read_buf.data(), 0, ggml_nbytes(cur));
  2297. }
  2298. }
  2299. size_done += ggml_nbytes(cur);
  2300. }
  2301. // check if this is the last call and do final cleanup
  2302. if (size_done >= size_data) {
  2303. // unmap offloaded tensors and metadata
  2304. if (use_mmap && mapping) {
  2305. mapping->unmap_fragment(0, mmap_used_first);
  2306. if (mmap_used_last != 0) {
  2307. mapping->unmap_fragment(mmap_used_last, mapping->size);
  2308. }
  2309. }
  2310. if (progress_callback) {
  2311. // Even though the model is done loading, we still honor
  2312. // cancellation since we need to free allocations.
  2313. return progress_callback(1.0f, progress_callback_user_data);
  2314. }
  2315. }
  2316. return true;
  2317. }
  2318. };
  2319. //
  2320. // load LLaMA models
  2321. //
  2322. static const char * llama_model_arch_name(llm_arch arch) {
  2323. auto it = LLM_ARCH_NAMES.find(arch);
  2324. if (it == LLM_ARCH_NAMES.end()) {
  2325. return "unknown";
  2326. }
  2327. return it->second;
  2328. }
  2329. static std::string llama_model_ftype_name(llama_ftype ftype) {
  2330. if (ftype & LLAMA_FTYPE_GUESSED) {
  2331. return llama_model_ftype_name((enum llama_ftype) (ftype & ~LLAMA_FTYPE_GUESSED)) + " (guessed)";
  2332. }
  2333. switch (ftype) {
  2334. case LLAMA_FTYPE_ALL_F32: return "all F32";
  2335. case LLAMA_FTYPE_MOSTLY_F16: return "F16";
  2336. case LLAMA_FTYPE_MOSTLY_Q4_0: return "Q4_0";
  2337. case LLAMA_FTYPE_MOSTLY_Q4_1: return "Q4_1";
  2338. case LLAMA_FTYPE_MOSTLY_Q4_1_SOME_F16:
  2339. return "Q4_1, some F16";
  2340. case LLAMA_FTYPE_MOSTLY_Q5_0: return "Q5_0";
  2341. case LLAMA_FTYPE_MOSTLY_Q5_1: return "Q5_1";
  2342. case LLAMA_FTYPE_MOSTLY_Q8_0: return "Q8_0";
  2343. // K-quants
  2344. case LLAMA_FTYPE_MOSTLY_Q2_K: return "Q2_K - Medium";
  2345. case LLAMA_FTYPE_MOSTLY_Q2_K_S: return "Q2_K - Small";
  2346. case LLAMA_FTYPE_MOSTLY_Q3_K_S: return "Q3_K - Small";
  2347. case LLAMA_FTYPE_MOSTLY_Q3_K_M: return "Q3_K - Medium";
  2348. case LLAMA_FTYPE_MOSTLY_Q3_K_L: return "Q3_K - Large";
  2349. case LLAMA_FTYPE_MOSTLY_Q4_K_S: return "Q4_K - Small";
  2350. case LLAMA_FTYPE_MOSTLY_Q4_K_M: return "Q4_K - Medium";
  2351. case LLAMA_FTYPE_MOSTLY_Q5_K_S: return "Q5_K - Small";
  2352. case LLAMA_FTYPE_MOSTLY_Q5_K_M: return "Q5_K - Medium";
  2353. case LLAMA_FTYPE_MOSTLY_Q6_K: return "Q6_K";
  2354. case LLAMA_FTYPE_MOSTLY_IQ2_XXS:return "IQ2_XXS - 2.0625 bpw";
  2355. case LLAMA_FTYPE_MOSTLY_IQ2_XS: return "IQ2_XS - 2.3125 bpw";
  2356. case LLAMA_FTYPE_MOSTLY_Q3_K_XS:return "Q3_K - Extra small";
  2357. case LLAMA_FTYPE_MOSTLY_IQ3_XXS:return "IQ3_XXS - 3.0625 bpw";
  2358. default: return "unknown, may not work";
  2359. }
  2360. }
  2361. static const char * llama_model_type_name(e_model type) {
  2362. switch (type) {
  2363. case MODEL_1B: return "1B";
  2364. case MODEL_3B: return "3B";
  2365. case MODEL_7B: return "7B";
  2366. case MODEL_8B: return "8B";
  2367. case MODEL_13B: return "13B";
  2368. case MODEL_14B: return "14B";
  2369. case MODEL_15B: return "15B";
  2370. case MODEL_20B: return "20B";
  2371. case MODEL_30B: return "30B";
  2372. case MODEL_34B: return "34B";
  2373. case MODEL_40B: return "40B";
  2374. case MODEL_65B: return "65B";
  2375. case MODEL_70B: return "70B";
  2376. case MODEL_SMALL: return "0.1B";
  2377. case MODEL_MEDIUM: return "0.4B";
  2378. case MODEL_LARGE: return "0.8B";
  2379. case MODEL_XL: return "1.5B";
  2380. default: return "?B";
  2381. }
  2382. }
  2383. static const char * llama_model_vocab_type_name(enum llama_vocab_type type){
  2384. switch (type) {
  2385. case LLAMA_VOCAB_TYPE_SPM: return "SPM";
  2386. case LLAMA_VOCAB_TYPE_BPE: return "BPE";
  2387. default: return "unknown";
  2388. }
  2389. }
  2390. static void llm_load_arch(llama_model_loader & ml, llama_model & model) {
  2391. model.arch = ml.get_arch();
  2392. if (model.arch == LLM_ARCH_UNKNOWN) {
  2393. throw std::runtime_error("unknown model architecture: '" + ml.get_arch_name() + "'");
  2394. }
  2395. }
  2396. static void llm_load_hparams(
  2397. llama_model_loader & ml,
  2398. llama_model & model) {
  2399. auto & hparams = model.hparams;
  2400. const gguf_context * ctx = ml.ctx_gguf;
  2401. // get metadata as string
  2402. for (int i = 0; i < gguf_get_n_kv(ctx); i++) {
  2403. enum gguf_type type = gguf_get_kv_type(ctx, i);
  2404. if (type == GGUF_TYPE_ARRAY) {
  2405. continue;
  2406. }
  2407. const char * name = gguf_get_key(ctx, i);
  2408. const std::string value = gguf_kv_to_str(ctx, i);
  2409. model.gguf_kv.emplace(name, value);
  2410. }
  2411. // get general kv
  2412. ml.get_key(LLM_KV_GENERAL_NAME, model.name, false);
  2413. // get hparams kv
  2414. ml.get_arr_n(LLM_KV_TOKENIZER_LIST, hparams.n_vocab);
  2415. ml.get_key (LLM_KV_CONTEXT_LENGTH, hparams.n_ctx_train);
  2416. ml.get_key (LLM_KV_EMBEDDING_LENGTH, hparams.n_embd);
  2417. ml.get_key (LLM_KV_FEED_FORWARD_LENGTH, hparams.n_ff);
  2418. ml.get_key (LLM_KV_ATTENTION_HEAD_COUNT, hparams.n_head);
  2419. ml.get_key (LLM_KV_BLOCK_COUNT, hparams.n_layer);
  2420. ml.get_key (LLM_KV_EXPERT_COUNT, hparams.n_expert, false);
  2421. ml.get_key (LLM_KV_EXPERT_USED_COUNT, hparams.n_expert_used, false);
  2422. GGML_ASSERT(hparams.n_expert <= LLAMA_MAX_EXPERTS);
  2423. GGML_ASSERT(hparams.n_expert_used <= hparams.n_expert);
  2424. if (hparams.n_expert > 0) {
  2425. GGML_ASSERT(hparams.n_expert_used > 0);
  2426. } else {
  2427. GGML_ASSERT(hparams.n_expert_used == 0);
  2428. }
  2429. // n_head_kv is optional, default to n_head
  2430. hparams.n_head_kv = hparams.n_head;
  2431. ml.get_key(LLM_KV_ATTENTION_HEAD_COUNT_KV, hparams.n_head_kv, false);
  2432. bool rope_finetuned = false;
  2433. ml.get_key(LLM_KV_ROPE_SCALING_FINETUNED, rope_finetuned, false);
  2434. hparams.rope_finetuned = rope_finetuned;
  2435. hparams.n_yarn_orig_ctx = hparams.n_ctx_train;
  2436. ml.get_key(LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, hparams.n_yarn_orig_ctx, false);
  2437. // rope_freq_base (optional)
  2438. hparams.rope_freq_base_train = 10000.0f;
  2439. ml.get_key(LLM_KV_ROPE_FREQ_BASE, hparams.rope_freq_base_train, false);
  2440. std::string rope_scaling("linear");
  2441. ml.get_key(LLM_KV_ROPE_SCALING_TYPE, rope_scaling, false);
  2442. hparams.rope_scaling_type_train = llama_rope_scaling_type_from_string(rope_scaling);
  2443. GGML_ASSERT(hparams.rope_scaling_type_train != LLAMA_ROPE_SCALING_UNSPECIFIED);
  2444. // rope_freq_scale (inverse of the kv) is optional
  2445. float ropescale = 0.0f;
  2446. if (!ml.get_key(LLM_KV_ROPE_SCALING_FACTOR, ropescale, false)) {
  2447. // try the old key name
  2448. ml.get_key(LLM_KV_ROPE_SCALE_LINEAR, ropescale, false);
  2449. }
  2450. hparams.rope_freq_scale_train = ropescale == 0.0f ? 1.0f : 1.0f/ropescale;
  2451. // sanity check for n_rot (optional)
  2452. {
  2453. hparams.n_rot = hparams.n_embd / hparams.n_head;
  2454. ml.get_key(LLM_KV_ROPE_DIMENSION_COUNT, hparams.n_rot, false);
  2455. if (model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON) {
  2456. if (hparams.n_rot != hparams.n_embd / hparams.n_head) {
  2457. throw std::runtime_error(format("invalid n_rot: %u, expected %u", hparams.n_rot, hparams.n_embd / hparams.n_head));
  2458. }
  2459. }
  2460. // gpt-neox n_rot = rotary_pct * (n_embd / n_head)
  2461. // gpt-j n_rot = rotary_dim
  2462. }
  2463. hparams.n_embd_head_k = hparams.n_embd / hparams.n_head;
  2464. ml.get_key(LLM_KV_ATTENTION_KEY_LENGTH, hparams.n_embd_head_k, false);
  2465. hparams.n_embd_head_v = hparams.n_embd / hparams.n_head;
  2466. ml.get_key(LLM_KV_ATTENTION_VALUE_LENGTH, hparams.n_embd_head_v, false);
  2467. // arch-specific KVs
  2468. switch (model.arch) {
  2469. case LLM_ARCH_LLAMA:
  2470. {
  2471. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2472. switch (hparams.n_layer) {
  2473. case 22: model.type = e_model::MODEL_1B; break;
  2474. case 26: model.type = e_model::MODEL_3B; break;
  2475. case 32: model.type = e_model::MODEL_7B; break;
  2476. case 40: model.type = e_model::MODEL_13B; break;
  2477. case 48: model.type = e_model::MODEL_34B; break;
  2478. case 60: model.type = e_model::MODEL_30B; break;
  2479. case 80: model.type = hparams.n_head == hparams.n_head_kv ? e_model::MODEL_65B : e_model::MODEL_70B; break;
  2480. default: model.type = e_model::MODEL_UNKNOWN;
  2481. }
  2482. } break;
  2483. case LLM_ARCH_FALCON:
  2484. {
  2485. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2486. switch (hparams.n_layer) {
  2487. case 32: model.type = e_model::MODEL_7B; break;
  2488. case 60: model.type = e_model::MODEL_40B; break;
  2489. default: model.type = e_model::MODEL_UNKNOWN;
  2490. }
  2491. } break;
  2492. case LLM_ARCH_BAICHUAN:
  2493. {
  2494. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2495. switch (hparams.n_layer) {
  2496. case 32: model.type = e_model::MODEL_7B; break;
  2497. case 40: model.type = e_model::MODEL_13B; break;
  2498. default: model.type = e_model::MODEL_UNKNOWN;
  2499. }
  2500. } break;
  2501. case LLM_ARCH_STARCODER:
  2502. {
  2503. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2504. switch (hparams.n_layer) {
  2505. case 24: model.type = e_model::MODEL_1B; break;
  2506. case 36: model.type = e_model::MODEL_3B; break;
  2507. case 42: model.type = e_model::MODEL_7B; break;
  2508. case 40: model.type = e_model::MODEL_15B; break;
  2509. default: model.type = e_model::MODEL_UNKNOWN;
  2510. }
  2511. } break;
  2512. case LLM_ARCH_PERSIMMON:
  2513. {
  2514. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2515. switch (hparams.n_layer) {
  2516. case 36: model.type = e_model::MODEL_8B; break;
  2517. default: model.type = e_model::MODEL_UNKNOWN;
  2518. }
  2519. } break;
  2520. case LLM_ARCH_REFACT:
  2521. {
  2522. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2523. switch (hparams.n_layer) {
  2524. case 32: model.type = e_model::MODEL_1B; break;
  2525. default: model.type = e_model::MODEL_UNKNOWN;
  2526. }
  2527. } break;
  2528. case LLM_ARCH_BLOOM:
  2529. {
  2530. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2531. switch (hparams.n_layer) {
  2532. case 24: model.type = e_model::MODEL_1B; break;
  2533. case 30:
  2534. switch (hparams.n_embd) {
  2535. case 2560: model.type = e_model::MODEL_3B; break;
  2536. case 4096: model.type = e_model::MODEL_7B; break;
  2537. } break;
  2538. }
  2539. } break;
  2540. case LLM_ARCH_MPT:
  2541. {
  2542. hparams.f_clamp_kqv = 0.0f;
  2543. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2544. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv, false);
  2545. ml.get_key(LLM_KV_ATTENTION_MAX_ALIBI_BIAS, hparams.f_max_alibi_bias);
  2546. switch (hparams.n_layer) {
  2547. case 32: model.type = e_model::MODEL_7B; break;
  2548. case 48: model.type = e_model::MODEL_30B; break;
  2549. default: model.type = e_model::MODEL_UNKNOWN;
  2550. }
  2551. } break;
  2552. case LLM_ARCH_STABLELM:
  2553. {
  2554. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2555. switch (hparams.n_layer) {
  2556. case 24: model.type = e_model::MODEL_1B; break;
  2557. case 32: model.type = e_model::MODEL_3B; break;
  2558. default: model.type = e_model::MODEL_UNKNOWN;
  2559. }
  2560. } break;
  2561. case LLM_ARCH_QWEN:
  2562. {
  2563. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2564. switch (hparams.n_layer) {
  2565. case 32: model.type = e_model::MODEL_7B; break;
  2566. case 40: model.type = e_model::MODEL_13B; break;
  2567. default: model.type = e_model::MODEL_UNKNOWN;
  2568. }
  2569. } break;
  2570. case LLM_ARCH_QWEN2:
  2571. {
  2572. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2573. switch (hparams.n_layer) {
  2574. case 24: model.type = hparams.n_embd == 1024 ? e_model::MODEL_0_5B : e_model::MODEL_1B; break;
  2575. case 32: model.type = e_model::MODEL_7B; break;
  2576. case 40: model.type = hparams.n_head == 20 ? e_model::MODEL_4B : e_model::MODEL_13B; break;
  2577. case 80: model.type = e_model::MODEL_70B; break;
  2578. default: model.type = e_model::MODEL_UNKNOWN;
  2579. }
  2580. } break;
  2581. case LLM_ARCH_PHI2:
  2582. {
  2583. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2584. switch (hparams.n_layer) {
  2585. case 24: model.type = e_model::MODEL_1B; break;
  2586. case 32: model.type = e_model::MODEL_3B; break;
  2587. default: model.type = e_model::MODEL_UNKNOWN;
  2588. }
  2589. } break;
  2590. case LLM_ARCH_PLAMO:
  2591. {
  2592. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2593. switch (hparams.n_layer) {
  2594. case 40: model.type = e_model::MODEL_13B; break;
  2595. default: model.type = e_model::MODEL_UNKNOWN;
  2596. }
  2597. } break;
  2598. case LLM_ARCH_GPT2:
  2599. {
  2600. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2601. switch (hparams.n_layer) {
  2602. case 12: model.type = e_model::MODEL_SMALL; break;
  2603. case 24: model.type = e_model::MODEL_MEDIUM; break;
  2604. case 36: model.type = e_model::MODEL_LARGE; break;
  2605. case 48: model.type = e_model::MODEL_XL; break;
  2606. default: model.type = e_model::MODEL_UNKNOWN;
  2607. }
  2608. } break;
  2609. case LLM_ARCH_CODESHELL:
  2610. {
  2611. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2612. switch (hparams.n_layer) {
  2613. case 42: model.type = e_model::MODEL_SMALL; break;
  2614. default: model.type = e_model::MODEL_UNKNOWN;
  2615. }
  2616. } break;
  2617. case LLM_ARCH_ORION:
  2618. {
  2619. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2620. switch (hparams.n_layer) {
  2621. case 40: model.type = e_model::MODEL_14B; break;
  2622. default: model.type = e_model::MODEL_UNKNOWN;
  2623. }
  2624. } break;
  2625. case LLM_ARCH_INTERNLM2:
  2626. {
  2627. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2628. switch (hparams.n_layer) {
  2629. case 32: model.type = e_model::MODEL_7B; break;
  2630. case 48: model.type = e_model::MODEL_20B; break;
  2631. default: model.type = e_model::MODEL_UNKNOWN;
  2632. }
  2633. } break;
  2634. default: (void)0;
  2635. }
  2636. model.ftype = ml.ftype;
  2637. }
  2638. // TODO: This should probably be in llama.h
  2639. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special = false);
  2640. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch);
  2641. static void llm_load_vocab(
  2642. llama_model_loader & ml,
  2643. llama_model & model) {
  2644. auto & vocab = model.vocab;
  2645. struct gguf_context * ctx = ml.ctx_gguf;
  2646. const auto kv = LLM_KV(model.arch);
  2647. const int token_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_LIST).c_str());
  2648. if (token_idx == -1) {
  2649. throw std::runtime_error("cannot find tokenizer vocab in model file\n");
  2650. }
  2651. const float * scores = nullptr;
  2652. const int score_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_SCORES).c_str());
  2653. if (score_idx != -1) {
  2654. scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
  2655. }
  2656. const int * toktypes = nullptr;
  2657. const int toktype_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE).c_str());
  2658. if (toktype_idx != -1) {
  2659. toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
  2660. }
  2661. // determine vocab type
  2662. {
  2663. std::string tokenizer_name;
  2664. ml.get_key(LLM_KV_TOKENIZER_MODEL, tokenizer_name);
  2665. if (tokenizer_name == "llama") {
  2666. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  2667. // default special tokens
  2668. vocab.special_bos_id = 1;
  2669. vocab.special_eos_id = 2;
  2670. vocab.special_unk_id = 0;
  2671. vocab.special_sep_id = -1;
  2672. vocab.special_pad_id = -1;
  2673. const int add_space_prefix_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_ADD_PREFIX).c_str());
  2674. if (add_space_prefix_keyidx != -1) {
  2675. vocab.add_space_prefix = gguf_get_val_bool(ctx, add_space_prefix_keyidx);
  2676. } // The default value of add_space_prefix is true.
  2677. } else if (tokenizer_name == "gpt2") {
  2678. vocab.type = LLAMA_VOCAB_TYPE_BPE;
  2679. // read bpe merges and populate bpe ranks
  2680. const int merges_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_MERGES).c_str());
  2681. if (merges_keyidx == -1) {
  2682. throw std::runtime_error("cannot find tokenizer merges in model file\n");
  2683. }
  2684. const int n_merges = gguf_get_arr_n(ctx, merges_keyidx);
  2685. for (int i = 0; i < n_merges; i++) {
  2686. const std::string word = gguf_get_arr_str(ctx, merges_keyidx, i);
  2687. GGML_ASSERT(codepoints_from_utf8(word).size() > 0);
  2688. std::string first;
  2689. std::string second;
  2690. const size_t pos = word.find(' ', 1);
  2691. if (pos != std::string::npos) {
  2692. first = word.substr(0, pos);
  2693. second = word.substr(pos + 1);
  2694. }
  2695. vocab.bpe_ranks.emplace(std::make_pair(first, second), i);
  2696. }
  2697. // default special tokens
  2698. vocab.special_bos_id = 11;
  2699. vocab.special_eos_id = 11;
  2700. vocab.special_unk_id = -1;
  2701. vocab.special_sep_id = -1;
  2702. vocab.special_pad_id = -1;
  2703. } else {
  2704. LLAMA_LOG_WARN("%s: unknown tokenizer: '%s'", __func__, tokenizer_name.c_str());
  2705. LLAMA_LOG_WARN("%s: using default tokenizer: 'llama'", __func__);
  2706. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  2707. }
  2708. }
  2709. const uint32_t n_vocab = gguf_get_arr_n(ctx, token_idx);
  2710. vocab.id_to_token.resize(n_vocab);
  2711. for (uint32_t i = 0; i < n_vocab; i++) {
  2712. std::string word = gguf_get_arr_str(ctx, token_idx, i);
  2713. GGML_ASSERT(codepoints_from_utf8(word).size() > 0);
  2714. vocab.token_to_id[word] = i;
  2715. auto & token_data = vocab.id_to_token[i];
  2716. token_data.text = std::move(word);
  2717. token_data.score = scores ? scores[i] : 0.0f;
  2718. token_data.type = toktypes ? (llama_token_type) toktypes[i] : LLAMA_TOKEN_TYPE_NORMAL;
  2719. }
  2720. GGML_ASSERT(vocab.id_to_token.size() == vocab.token_to_id.size());
  2721. // determine the newline token: LLaMA "<0x0A>" == 10 == '\n', Falcon 193 == '\n'
  2722. if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  2723. vocab.linefeed_id = llama_byte_to_token(vocab, '\n');
  2724. } else {
  2725. const std::vector<int> ids = llama_tokenize_internal(vocab, "\u010A", false);
  2726. GGML_ASSERT(!ids.empty() && "model vocab missing newline token");
  2727. vocab.linefeed_id = ids[0];
  2728. }
  2729. // special tokens
  2730. {
  2731. const std::vector<std::pair<enum llm_kv, int32_t &>> special_token_types = {
  2732. { LLM_KV_TOKENIZER_BOS_ID, vocab.special_bos_id },
  2733. { LLM_KV_TOKENIZER_EOS_ID, vocab.special_eos_id },
  2734. { LLM_KV_TOKENIZER_UNK_ID, vocab.special_unk_id },
  2735. { LLM_KV_TOKENIZER_SEP_ID, vocab.special_sep_id },
  2736. { LLM_KV_TOKENIZER_PAD_ID, vocab.special_pad_id },
  2737. };
  2738. for (const auto & it : special_token_types) {
  2739. const std::string & key = kv(std::get<0>(it));
  2740. int32_t & id = std::get<1>(it);
  2741. uint32_t new_id;
  2742. if (!ml.get_key(std::get<0>(it), new_id, false)) {
  2743. continue;
  2744. }
  2745. if (new_id >= vocab.id_to_token.size()) {
  2746. LLAMA_LOG_WARN("%s: bad special token: '%s' = %ud, using default id %d\n",
  2747. __func__, key.c_str(), new_id, id);
  2748. } else {
  2749. id = new_id;
  2750. }
  2751. }
  2752. // Handle add_bos_token and add_eos_token
  2753. {
  2754. bool temp = true;
  2755. if (ml.get_key(LLM_KV_TOKENIZER_ADD_BOS, temp, false)) {
  2756. vocab.special_add_bos = int(temp);
  2757. }
  2758. if (ml.get_key(LLM_KV_TOKENIZER_ADD_EOS, temp, false)) {
  2759. vocab.special_add_eos = int(temp);
  2760. }
  2761. }
  2762. }
  2763. // build special tokens cache
  2764. {
  2765. // TODO: It is unclear (to me) at this point, whether special tokes are guaranteed to be of a deterministic type,
  2766. // and will always be correctly labeled in 'added_tokens.json' etc.
  2767. // The assumption is, since special tokens aren't meant to be exposed to end user, they are designed
  2768. // to be unmatchable by the tokenizer, therefore tokens from the vocab, which are unmatchable by the tokenizer
  2769. // are special tokens.
  2770. // From testing, this appears to correlate 1:1 with special tokens.
  2771. //
  2772. // Counting special tokens and verifying in only one direction
  2773. // is sufficient to detect difference in those two sets.
  2774. //
  2775. uint32_t special_tokens_count_by_type = 0;
  2776. uint32_t special_tokens_count_from_verification = 0;
  2777. bool special_tokens_definition_mismatch = false;
  2778. for (const auto & t : vocab.token_to_id) {
  2779. const auto & token = t.first;
  2780. const auto & id = t.second;
  2781. // Count all non-normal tokens in the vocab while iterating
  2782. if (vocab.id_to_token[id].type != LLAMA_TOKEN_TYPE_NORMAL) {
  2783. special_tokens_count_by_type++;
  2784. }
  2785. // Skip single character tokens
  2786. if (token.length() > 1) {
  2787. bool is_tokenizable = false;
  2788. // Split token string representation in two, in all possible ways
  2789. // and check if both halves can be matched to a valid token
  2790. for (unsigned i = 1; i < token.length();) {
  2791. const auto left = token.substr(0, i);
  2792. const auto right = token.substr(i);
  2793. // check if we didnt partition in the middle of a utf sequence
  2794. auto utf = utf8_len(left.at(left.length() - 1));
  2795. if (utf == 1) {
  2796. if (vocab.token_to_id.find(left) != vocab.token_to_id.end() &&
  2797. vocab.token_to_id.find(right) != vocab.token_to_id.end() ) {
  2798. is_tokenizable = true;
  2799. break;
  2800. }
  2801. i++;
  2802. } else {
  2803. // skip over the rest of multibyte utf sequence
  2804. i += utf - 1;
  2805. }
  2806. }
  2807. if (!is_tokenizable) {
  2808. // Some tokens are multibyte, but they are utf sequences with equivalent text length of 1
  2809. // it's faster to re-filter them here, since there are way less candidates now
  2810. // Calculate a total "utf" length of a token string representation
  2811. size_t utf8_str_len = 0;
  2812. for (unsigned i = 0; i < token.length();) {
  2813. utf8_str_len++;
  2814. i += utf8_len(token.at(i));
  2815. }
  2816. // And skip the ones which are one character
  2817. if (utf8_str_len > 1) {
  2818. // At this point what we have left are special tokens only
  2819. vocab.special_tokens_cache[token] = id;
  2820. // Count manually found special tokens
  2821. special_tokens_count_from_verification++;
  2822. // If this manually found special token is not marked as such, flag a mismatch
  2823. if (vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL) {
  2824. special_tokens_definition_mismatch = true;
  2825. }
  2826. }
  2827. }
  2828. }
  2829. }
  2830. if (special_tokens_definition_mismatch || special_tokens_count_from_verification != special_tokens_count_by_type) {
  2831. LLAMA_LOG_WARN("%s: mismatch in special tokens definition ( %u/%zu vs %u/%zu ).\n",
  2832. __func__,
  2833. special_tokens_count_from_verification, vocab.id_to_token.size(),
  2834. special_tokens_count_by_type, vocab.id_to_token.size()
  2835. );
  2836. } else {
  2837. LLAMA_LOG_INFO("%s: special tokens definition check successful ( %u/%zu ).\n",
  2838. __func__,
  2839. special_tokens_count_from_verification, vocab.id_to_token.size()
  2840. );
  2841. }
  2842. }
  2843. }
  2844. static void llm_load_print_meta(llama_model_loader & ml, llama_model & model) {
  2845. const auto & hparams = model.hparams;
  2846. const auto & vocab = model.vocab;
  2847. const char * rope_scaling_type = LLAMA_ROPE_SCALING_TYPES.at(hparams.rope_scaling_type_train);
  2848. // hparams
  2849. LLAMA_LOG_INFO("%s: format = %s\n", __func__, llama_file_version_name(ml.fver));
  2850. LLAMA_LOG_INFO("%s: arch = %s\n", __func__, LLM_ARCH_NAMES.at(model.arch));
  2851. LLAMA_LOG_INFO("%s: vocab type = %s\n", __func__, llama_model_vocab_type_name(vocab.type));
  2852. LLAMA_LOG_INFO("%s: n_vocab = %u\n", __func__, hparams.n_vocab);
  2853. LLAMA_LOG_INFO("%s: n_merges = %u\n", __func__, (int) vocab.bpe_ranks.size());
  2854. LLAMA_LOG_INFO("%s: n_ctx_train = %u\n", __func__, hparams.n_ctx_train);
  2855. LLAMA_LOG_INFO("%s: n_embd = %u\n", __func__, hparams.n_embd);
  2856. LLAMA_LOG_INFO("%s: n_head = %u\n", __func__, hparams.n_head);
  2857. LLAMA_LOG_INFO("%s: n_head_kv = %u\n", __func__, hparams.n_head_kv);
  2858. LLAMA_LOG_INFO("%s: n_layer = %u\n", __func__, hparams.n_layer);
  2859. LLAMA_LOG_INFO("%s: n_rot = %u\n", __func__, hparams.n_rot);
  2860. LLAMA_LOG_INFO("%s: n_embd_head_k = %u\n", __func__, hparams.n_embd_head_k);
  2861. LLAMA_LOG_INFO("%s: n_embd_head_v = %u\n", __func__, hparams.n_embd_head_v);
  2862. LLAMA_LOG_INFO("%s: n_gqa = %u\n", __func__, hparams.n_gqa());
  2863. LLAMA_LOG_INFO("%s: n_embd_k_gqa = %u\n", __func__, hparams.n_embd_k_gqa());
  2864. LLAMA_LOG_INFO("%s: n_embd_v_gqa = %u\n", __func__, hparams.n_embd_v_gqa());
  2865. LLAMA_LOG_INFO("%s: f_norm_eps = %.1e\n", __func__, hparams.f_norm_eps);
  2866. LLAMA_LOG_INFO("%s: f_norm_rms_eps = %.1e\n", __func__, hparams.f_norm_rms_eps);
  2867. LLAMA_LOG_INFO("%s: f_clamp_kqv = %.1e\n", __func__, hparams.f_clamp_kqv);
  2868. LLAMA_LOG_INFO("%s: f_max_alibi_bias = %.1e\n", __func__, hparams.f_max_alibi_bias);
  2869. LLAMA_LOG_INFO("%s: n_ff = %u\n", __func__, hparams.n_ff);
  2870. LLAMA_LOG_INFO("%s: n_expert = %u\n", __func__, hparams.n_expert);
  2871. LLAMA_LOG_INFO("%s: n_expert_used = %u\n", __func__, hparams.n_expert_used);
  2872. LLAMA_LOG_INFO("%s: rope scaling = %s\n", __func__, rope_scaling_type);
  2873. LLAMA_LOG_INFO("%s: freq_base_train = %.1f\n", __func__, hparams.rope_freq_base_train);
  2874. LLAMA_LOG_INFO("%s: freq_scale_train = %g\n", __func__, hparams.rope_freq_scale_train);
  2875. LLAMA_LOG_INFO("%s: n_yarn_orig_ctx = %u\n", __func__, hparams.n_yarn_orig_ctx);
  2876. LLAMA_LOG_INFO("%s: rope_finetuned = %s\n", __func__, hparams.rope_finetuned ? "yes" : "unknown");
  2877. LLAMA_LOG_INFO("%s: model type = %s\n", __func__, llama_model_type_name(model.type));
  2878. LLAMA_LOG_INFO("%s: model ftype = %s\n", __func__, llama_model_ftype_name(model.ftype).c_str());
  2879. if (ml.n_elements >= 1e12) {
  2880. LLAMA_LOG_INFO("%s: model params = %.2f T\n", __func__, ml.n_elements*1e-12);
  2881. } else if (ml.n_elements >= 1e9) {
  2882. LLAMA_LOG_INFO("%s: model params = %.2f B\n", __func__, ml.n_elements*1e-9);
  2883. } else if (ml.n_elements >= 1e6) {
  2884. LLAMA_LOG_INFO("%s: model params = %.2f M\n", __func__, ml.n_elements*1e-6);
  2885. } else {
  2886. LLAMA_LOG_INFO("%s: model params = %.2f K\n", __func__, ml.n_elements*1e-3);
  2887. }
  2888. if (ml.n_bytes < GiB) {
  2889. 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);
  2890. } else {
  2891. 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);
  2892. }
  2893. // general kv
  2894. LLAMA_LOG_INFO("%s: general.name = %s\n", __func__, model.name.c_str());
  2895. // special tokens
  2896. 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() ); }
  2897. 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() ); }
  2898. 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() ); }
  2899. 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() ); }
  2900. 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() ); }
  2901. 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() ); }
  2902. }
  2903. // Returns false if cancelled by progress_callback
  2904. static bool llm_load_tensors(
  2905. llama_model_loader & ml,
  2906. llama_model & model,
  2907. int n_gpu_layers,
  2908. enum llama_split_mode split_mode,
  2909. int main_gpu,
  2910. const float * tensor_split,
  2911. bool use_mlock,
  2912. llama_progress_callback progress_callback,
  2913. void * progress_callback_user_data) {
  2914. model.t_start_us = ggml_time_us();
  2915. auto & hparams = model.hparams;
  2916. model.split_mode = split_mode;
  2917. model.main_gpu = main_gpu;
  2918. model.n_gpu_layers = n_gpu_layers;
  2919. const int64_t n_layer = hparams.n_layer;
  2920. const int64_t i_gpu_start = std::max((int64_t) hparams.n_layer - n_gpu_layers, (int64_t) 0);
  2921. // there is very little benefit to offloading the input layer, so always keep it on the CPU
  2922. model.buft_input = llama_default_buffer_type_cpu(true);
  2923. model.buft_layer.resize(n_layer);
  2924. // assign cpu layers
  2925. for (int64_t i = 0; i < i_gpu_start; ++i) {
  2926. model.buft_layer[i] = llama_default_buffer_type_cpu(true);
  2927. }
  2928. #ifdef GGML_USE_CUBLAS
  2929. if (split_mode == LLAMA_SPLIT_LAYER) {
  2930. // calculate the split points
  2931. int device_count = ggml_backend_cuda_get_device_count();
  2932. bool all_zero = tensor_split == nullptr || std::all_of(tensor_split, tensor_split + device_count, [](float x) { return x == 0.0f; });
  2933. float splits[GGML_CUDA_MAX_DEVICES];
  2934. if (all_zero) {
  2935. // default split, by free memory
  2936. for (int i = 0; i < device_count; ++i) {
  2937. size_t total;
  2938. size_t free;
  2939. ggml_backend_cuda_get_device_memory(i, &total, &free);
  2940. splits[i] = free;
  2941. }
  2942. } else {
  2943. std::copy(tensor_split, tensor_split + device_count, splits);
  2944. }
  2945. // sum and normalize the splits to get the split points
  2946. float split_sum = 0.0f;
  2947. for (int i = 0; i < device_count; ++i) {
  2948. split_sum += splits[i];
  2949. splits[i] = split_sum;
  2950. }
  2951. for (int i = 0; i < device_count; ++i) {
  2952. splits[i] /= split_sum;
  2953. }
  2954. // assign the repeating layers to the devices according to the splits
  2955. int act_gpu_layers = std::min(n_gpu_layers, (int)n_layer + 1);
  2956. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  2957. int layer_gpu = std::upper_bound(splits, splits + device_count, float(i - i_gpu_start)/act_gpu_layers) - splits;
  2958. model.buft_layer[i] = llama_default_buffer_type_offload(layer_gpu);
  2959. }
  2960. // assign the output layer
  2961. if (n_gpu_layers > n_layer) {
  2962. int layer_gpu = std::upper_bound(splits, splits + device_count, float(act_gpu_layers - 1)/act_gpu_layers) - splits;
  2963. model.buft_output = llama_default_buffer_type_offload(layer_gpu);
  2964. } else {
  2965. model.buft_output = llama_default_buffer_type_cpu(true);
  2966. }
  2967. } else
  2968. #endif
  2969. {
  2970. ggml_backend_buffer_type_t split_buft;
  2971. if (split_mode == LLAMA_SPLIT_ROW) {
  2972. split_buft = llama_default_buffer_type_split(main_gpu, tensor_split);
  2973. } else {
  2974. // LLAMA_SPLIT_NONE or LLAMA_SPLIT_LAYER in backends where it is not supported
  2975. split_buft = llama_default_buffer_type_offload(main_gpu);
  2976. }
  2977. // assign the repeating layers
  2978. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  2979. model.buft_layer[i] = {
  2980. split_buft,
  2981. llama_default_buffer_type_offload(main_gpu)
  2982. };
  2983. }
  2984. // assign the output layer
  2985. if (n_gpu_layers > n_layer) {
  2986. model.buft_output = {
  2987. split_buft,
  2988. llama_default_buffer_type_offload(main_gpu)
  2989. };
  2990. } else {
  2991. model.buft_output = llama_default_buffer_type_cpu(true);
  2992. }
  2993. }
  2994. // count used buffer types
  2995. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  2996. buft_layer_count[model.buft_input.buft]++;
  2997. buft_layer_count[model.buft_input.buft_matrix]++;
  2998. buft_layer_count[model.buft_output.buft]++;
  2999. buft_layer_count[model.buft_output.buft_matrix]++;
  3000. for (int64_t i = 0; i < n_layer; ++i) {
  3001. buft_layer_count[model.buft_layer[i].buft]++;
  3002. buft_layer_count[model.buft_layer[i].buft_matrix]++;
  3003. }
  3004. // create one context per buffer type
  3005. size_t ctx_size = ggml_tensor_overhead()*ml.n_tensors;
  3006. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  3007. for (auto & it : buft_layer_count) {
  3008. struct ggml_init_params params = {
  3009. /*.mem_size =*/ ctx_size,
  3010. /*.mem_buffer =*/ NULL,
  3011. /*.no_alloc =*/ true,
  3012. };
  3013. ggml_context * ctx = ggml_init(params);
  3014. if (!ctx) {
  3015. throw std::runtime_error(format("failed to create context"));
  3016. }
  3017. ctx_map[it.first] = ctx;
  3018. model.ctxs.push_back(ctx);
  3019. }
  3020. LLAMA_LOG_INFO("%s: ggml ctx size = %7.2f MiB\n", __func__, model.ctxs.size()*ctx_size/1024.0/1024.0);
  3021. // create tensors for the weights
  3022. {
  3023. const int64_t n_embd = hparams.n_embd;
  3024. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3025. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  3026. const int64_t n_embd_gqa = n_embd_v_gqa;
  3027. const int64_t n_vocab = hparams.n_vocab;
  3028. const int64_t n_ff = hparams.n_ff;
  3029. GGML_ASSERT(n_embd_gqa == n_embd_k_gqa);
  3030. ggml_context * ctx_input = ctx_map.at(model.buft_input.buft);
  3031. ggml_context * ctx_output = ctx_map.at(model.buft_output.buft);
  3032. ggml_context * ctx_output_split = ctx_map.at(model.buft_output.buft_matrix);
  3033. auto ctx_for_layer = [&](int i) { return ctx_map.at(model.buft_layer[i].buft); };
  3034. auto ctx_for_layer_split = [&](int i) { return ctx_map.at(model.buft_layer[i].buft_matrix); };
  3035. model.layers.resize(n_layer);
  3036. const auto tn = LLM_TN(model.arch);
  3037. switch (model.arch) {
  3038. case LLM_ARCH_LLAMA:
  3039. case LLM_ARCH_REFACT:
  3040. {
  3041. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3042. // output
  3043. {
  3044. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3045. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3046. }
  3047. for (int i = 0; i < n_layer; ++i) {
  3048. ggml_context * ctx_layer = ctx_for_layer(i);
  3049. ggml_context * ctx_split = ctx_for_layer_split(i);
  3050. auto & layer = model.layers[i];
  3051. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3052. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3053. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3054. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3055. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3056. // optional bias tensors
  3057. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, false);
  3058. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, false);
  3059. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, false);
  3060. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, false);
  3061. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3062. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd}, false);
  3063. if (layer.ffn_gate_inp == nullptr) {
  3064. GGML_ASSERT(hparams.n_expert == 0);
  3065. GGML_ASSERT(hparams.n_expert_used == 0);
  3066. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3067. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3068. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3069. } else {
  3070. GGML_ASSERT(hparams.n_expert > 0);
  3071. GGML_ASSERT(hparams.n_expert_used > 0);
  3072. // MoE branch
  3073. for (uint32_t x = 0; x < hparams.n_expert; ++x) {
  3074. layer.ffn_gate_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, x), {n_embd, n_ff});
  3075. layer.ffn_down_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, x), { n_ff, n_embd});
  3076. layer.ffn_up_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, x), {n_embd, n_ff});
  3077. }
  3078. }
  3079. }
  3080. } break;
  3081. case LLM_ARCH_BAICHUAN:
  3082. {
  3083. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3084. {
  3085. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3086. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3087. }
  3088. for (int i = 0; i < n_layer; ++i) {
  3089. ggml_context * ctx_layer = ctx_for_layer(i);
  3090. ggml_context * ctx_split = ctx_for_layer_split(i);
  3091. auto & layer = model.layers[i];
  3092. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3093. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3094. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3095. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3096. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3097. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3098. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3099. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3100. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3101. }
  3102. } break;
  3103. case LLM_ARCH_FALCON:
  3104. {
  3105. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3106. // output
  3107. {
  3108. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3109. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3110. if (gguf_find_tensor(ml.ctx_gguf, tn(LLM_TENSOR_OUTPUT, "weight").c_str()) >= 0) {
  3111. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3112. } else {
  3113. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}); // needs to be on GPU
  3114. ml.n_created--; // artificial tensor
  3115. }
  3116. }
  3117. for (int i = 0; i < n_layer; ++i) {
  3118. ggml_context * ctx_layer = ctx_for_layer(i);
  3119. ggml_context * ctx_split = ctx_for_layer_split(i);
  3120. auto & layer = model.layers[i];
  3121. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3122. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3123. if (gguf_find_tensor(ml.ctx_gguf, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i).c_str()) >= 0) {
  3124. layer.attn_norm_2 = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i), {n_embd});
  3125. layer.attn_norm_2_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "bias", i), {n_embd});
  3126. }
  3127. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3128. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3129. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3130. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3131. }
  3132. } break;
  3133. case LLM_ARCH_STARCODER:
  3134. {
  3135. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3136. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3137. // output
  3138. {
  3139. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3140. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3141. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3142. }
  3143. for (int i = 0; i < n_layer; ++i) {
  3144. ggml_context * ctx_layer = ctx_for_layer(i);
  3145. ggml_context * ctx_split = ctx_for_layer_split(i);
  3146. auto & layer = model.layers[i];
  3147. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3148. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3149. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3150. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3151. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3152. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3153. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3154. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3155. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3156. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3157. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3158. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3159. }
  3160. } break;
  3161. case LLM_ARCH_PERSIMMON:
  3162. {
  3163. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3164. {
  3165. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3166. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3167. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3168. }
  3169. for (int i = 0; i < n_layer; ++i) {
  3170. ggml_context * ctx_layer = ctx_for_layer(i);
  3171. ggml_context * ctx_split = ctx_for_layer_split(i);
  3172. auto & layer = model.layers[i];
  3173. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3174. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3175. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3176. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3177. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3178. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3179. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3180. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3181. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3182. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3183. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3184. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3185. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {64});
  3186. layer.attn_q_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "bias", i), {64});
  3187. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {64});
  3188. layer.attn_k_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "bias", i), {64});
  3189. }
  3190. } break;
  3191. case LLM_ARCH_BLOOM:
  3192. {
  3193. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3194. model.tok_norm = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  3195. model.tok_norm_b = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  3196. // output
  3197. {
  3198. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3199. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3200. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3201. }
  3202. for (int i = 0; i < n_layer; ++i) {
  3203. ggml_context * ctx_layer = ctx_for_layer(i);
  3204. ggml_context * ctx_split = ctx_for_layer_split(i);
  3205. auto & layer = model.layers[i];
  3206. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3207. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3208. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3209. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3210. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3211. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3212. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3213. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3214. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3215. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3216. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3217. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3218. }
  3219. } break;
  3220. case LLM_ARCH_MPT:
  3221. {
  3222. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3223. // output
  3224. {
  3225. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3226. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3227. }
  3228. for (int i = 0; i < n_layer; ++i) {
  3229. ggml_context * ctx_layer = ctx_for_layer(i);
  3230. ggml_context * ctx_split = ctx_for_layer_split(i);
  3231. auto & layer = model.layers[i];
  3232. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3233. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3234. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3235. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3236. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3237. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3238. // AWQ ScaleActivation layer
  3239. layer.ffn_act = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_ACT, "scales", i), {n_ff}, false);
  3240. }
  3241. } break;
  3242. case LLM_ARCH_STABLELM:
  3243. {
  3244. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3245. // output
  3246. {
  3247. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3248. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3249. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3250. }
  3251. for (int i = 0; i < n_layer; ++i) {
  3252. ggml_context * ctx_layer = ctx_for_layer(i);
  3253. ggml_context * ctx_split = ctx_for_layer_split(i);
  3254. auto & layer = model.layers[i];
  3255. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3256. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3257. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3258. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3259. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3260. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3261. // optional bias tensors, present in Stable LM 2 1.6B
  3262. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, false);
  3263. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, false);
  3264. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, false);
  3265. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3266. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3267. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3268. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3269. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3270. }
  3271. } break;
  3272. case LLM_ARCH_QWEN:
  3273. {
  3274. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3275. // output
  3276. {
  3277. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3278. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3279. }
  3280. for (int i = 0; i < n_layer; ++i) {
  3281. ggml_context * ctx_layer = ctx_for_layer(i);
  3282. ggml_context * ctx_split = ctx_for_layer_split(i);
  3283. auto & layer = model.layers[i];
  3284. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3285. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd*3});
  3286. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd*3});
  3287. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3288. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3289. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff/2});
  3290. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff/2, n_embd});
  3291. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff/2});
  3292. }
  3293. } break;
  3294. case LLM_ARCH_QWEN2:
  3295. {
  3296. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3297. // output
  3298. {
  3299. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3300. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3301. }
  3302. for (int i = 0; i < n_layer; ++i) {
  3303. ggml_context * ctx_layer = ctx_for_layer(i);
  3304. ggml_context * ctx_split = ctx_for_layer_split(i);
  3305. auto & layer = model.layers[i];
  3306. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3307. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3308. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3309. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3310. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3311. // optional bias tensors
  3312. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  3313. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  3314. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  3315. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3316. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3317. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3318. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3319. }
  3320. } break;
  3321. case LLM_ARCH_PHI2:
  3322. {
  3323. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3324. // output
  3325. {
  3326. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3327. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3328. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3329. model.output_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT, "bias"), {n_vocab});
  3330. }
  3331. for (int i = 0; i < n_layer; ++i) {
  3332. ggml_context * ctx_layer = ctx_for_layer(i);
  3333. ggml_context * ctx_split = ctx_for_layer_split(i);
  3334. auto & layer = model.layers[i];
  3335. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3336. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3337. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, false);
  3338. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, false);
  3339. if (layer.wqkv == nullptr) {
  3340. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3341. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  3342. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3343. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  3344. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3345. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  3346. }
  3347. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3348. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3349. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3350. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3351. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3352. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3353. }
  3354. } break;
  3355. case LLM_ARCH_PLAMO:
  3356. {
  3357. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3358. // output
  3359. {
  3360. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3361. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3362. }
  3363. for (int i = 0; i < n_layer; ++i) {
  3364. ggml_context * ctx_layer = ctx_for_layer(i);
  3365. ggml_context * ctx_split = ctx_for_layer_split(i);
  3366. auto & layer = model.layers[i];
  3367. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3368. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3369. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3370. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3371. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3372. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3373. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3374. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3375. }
  3376. } break;
  3377. case LLM_ARCH_GPT2:
  3378. {
  3379. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3380. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3381. // output
  3382. {
  3383. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3384. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3385. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3386. }
  3387. for (int i = 0; i < n_layer; ++i) {
  3388. ggml_context * ctx_layer = ctx_for_layer(i);
  3389. ggml_context * ctx_split = ctx_for_layer_split(i);
  3390. auto & layer = model.layers[i];
  3391. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3392. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3393. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3394. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3395. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3396. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3397. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3398. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3399. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3400. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3401. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3402. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3403. }
  3404. } break;
  3405. case LLM_ARCH_CODESHELL:
  3406. {
  3407. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3408. // output
  3409. {
  3410. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3411. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3412. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3413. }
  3414. for (int i = 0; i < n_layer; ++i) {
  3415. ggml_context * ctx_layer = ctx_for_layer(i);
  3416. ggml_context * ctx_split = ctx_for_layer_split(i);
  3417. auto & layer = model.layers[i];
  3418. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3419. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3420. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3421. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3422. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3423. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3424. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3425. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3426. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3427. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3428. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3429. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3430. }
  3431. } break;
  3432. case LLM_ARCH_ORION:
  3433. {
  3434. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3435. {
  3436. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3437. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3438. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3439. }
  3440. for (int i = 0; i < n_layer; ++i) {
  3441. ggml_context * ctx_layer = ctx_for_layer(i);
  3442. ggml_context * ctx_split = ctx_for_layer_split(i);
  3443. auto & layer = model.layers[i];
  3444. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3445. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3446. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3447. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3448. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3449. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3450. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3451. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3452. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3453. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3454. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3455. }
  3456. } break;
  3457. case LLM_ARCH_INTERNLM2:
  3458. {
  3459. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3460. // output
  3461. {
  3462. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3463. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3464. }
  3465. for (int i = 0; i < n_layer; ++i) {
  3466. ggml_context * ctx_layer = ctx_for_layer(i);
  3467. ggml_context * ctx_split = ctx_for_layer_split(i);
  3468. auto & layer = model.layers[i];
  3469. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3470. // layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3471. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3472. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3473. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3474. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3475. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3476. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3477. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3478. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3479. }
  3480. } break;
  3481. default:
  3482. throw std::runtime_error("unknown architecture");
  3483. }
  3484. }
  3485. ml.done_getting_tensors();
  3486. ml.init_mapping(true, use_mlock ? &model.mlock_mmap : nullptr);
  3487. // create the backend buffers
  3488. std::vector<std::pair<ggml_context *, ggml_backend_buffer_t>> ctx_bufs;
  3489. for (auto & it : ctx_map) {
  3490. ggml_backend_buffer_type_t buft = it.first;
  3491. ggml_context * ctx = it.second;
  3492. ggml_backend_buffer_t buf = nullptr;
  3493. // only the mmap region containing the tensors in the model is mapped to the backend buffer
  3494. // 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
  3495. // this allows using partial offloading when the model size exceeds the metal buffer size, but not the RAM size
  3496. if (ml.use_mmap && buft == llama_default_buffer_type_cpu(true)) {
  3497. size_t first, last;
  3498. ml.get_mapping_range(&first, &last, ctx);
  3499. buf = ggml_backend_cpu_buffer_from_ptr((char *) ml.mapping->addr + first, last - first);
  3500. }
  3501. #ifdef GGML_USE_METAL
  3502. else if (ml.use_mmap && buft == ggml_backend_metal_buffer_type()) {
  3503. const size_t max_size = ggml_get_max_tensor_size(ctx);
  3504. size_t first, last;
  3505. ml.get_mapping_range(&first, &last, ctx);
  3506. buf = ggml_backend_metal_buffer_from_ptr((char *) ml.mapping->addr + first, last - first, max_size);
  3507. }
  3508. #endif
  3509. else {
  3510. buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  3511. if (buf != nullptr && use_mlock && ggml_backend_buffer_is_host(buf)) {
  3512. model.mlock_bufs.emplace_back(new llama_mlock);
  3513. auto & mlock_buf = model.mlock_bufs.back();
  3514. mlock_buf->init (ggml_backend_buffer_get_base(buf));
  3515. mlock_buf->grow_to(ggml_backend_buffer_get_size(buf));
  3516. }
  3517. }
  3518. if (buf == nullptr) {
  3519. throw std::runtime_error("failed to allocate buffer");
  3520. }
  3521. // indicate that this buffer contains weights
  3522. // 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
  3523. ggml_backend_buffer_set_usage(buf, GGML_BACKEND_BUFFER_USAGE_WEIGHTS);
  3524. model.bufs.push_back(buf);
  3525. ctx_bufs.emplace_back(ctx, buf);
  3526. }
  3527. // print memory requirements
  3528. {
  3529. const int n_gpu = std::min(n_gpu_layers, int(hparams.n_layer));
  3530. LLAMA_LOG_INFO("%s: offloading %d repeating layers to GPU\n", __func__, n_gpu);
  3531. if (n_gpu_layers > (int) hparams.n_layer) {
  3532. LLAMA_LOG_INFO("%s: offloading non-repeating layers to GPU\n", __func__);
  3533. }
  3534. const int max_backend_supported_layers = hparams.n_layer + 1;
  3535. const int max_offloadable_layers = hparams.n_layer + 1;
  3536. LLAMA_LOG_INFO("%s: offloaded %d/%d layers to GPU\n", __func__, std::min(n_gpu_layers, max_offloadable_layers), max_backend_supported_layers);
  3537. for (ggml_backend_buffer_t buf : model.bufs) {
  3538. 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);
  3539. }
  3540. }
  3541. // populate tensors_by_name
  3542. for (ggml_context * ctx : model.ctxs) {
  3543. for (auto * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  3544. model.tensors_by_name.emplace_back(ggml_get_name(cur), cur);
  3545. }
  3546. }
  3547. // load tensor data
  3548. for (auto & it : ctx_bufs) {
  3549. ggml_context * ctx = it.first;
  3550. ggml_backend_buffer_t buf = it.second;
  3551. if (!ml.load_all_data(ctx, progress_callback, progress_callback_user_data, buf, use_mlock ? &model.mlock_mmap : NULL)) {
  3552. return false;
  3553. }
  3554. }
  3555. model.mapping = std::move(ml.mapping);
  3556. // loading time will be recalculate after the first eval, so
  3557. // we take page faults deferred by mmap() into consideration
  3558. model.t_load_us = ggml_time_us() - model.t_start_us;
  3559. return true;
  3560. }
  3561. // Returns 0 on success, -1 on error, and -2 on cancellation via llama_progress_callback
  3562. static int llama_model_load(const std::string & fname, llama_model & model, llama_model_params & params) {
  3563. try {
  3564. llama_model_loader ml(fname, params.use_mmap, params.kv_overrides);
  3565. model.hparams.vocab_only = params.vocab_only;
  3566. llm_load_arch (ml, model);
  3567. llm_load_hparams(ml, model);
  3568. llm_load_vocab (ml, model);
  3569. llm_load_print_meta(ml, model);
  3570. if (model.hparams.n_vocab != model.vocab.id_to_token.size()) {
  3571. throw std::runtime_error("vocab size mismatch");
  3572. }
  3573. if (params.vocab_only) {
  3574. LLAMA_LOG_INFO("%s: vocab only - skipping tensors\n", __func__);
  3575. return 0;
  3576. }
  3577. #ifdef GGML_USE_KOMPUTE
  3578. if (params.n_gpu_layers > 0 && (
  3579. !(model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON)
  3580. || !(
  3581. model.ftype == LLAMA_FTYPE_ALL_F32 ||
  3582. model.ftype == LLAMA_FTYPE_MOSTLY_F16 ||
  3583. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ||
  3584. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_1
  3585. )
  3586. )) {
  3587. // TODO(cebtenzzre): propagate this error outside of llama_load_model_from_file
  3588. LLAMA_LOG_WARN("%s: disabling Kompute due to unsupported model arch or quantization\n", __func__);
  3589. params.n_gpu_layers = 0;
  3590. }
  3591. #endif
  3592. if (!llm_load_tensors(
  3593. ml, model, params.n_gpu_layers, params.split_mode, params.main_gpu, params.tensor_split, params.use_mlock,
  3594. params.progress_callback, params.progress_callback_user_data
  3595. )) {
  3596. return -2;
  3597. }
  3598. } catch (const std::exception & err) {
  3599. LLAMA_LOG_ERROR("%s: error loading model: %s\n", __func__, err.what());
  3600. return -1;
  3601. }
  3602. return 0;
  3603. }
  3604. //
  3605. // llm_build
  3606. //
  3607. using llm_build_cb = std::function<void(struct ggml_tensor * cur, const char * name, int nl)>;
  3608. enum llm_rope_type {
  3609. LLM_ROPE,
  3610. LLM_ROPE_NEOX,
  3611. LLM_ROPE_GLM,
  3612. };
  3613. enum llm_ffn_op_type {
  3614. LLM_FFN_SILU,
  3615. LLM_FFN_GELU,
  3616. LLM_FFN_RELU,
  3617. LLM_FFN_RELU_SQR,
  3618. };
  3619. enum llm_ffn_gate_type {
  3620. LLM_FFN_SEQ,
  3621. LLM_FFN_PAR, // ffn_gate is parallel to ffn_up
  3622. };
  3623. enum llm_norm_type {
  3624. LLM_NORM,
  3625. LLM_NORM_RMS,
  3626. };
  3627. static struct ggml_tensor * llm_build_inp_embd(
  3628. struct ggml_context * ctx,
  3629. const llama_hparams & hparams,
  3630. const llama_batch & batch,
  3631. struct ggml_tensor * tok_embd,
  3632. struct ggml_tensor * inp_tokens,
  3633. struct ggml_tensor * inp_embd,
  3634. const llm_build_cb & cb) {
  3635. const int64_t n_embd = hparams.n_embd;
  3636. struct ggml_tensor * inpL;
  3637. if (batch.token) {
  3638. struct ggml_tensor * inp_tokens_v = ggml_view_1d(ctx, inp_tokens, batch.n_tokens, 0);
  3639. cb(inp_tokens, "inp_tokens", -1);
  3640. inpL = ggml_get_rows(ctx, tok_embd, inp_tokens_v);
  3641. } else {
  3642. #ifdef GGML_USE_MPI
  3643. GGML_ASSERT(false && "not implemented");
  3644. #endif
  3645. inpL = ggml_view_2d(ctx, inp_embd, n_embd, batch.n_tokens, inp_embd->nb[1], 0);
  3646. }
  3647. return inpL;
  3648. }
  3649. // Persimmon: n_rot = n_embd_head_k/2
  3650. // Other: n_rot = n_embd_head_k
  3651. static void llm_build_k_shift(
  3652. struct ggml_context * ctx,
  3653. const llama_hparams & hparams,
  3654. const llama_cparams & cparams,
  3655. const llama_kv_cache & kv,
  3656. struct ggml_cgraph * graph,
  3657. struct ggml_tensor * K_shift,
  3658. llm_rope_type type,
  3659. int64_t n_ctx,
  3660. float freq_base,
  3661. float freq_scale,
  3662. const llm_build_cb & cb) {
  3663. const int64_t n_layer = hparams.n_layer;
  3664. const int64_t n_head_kv = hparams.n_head_kv;
  3665. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  3666. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3667. const int32_t n_rot = hparams.n_rot;
  3668. const int32_t n_orig_ctx = cparams.n_yarn_orig_ctx;
  3669. const float ext_factor = cparams.yarn_ext_factor;
  3670. const float attn_factor = cparams.yarn_attn_factor;
  3671. const float beta_fast = cparams.yarn_beta_fast;
  3672. const float beta_slow = cparams.yarn_beta_slow;
  3673. int rope_type = 0;
  3674. switch (type) {
  3675. case LLM_ROPE: rope_type = 0; break;
  3676. case LLM_ROPE_NEOX: rope_type = 2; break;
  3677. case LLM_ROPE_GLM: rope_type = 4; break;
  3678. }
  3679. for (int il = 0; il < n_layer; ++il) {
  3680. struct ggml_tensor * tmp =
  3681. // we rotate only the first n_rot dimensions
  3682. ggml_rope_custom_inplace(ctx,
  3683. ggml_view_3d(ctx, kv.k_l[il],
  3684. n_embd_head_k, n_head_kv, n_ctx,
  3685. ggml_row_size(kv.k_l[il]->type, n_embd_head_k),
  3686. ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa),
  3687. 0),
  3688. K_shift, n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  3689. ext_factor, attn_factor, beta_fast, beta_slow);
  3690. cb(tmp, "K_shifted", il);
  3691. ggml_build_forward_expand(graph, tmp);
  3692. }
  3693. }
  3694. static void llm_build_kv_store(
  3695. struct ggml_context * ctx,
  3696. const llama_hparams & hparams,
  3697. const llama_kv_cache & kv,
  3698. struct ggml_cgraph * graph,
  3699. struct ggml_tensor * k_cur,
  3700. struct ggml_tensor * v_cur,
  3701. int64_t n_ctx,
  3702. int32_t n_tokens,
  3703. int32_t kv_head,
  3704. const llm_build_cb & cb,
  3705. int64_t il) {
  3706. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3707. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  3708. // compute the transposed [n_tokens, n_embd] V matrix
  3709. struct ggml_tensor * v_cur_t = ggml_transpose(ctx, ggml_reshape_2d(ctx, v_cur, n_embd_v_gqa, n_tokens));
  3710. //struct ggml_tensor * v_cur_t = ggml_transpose(ctx, v_cur); // TODO: reshape above is likely not needed
  3711. cb(v_cur_t, "v_cur_t", il);
  3712. struct ggml_tensor * k_cache_view = ggml_view_1d(ctx, kv.k_l[il], n_tokens*n_embd_k_gqa,
  3713. (ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa))*kv_head);
  3714. cb(k_cache_view, "k_cache_view", il);
  3715. struct ggml_tensor * v_cache_view = ggml_view_2d(ctx, kv.v_l[il], n_tokens, n_embd_v_gqa,
  3716. ( n_ctx)*ggml_element_size(kv.v_l[il]),
  3717. (kv_head)*ggml_element_size(kv.v_l[il]));
  3718. cb(v_cache_view, "v_cache_view", il);
  3719. // important: storing RoPE-ed version of K in the KV cache!
  3720. ggml_build_forward_expand(graph, ggml_cpy(ctx, k_cur, k_cache_view));
  3721. ggml_build_forward_expand(graph, ggml_cpy(ctx, v_cur_t, v_cache_view));
  3722. }
  3723. static struct ggml_tensor * llm_build_norm(
  3724. struct ggml_context * ctx,
  3725. struct ggml_tensor * cur,
  3726. const llama_hparams & hparams,
  3727. struct ggml_tensor * mw,
  3728. struct ggml_tensor * mb,
  3729. llm_norm_type type,
  3730. const llm_build_cb & cb,
  3731. int il) {
  3732. switch (type) {
  3733. case LLM_NORM: cur = ggml_norm (ctx, cur, hparams.f_norm_eps); break;
  3734. case LLM_NORM_RMS: cur = ggml_rms_norm(ctx, cur, hparams.f_norm_rms_eps); break;
  3735. }
  3736. if (mw || mb) {
  3737. cb(cur, "norm", il);
  3738. }
  3739. if (mw) {
  3740. cur = ggml_mul(ctx, cur, mw);
  3741. if (mb) {
  3742. cb(cur, "norm_w", il);
  3743. }
  3744. }
  3745. if (mb) {
  3746. cur = ggml_add(ctx, cur, mb);
  3747. }
  3748. return cur;
  3749. }
  3750. static struct ggml_tensor * llm_build_ffn(
  3751. struct ggml_context * ctx,
  3752. struct ggml_tensor * cur,
  3753. struct ggml_tensor * up,
  3754. struct ggml_tensor * up_b,
  3755. struct ggml_tensor * gate,
  3756. struct ggml_tensor * gate_b,
  3757. struct ggml_tensor * down,
  3758. struct ggml_tensor * down_b,
  3759. struct ggml_tensor * act_scales,
  3760. llm_ffn_op_type type_op,
  3761. llm_ffn_gate_type type_gate,
  3762. const llm_build_cb & cb,
  3763. int il) {
  3764. struct ggml_tensor * tmp = ggml_mul_mat(ctx, up, cur);
  3765. cb(tmp, "ffn_up", il);
  3766. if (up_b) {
  3767. tmp = ggml_add(ctx, tmp, up_b);
  3768. cb(tmp, "ffn_up_b", il);
  3769. }
  3770. if (gate) {
  3771. switch (type_gate) {
  3772. case LLM_FFN_SEQ:
  3773. {
  3774. cur = ggml_mul_mat(ctx, gate, tmp);
  3775. cb(cur, "ffn_gate", il);
  3776. } break;
  3777. case LLM_FFN_PAR:
  3778. {
  3779. cur = ggml_mul_mat(ctx, gate, cur);
  3780. cb(cur, "ffn_gate", il);
  3781. } break;
  3782. }
  3783. if (gate_b) {
  3784. cur = ggml_add(ctx, cur, gate_b);
  3785. cb(cur, "ffn_gate_b", il);
  3786. }
  3787. } else {
  3788. cur = tmp;
  3789. }
  3790. switch (type_op) {
  3791. case LLM_FFN_SILU:
  3792. {
  3793. cur = ggml_silu(ctx, cur);
  3794. cb(cur, "ffn_silu", il);
  3795. } break;
  3796. case LLM_FFN_GELU:
  3797. {
  3798. cur = ggml_gelu(ctx, cur);
  3799. cb(cur, "ffn_gelu", il);
  3800. if (act_scales != NULL) {
  3801. cur = ggml_div(ctx, cur, act_scales);
  3802. cb(cur, "ffn_act", il);
  3803. }
  3804. } break;
  3805. case LLM_FFN_RELU:
  3806. {
  3807. cur = ggml_relu(ctx, cur);
  3808. cb(cur, "ffn_relu", il);
  3809. } break;
  3810. case LLM_FFN_RELU_SQR:
  3811. {
  3812. cur = ggml_relu(ctx, cur);
  3813. cb(cur, "ffn_relu", il);
  3814. cur = ggml_sqr(ctx, cur);
  3815. cb(cur, "ffn_sqr(relu)", il);
  3816. } break;
  3817. }
  3818. if (type_gate == LLM_FFN_PAR) {
  3819. cur = ggml_mul(ctx, cur, tmp);
  3820. cb(cur, "ffn_gate_par", il);
  3821. }
  3822. cur = ggml_mul_mat(ctx, down, cur);
  3823. if (down_b) {
  3824. cb(cur, "ffn_down", il);
  3825. }
  3826. if (down_b) {
  3827. cur = ggml_add(ctx, cur, down_b);
  3828. }
  3829. return cur;
  3830. }
  3831. // if max_alibi_bias > 0 then apply ALiBi
  3832. static struct ggml_tensor * llm_build_kqv(
  3833. struct ggml_context * ctx,
  3834. const llama_model & model,
  3835. const llama_hparams & hparams,
  3836. const llama_kv_cache & kv,
  3837. struct ggml_cgraph * graph,
  3838. struct ggml_tensor * wo,
  3839. struct ggml_tensor * wo_b,
  3840. struct ggml_tensor * q_cur,
  3841. struct ggml_tensor * kq_mask,
  3842. int64_t n_ctx,
  3843. int32_t n_tokens,
  3844. int32_t n_kv,
  3845. float max_alibi_bias,
  3846. float kq_scale,
  3847. const llm_build_cb & cb,
  3848. int il) {
  3849. const int64_t n_head = hparams.n_head;
  3850. const int64_t n_head_kv = hparams.n_head_kv;
  3851. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  3852. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3853. const int64_t n_embd_head_v = hparams.n_embd_head_v;
  3854. struct ggml_tensor * q = ggml_permute(ctx, q_cur, 0, 2, 1, 3);
  3855. cb(q, "q", il);
  3856. struct ggml_tensor * k =
  3857. ggml_view_3d(ctx, kv.k_l[il],
  3858. n_embd_head_k, n_kv, n_head_kv,
  3859. ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa),
  3860. ggml_row_size(kv.k_l[il]->type, n_embd_head_k),
  3861. 0);
  3862. cb(k, "k", il);
  3863. struct ggml_tensor * kq = ggml_mul_mat(ctx, k, q);
  3864. cb(kq, "kq", il);
  3865. if (model.arch == LLM_ARCH_PHI2) {
  3866. // for this arch, we need to perform the KQ multiplication with F32 precision, otherwise we get NaNs
  3867. // ref: https://github.com/ggerganov/llama.cpp/pull/4490#issuecomment-1859055847
  3868. ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  3869. }
  3870. if (max_alibi_bias > 0.0f) {
  3871. // temporary branch until we figure out how to handle ggml_alibi through ggml_add
  3872. kq = ggml_scale(ctx, kq, kq_scale);
  3873. cb(kq, "kq_scaled", il);
  3874. if (max_alibi_bias > 0.0f) {
  3875. // TODO: n_head or n_head_kv
  3876. // TODO: K-shift is likely not working
  3877. // TODO: change to ggml_add
  3878. kq = ggml_alibi(ctx, kq, /*n_past*/ 0, n_head, max_alibi_bias);
  3879. cb(kq, "kq_scaled_alibi", il);
  3880. }
  3881. kq = ggml_add(ctx, kq, kq_mask);
  3882. cb(kq, "kq_masked", il);
  3883. kq = ggml_soft_max(ctx, kq);
  3884. cb(kq, "kq_soft_max", il);
  3885. } else {
  3886. kq = ggml_soft_max_ext(ctx, kq, kq_mask, kq_scale);
  3887. cb(kq, "kq_soft_max_ext", il);
  3888. }
  3889. // split cached v into n_head heads
  3890. struct ggml_tensor * v =
  3891. ggml_view_3d(ctx, kv.v_l[il],
  3892. n_kv, n_embd_head_v, n_head_kv,
  3893. ggml_element_size(kv.v_l[il])*n_ctx,
  3894. ggml_element_size(kv.v_l[il])*n_ctx*n_embd_head_v,
  3895. 0);
  3896. cb(v, "v", il);
  3897. struct ggml_tensor * kqv = ggml_mul_mat(ctx, v, kq);
  3898. cb(kqv, "kqv", il);
  3899. struct ggml_tensor * kqv_merged = ggml_permute(ctx, kqv, 0, 2, 1, 3);
  3900. cb(kqv_merged, "kqv_merged", il);
  3901. struct ggml_tensor * cur = ggml_cont_2d(ctx, kqv_merged, n_embd_head_k*n_head, n_tokens);
  3902. cb(cur, "kqv_merged_cont", il);
  3903. ggml_build_forward_expand(graph, cur);
  3904. cur = ggml_mul_mat(ctx, wo, cur);
  3905. if (wo_b) {
  3906. cb(cur, "kqv_wo", il);
  3907. }
  3908. if (wo_b) {
  3909. cur = ggml_add(ctx, cur, wo_b);
  3910. }
  3911. return cur;
  3912. }
  3913. static struct ggml_tensor * llm_build_kv(
  3914. struct ggml_context * ctx,
  3915. const llama_model & model,
  3916. const llama_hparams & hparams,
  3917. const llama_kv_cache & kv,
  3918. struct ggml_cgraph * graph,
  3919. struct ggml_tensor * wo,
  3920. struct ggml_tensor * wo_b,
  3921. struct ggml_tensor * k_cur,
  3922. struct ggml_tensor * v_cur,
  3923. struct ggml_tensor * q_cur,
  3924. struct ggml_tensor * kq_mask,
  3925. int64_t n_ctx,
  3926. int32_t n_tokens,
  3927. int32_t kv_head,
  3928. int32_t n_kv,
  3929. float max_alibi_bias,
  3930. float kq_scale,
  3931. const llm_build_cb & cb,
  3932. int il) {
  3933. // these nodes are added to the graph together so that they are not reordered
  3934. // by doing so, the number of splits in the graph is reduced
  3935. ggml_build_forward_expand(graph, q_cur);
  3936. ggml_build_forward_expand(graph, k_cur);
  3937. ggml_build_forward_expand(graph, v_cur);
  3938. llm_build_kv_store(ctx, hparams, kv, graph, k_cur, v_cur, n_ctx, n_tokens, kv_head, cb, il);
  3939. struct ggml_tensor * cur;
  3940. cur = llm_build_kqv(ctx, model, hparams, kv, graph,
  3941. wo, wo_b,
  3942. q_cur, kq_mask, n_ctx, n_tokens, n_kv, max_alibi_bias, kq_scale, cb, il);
  3943. cb(cur, "kqv_out", il);
  3944. return cur;
  3945. }
  3946. struct llm_build_context {
  3947. const llama_model & model;
  3948. const llama_context & lctx;
  3949. const llama_hparams & hparams;
  3950. const llama_cparams & cparams;
  3951. const llama_batch & batch;
  3952. const llama_kv_cache & kv_self;
  3953. const int64_t n_embd;
  3954. const int64_t n_layer;
  3955. const int64_t n_ctx; // user-specified context size (can be different from n_ctx_train)
  3956. const int64_t n_head;
  3957. const int64_t n_head_kv;
  3958. const int64_t n_embd_head_k;
  3959. const int64_t n_embd_k_gqa;
  3960. const int64_t n_embd_head_v;
  3961. const int64_t n_embd_v_gqa;
  3962. const int64_t n_expert;
  3963. const int64_t n_expert_used;
  3964. const float freq_base;
  3965. const float freq_scale;
  3966. const float ext_factor;
  3967. const float attn_factor;
  3968. const float beta_fast;
  3969. const float beta_slow;
  3970. const float norm_eps;
  3971. const float norm_rms_eps;
  3972. const int32_t n_tokens;
  3973. const int32_t n_kv; // size of KV cache to consider (n_kv <= n_ctx)
  3974. const int32_t kv_head; // index of where we store new KV data in the cache
  3975. const int32_t n_orig_ctx;
  3976. const bool do_rope_shift;
  3977. const llm_build_cb & cb;
  3978. std::vector<uint8_t> & buf_compute_meta;
  3979. struct ggml_context * ctx0 = nullptr;
  3980. // TODO: consider making the entire interface noexcept
  3981. llm_build_context(
  3982. llama_context & lctx,
  3983. const llama_batch & batch,
  3984. const llm_build_cb & cb,
  3985. bool worst_case) :
  3986. model (lctx.model),
  3987. lctx (lctx),
  3988. hparams (model.hparams),
  3989. cparams (lctx.cparams),
  3990. batch (batch),
  3991. kv_self (lctx.kv_self),
  3992. n_embd (hparams.n_embd),
  3993. n_layer (hparams.n_layer),
  3994. n_ctx (cparams.n_ctx),
  3995. n_head (hparams.n_head),
  3996. n_head_kv (hparams.n_head_kv),
  3997. n_embd_head_k (hparams.n_embd_head_k),
  3998. n_embd_k_gqa (hparams.n_embd_k_gqa()),
  3999. n_embd_head_v (hparams.n_embd_head_v),
  4000. n_embd_v_gqa (hparams.n_embd_v_gqa()),
  4001. n_expert (hparams.n_expert),
  4002. n_expert_used (hparams.n_expert_used),
  4003. freq_base (cparams.rope_freq_base),
  4004. freq_scale (cparams.rope_freq_scale),
  4005. ext_factor (cparams.yarn_ext_factor),
  4006. attn_factor (cparams.yarn_attn_factor),
  4007. beta_fast (cparams.yarn_beta_fast),
  4008. beta_slow (cparams.yarn_beta_slow),
  4009. norm_eps (hparams.f_norm_eps),
  4010. norm_rms_eps (hparams.f_norm_rms_eps),
  4011. n_tokens (batch.n_tokens),
  4012. n_kv (worst_case ? n_ctx : kv_self.n),
  4013. kv_head (worst_case ? n_ctx - n_tokens : kv_self.head),
  4014. n_orig_ctx (cparams.n_yarn_orig_ctx),
  4015. do_rope_shift (worst_case || kv_self.has_shift),
  4016. cb (cb),
  4017. buf_compute_meta (lctx.buf_compute_meta) {
  4018. // all initializations should be done in init()
  4019. }
  4020. void init() {
  4021. struct ggml_init_params params = {
  4022. /*.mem_size =*/ buf_compute_meta.size(),
  4023. /*.mem_buffer =*/ buf_compute_meta.data(),
  4024. /*.no_alloc =*/ true,
  4025. };
  4026. ctx0 = ggml_init(params);
  4027. }
  4028. void free() {
  4029. if (ctx0) {
  4030. ggml_free(ctx0);
  4031. ctx0 = nullptr;
  4032. }
  4033. }
  4034. struct ggml_cgraph * build_llama() {
  4035. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4036. const int64_t n_embd_head = hparams.n_embd_head_v;
  4037. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4038. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4039. struct ggml_tensor * cur;
  4040. struct ggml_tensor * inpL;
  4041. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4042. cb(inpL, "inp_embd", -1);
  4043. // inp_pos - contains the positions
  4044. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4045. cb(inp_pos, "inp_pos", -1);
  4046. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4047. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  4048. cb(KQ_mask, "KQ_mask", -1);
  4049. // shift the entire K-cache if needed
  4050. if (do_rope_shift) {
  4051. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  4052. }
  4053. for (int il = 0; il < n_layer; ++il) {
  4054. struct ggml_tensor * inpSA = inpL;
  4055. // norm
  4056. cur = llm_build_norm(ctx0, inpL, hparams,
  4057. model.layers[il].attn_norm, NULL,
  4058. LLM_NORM_RMS, cb, il);
  4059. cb(cur, "attn_norm", il);
  4060. // self-attention
  4061. {
  4062. // compute Q and K and RoPE them
  4063. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4064. cb(Qcur, "Qcur", il);
  4065. if (model.layers[il].bq) {
  4066. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  4067. cb(Qcur, "Qcur", il);
  4068. }
  4069. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4070. cb(Kcur, "Kcur", il);
  4071. if (model.layers[il].bk) {
  4072. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  4073. cb(Kcur, "Kcur", il);
  4074. }
  4075. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4076. cb(Vcur, "Vcur", il);
  4077. if (model.layers[il].bv) {
  4078. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  4079. cb(Vcur, "Vcur", il);
  4080. }
  4081. Qcur = ggml_rope_custom(
  4082. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  4083. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  4084. ext_factor, attn_factor, beta_fast, beta_slow
  4085. );
  4086. cb(Qcur, "Qcur", il);
  4087. Kcur = ggml_rope_custom(
  4088. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  4089. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  4090. ext_factor, attn_factor, beta_fast, beta_slow
  4091. );
  4092. cb(Kcur, "Kcur", il);
  4093. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4094. model.layers[il].wo, model.layers[il].bo,
  4095. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4096. cb(cur, "kqv_out", il);
  4097. }
  4098. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4099. cb(ffn_inp, "ffn_inp", il);
  4100. // feed-forward network
  4101. if (model.layers[il].ffn_gate_inp == nullptr) {
  4102. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4103. model.layers[il].ffn_norm, NULL,
  4104. LLM_NORM_RMS, cb, il);
  4105. cb(cur, "ffn_norm", il);
  4106. cur = llm_build_ffn(ctx0, cur,
  4107. model.layers[il].ffn_up, NULL,
  4108. model.layers[il].ffn_gate, NULL,
  4109. model.layers[il].ffn_down, NULL,
  4110. NULL,
  4111. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4112. cb(cur, "ffn_out", il);
  4113. } else {
  4114. // MoE branch
  4115. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4116. model.layers[il].ffn_norm, NULL,
  4117. LLM_NORM_RMS, cb, il);
  4118. cb(cur, "ffn_norm", il);
  4119. ggml_tensor * logits = ggml_mul_mat(ctx0, model.layers[il].ffn_gate_inp, cur); // [n_tokens, num_experts]
  4120. cb(logits, "ffn_moe_logits", il);
  4121. ggml_tensor * probs = ggml_soft_max(ctx0, logits); // [n_tokens, num_experts]
  4122. cb(probs, "ffn_moe_probs", il);
  4123. // select experts
  4124. ggml_tensor * selected_experts = ggml_top_k(ctx0, probs, n_expert_used); // [n_tokens, num_experts_per_tok]
  4125. cb(selected_experts->src[0], "ffn_moe_argsort", il);
  4126. ggml_tensor * weights = ggml_get_rows(ctx0,
  4127. ggml_reshape_3d(ctx0, probs, 1, n_expert, n_tokens), selected_experts);
  4128. cb(weights, "ffn_moe_weights", il);
  4129. weights = ggml_reshape_2d(ctx0, weights, n_expert_used, n_tokens); // [n_tokens, num_experts_per_tok]
  4130. ggml_tensor * weights_sum = ggml_sum_rows(ctx0, weights);
  4131. cb(weights_sum, "ffn_moe_weights_sum", il);
  4132. weights = ggml_div(ctx0, weights, weights_sum); // [n_tokens, num_experts_per_tok]
  4133. cb(weights, "ffn_moe_weights_norm", il);
  4134. // compute expert outputs
  4135. ggml_tensor * moe_out = nullptr;
  4136. for (int i = 0; i < n_expert_used; ++i) {
  4137. ggml_tensor * cur_expert;
  4138. ggml_tensor * cur_up = ggml_mul_mat_id(ctx0, model.layers[il].ffn_up_exp, n_expert, selected_experts, i, cur);
  4139. cb(cur_up, "ffn_moe_up", il);
  4140. ggml_tensor * cur_gate = ggml_mul_mat_id(ctx0, model.layers[il].ffn_gate_exp, n_expert, selected_experts, i, cur);
  4141. cb(cur_gate, "ffn_moe_gate", il);
  4142. cur_gate = ggml_silu(ctx0, cur_gate);
  4143. cb(cur_gate, "ffn_moe_silu", il);
  4144. cur_expert = ggml_mul(ctx0, cur_up, cur_gate); // [n_tokens, n_embd]
  4145. cb(cur_expert, "ffn_moe_gate_par", il);
  4146. cur_expert = ggml_mul_mat_id(ctx0, model.layers[il].ffn_down_exp, n_expert, selected_experts, i, cur_expert); // [n_tokens, n_embd]
  4147. cb(cur_expert, "ffn_moe_down", il);
  4148. cur_expert = ggml_mul(ctx0, cur_expert,
  4149. ggml_view_2d(ctx0, weights, 1, n_tokens, weights->nb[1], i*weights->nb[0]));
  4150. cb(cur_expert, "ffn_moe_weighted", il);
  4151. if (i == 0) {
  4152. moe_out = cur_expert;
  4153. } else {
  4154. moe_out = ggml_add(ctx0, moe_out, cur_expert);
  4155. cb(moe_out, "ffn_moe_out", il);
  4156. }
  4157. }
  4158. cur = moe_out;
  4159. }
  4160. cur = ggml_add(ctx0, cur, ffn_inp);
  4161. cb(cur, "l_out", il);
  4162. // input for next layer
  4163. inpL = cur;
  4164. }
  4165. cur = inpL;
  4166. cur = llm_build_norm(ctx0, cur, hparams,
  4167. model.output_norm, NULL,
  4168. LLM_NORM_RMS, cb, -1);
  4169. cb(cur, "result_norm", -1);
  4170. // lm_head
  4171. cur = ggml_mul_mat(ctx0, model.output, cur);
  4172. cb(cur, "result_output", -1);
  4173. ggml_build_forward_expand(gf, cur);
  4174. return gf;
  4175. }
  4176. struct ggml_cgraph * build_baichuan() {
  4177. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4178. const int64_t n_embd_head = hparams.n_embd_head_v;
  4179. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4180. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4181. struct ggml_tensor * cur;
  4182. struct ggml_tensor * inpL;
  4183. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4184. cb(inpL, "inp_embd", -1);
  4185. // inp_pos - contains the positions
  4186. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4187. cb(inp_pos, "inp_pos", -1);
  4188. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4189. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  4190. cb(KQ_mask, "KQ_mask", -1);
  4191. // shift the entire K-cache if needed
  4192. if (do_rope_shift) {
  4193. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  4194. }
  4195. for (int il = 0; il < n_layer; ++il) {
  4196. struct ggml_tensor * inpSA = inpL;
  4197. cur = llm_build_norm(ctx0, inpL, hparams,
  4198. model.layers[il].attn_norm, NULL,
  4199. LLM_NORM_RMS, cb, il);
  4200. cb(cur, "attn_norm", il);
  4201. // self-attention
  4202. {
  4203. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4204. cb(Qcur, "Qcur", il);
  4205. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4206. cb(Kcur, "Kcur", il);
  4207. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4208. cb(Vcur, "Vcur", il);
  4209. switch (model.type) {
  4210. case MODEL_7B:
  4211. Qcur = ggml_rope_custom(
  4212. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  4213. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  4214. ext_factor, attn_factor, beta_fast, beta_slow
  4215. );
  4216. Kcur = ggml_rope_custom(
  4217. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  4218. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  4219. ext_factor, attn_factor, beta_fast, beta_slow
  4220. );
  4221. break;
  4222. case MODEL_13B:
  4223. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd/n_head, n_head, n_tokens);
  4224. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd/n_head, n_head, n_tokens);
  4225. break;
  4226. default:
  4227. GGML_ASSERT(false);
  4228. }
  4229. cb(Qcur, "Qcur", il);
  4230. cb(Kcur, "Kcur", il);
  4231. // apply ALiBi for 13B model
  4232. const float max_alibi_bias = model.type == MODEL_13B ? 8.0f : -1.0f;
  4233. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4234. model.layers[il].wo, NULL,
  4235. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, max_alibi_bias, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4236. cb(cur, "kqv_out", il);
  4237. }
  4238. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4239. cb(ffn_inp, "ffn_inp", il);
  4240. // feed-forward network
  4241. {
  4242. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4243. model.layers[il].ffn_norm, NULL,
  4244. LLM_NORM_RMS, cb, il);
  4245. cb(cur, "ffn_norm", il);
  4246. cur = llm_build_ffn(ctx0, cur,
  4247. model.layers[il].ffn_up, NULL,
  4248. model.layers[il].ffn_gate, NULL,
  4249. model.layers[il].ffn_down, NULL,
  4250. NULL,
  4251. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4252. cb(cur, "ffn_out", il);
  4253. }
  4254. cur = ggml_add(ctx0, cur, ffn_inp);
  4255. cb(cur, "l_out", il);
  4256. // input for next layer
  4257. inpL = cur;
  4258. }
  4259. cur = inpL;
  4260. cur = llm_build_norm(ctx0, cur, hparams,
  4261. model.output_norm, NULL,
  4262. LLM_NORM_RMS, cb, -1);
  4263. cb(cur, "result_norm", -1);
  4264. // lm_head
  4265. cur = ggml_mul_mat(ctx0, model.output, cur);
  4266. cb(cur, "result_output", -1);
  4267. ggml_build_forward_expand(gf, cur);
  4268. return gf;
  4269. }
  4270. struct ggml_cgraph * build_falcon() {
  4271. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4272. const int64_t n_embd_head = hparams.n_embd_head_v;
  4273. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4274. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4275. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4276. struct ggml_tensor * cur;
  4277. struct ggml_tensor * inpL;
  4278. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4279. cb(inpL, "inp_embd", -1);
  4280. // inp_pos - contains the positions
  4281. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4282. cb(inp_pos, "inp_pos", -1);
  4283. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4284. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  4285. cb(KQ_mask, "KQ_mask", -1);
  4286. // shift the entire K-cache if needed
  4287. if (do_rope_shift) {
  4288. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  4289. }
  4290. for (int il = 0; il < n_layer; ++il) {
  4291. struct ggml_tensor * attn_norm;
  4292. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  4293. model.layers[il].attn_norm,
  4294. model.layers[il].attn_norm_b,
  4295. LLM_NORM, cb, il);
  4296. cb(attn_norm, "attn_norm", il);
  4297. // self-attention
  4298. {
  4299. if (model.layers[il].attn_norm_2) {
  4300. // Falcon-40B
  4301. cur = llm_build_norm(ctx0, inpL, hparams,
  4302. model.layers[il].attn_norm_2,
  4303. model.layers[il].attn_norm_2_b,
  4304. LLM_NORM, cb, il);
  4305. cb(cur, "attn_norm_2", il);
  4306. } else {
  4307. cur = attn_norm;
  4308. }
  4309. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4310. cb(cur, "wqkv", il);
  4311. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4312. 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)));
  4313. 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)));
  4314. cb(Qcur, "Qcur", il);
  4315. cb(Kcur, "Kcur", il);
  4316. cb(Vcur, "Vcur", il);
  4317. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4318. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  4319. // using mode = 2 for neox mode
  4320. Qcur = ggml_rope_custom(
  4321. ctx0, Qcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4322. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4323. );
  4324. cb(Qcur, "Qcur", il);
  4325. Kcur = ggml_rope_custom(
  4326. ctx0, Kcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4327. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4328. );
  4329. cb(Kcur, "Kcur", il);
  4330. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4331. model.layers[il].wo, NULL,
  4332. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4333. cb(cur, "kqv_out", il);
  4334. }
  4335. struct ggml_tensor * ffn_inp = cur;
  4336. // feed forward
  4337. {
  4338. cur = llm_build_ffn(ctx0, attn_norm, // !! use the attn norm, not the result
  4339. model.layers[il].ffn_up, NULL,
  4340. NULL, NULL,
  4341. model.layers[il].ffn_down, NULL,
  4342. NULL,
  4343. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4344. cb(cur, "ffn_out", il);
  4345. }
  4346. cur = ggml_add(ctx0, cur, ffn_inp);
  4347. cb(cur, "l_out", il);
  4348. cur = ggml_add(ctx0, cur, inpL);
  4349. cb(cur, "l_out", il);
  4350. // input for next layer
  4351. inpL = cur;
  4352. }
  4353. cur = inpL;
  4354. // norm
  4355. cur = llm_build_norm(ctx0, cur, hparams,
  4356. model.output_norm,
  4357. model.output_norm_b,
  4358. LLM_NORM, cb, -1);
  4359. cb(cur, "result_norm", -1);
  4360. cur = ggml_mul_mat(ctx0, model.output, cur);
  4361. cb(cur, "result_output", -1);
  4362. ggml_build_forward_expand(gf, cur);
  4363. return gf;
  4364. }
  4365. struct ggml_cgraph * build_starcoder() {
  4366. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4367. const int64_t n_embd_head = hparams.n_embd_head_v;
  4368. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4369. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4370. struct ggml_tensor * cur;
  4371. struct ggml_tensor * pos;
  4372. struct ggml_tensor * inpL;
  4373. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4374. cb(inpL, "inp_embd", -1);
  4375. // inp_pos - contains the positions
  4376. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4377. cb(inp_pos, "inp_pos", -1);
  4378. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4379. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  4380. cb(KQ_mask, "KQ_mask", -1);
  4381. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  4382. cb(pos, "pos_embd", -1);
  4383. inpL = ggml_add(ctx0, inpL, pos);
  4384. cb(inpL, "inpL", -1);
  4385. for (int il = 0; il < n_layer; ++il) {
  4386. cur = llm_build_norm(ctx0, inpL, hparams,
  4387. model.layers[il].attn_norm,
  4388. model.layers[il].attn_norm_b,
  4389. LLM_NORM, cb, il);
  4390. cb(cur, "attn_norm", il);
  4391. // self-attention
  4392. {
  4393. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4394. cb(cur, "wqkv", il);
  4395. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4396. cb(cur, "bqkv", il);
  4397. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4398. 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)));
  4399. 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)));
  4400. cb(Qcur, "Qcur", il);
  4401. cb(Kcur, "Kcur", il);
  4402. cb(Vcur, "Vcur", il);
  4403. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4404. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4405. model.layers[il].wo, model.layers[il].bo,
  4406. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4407. cb(cur, "kqv_out", il);
  4408. }
  4409. // add the input
  4410. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  4411. cb(ffn_inp, "ffn_inp", il);
  4412. // FF
  4413. {
  4414. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4415. model.layers[il].ffn_norm,
  4416. model.layers[il].ffn_norm_b,
  4417. LLM_NORM, cb, il);
  4418. cb(cur, "ffn_norm", il);
  4419. cur = llm_build_ffn(ctx0, cur,
  4420. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  4421. NULL, NULL,
  4422. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  4423. NULL,
  4424. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4425. cb(cur, "ffn_out", il);
  4426. }
  4427. inpL = ggml_add(ctx0, cur, ffn_inp);
  4428. cb(inpL, "l_out", il);
  4429. }
  4430. cur = llm_build_norm(ctx0, inpL, hparams,
  4431. model.output_norm,
  4432. model.output_norm_b,
  4433. LLM_NORM, cb, -1);
  4434. cb(cur, "result_norm", -1);
  4435. cur = ggml_mul_mat(ctx0, model.output, cur);
  4436. cb(cur, "result_output", -1);
  4437. ggml_build_forward_expand(gf, cur);
  4438. return gf;
  4439. }
  4440. struct ggml_cgraph * build_persimmon() {
  4441. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4442. const int64_t n_embd_head = hparams.n_embd_head_v;
  4443. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4444. GGML_ASSERT(n_embd_head/2 == hparams.n_rot);
  4445. struct ggml_tensor * cur;
  4446. struct ggml_tensor * inpL;
  4447. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4448. cb(inpL, "inp_embd", -1);
  4449. // inp_pos - contains the positions
  4450. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4451. cb(inp_pos, "inp_pos", -1);
  4452. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4453. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  4454. cb(KQ_mask, "KQ_mask", -1);
  4455. if (do_rope_shift) {
  4456. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  4457. }
  4458. for (int il = 0; il < n_layer; ++il) {
  4459. struct ggml_tensor * residual = inpL;
  4460. cur = llm_build_norm(ctx0, inpL, hparams,
  4461. model.layers[il].attn_norm,
  4462. model.layers[il].attn_norm_b,
  4463. LLM_NORM, cb, il);
  4464. cb(cur, "attn_norm", il);
  4465. // self attention
  4466. {
  4467. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4468. cb(cur, "wqkv", il);
  4469. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4470. cb(cur, "bqkv", il);
  4471. // split qkv
  4472. GGML_ASSERT(n_head_kv == n_head);
  4473. struct ggml_tensor * tmpqkv = ggml_reshape_4d(ctx0, cur, n_embd_head, 3, n_head, n_tokens);
  4474. cb(tmpqkv, "tmpqkv", il);
  4475. struct ggml_tensor * tmpqkv_perm = ggml_cont(ctx0, ggml_permute(ctx0, tmpqkv, 0, 3, 1, 2));
  4476. cb(tmpqkv_perm, "tmpqkv", il);
  4477. struct ggml_tensor * tmpq = ggml_view_3d(
  4478. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  4479. ggml_element_size(tmpqkv_perm) * n_embd_head,
  4480. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  4481. 0
  4482. );
  4483. cb(tmpq, "tmpq", il);
  4484. struct ggml_tensor * tmpk = ggml_view_3d(
  4485. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  4486. ggml_element_size(tmpqkv_perm) * n_embd_head,
  4487. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  4488. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens
  4489. );
  4490. cb(tmpk, "tmpk", il);
  4491. // Q/K Layernorm
  4492. tmpq = llm_build_norm(ctx0, tmpq, hparams,
  4493. model.layers[il].attn_q_norm,
  4494. model.layers[il].attn_q_norm_b,
  4495. LLM_NORM, cb, il);
  4496. cb(tmpq, "tmpq", il);
  4497. tmpk = llm_build_norm(ctx0, tmpk, hparams,
  4498. model.layers[il].attn_k_norm,
  4499. model.layers[il].attn_k_norm_b,
  4500. LLM_NORM, cb, il);
  4501. cb(tmpk, "tmpk", il);
  4502. // RoPE the first n_rot of q/k, pass the other half, and concat.
  4503. struct ggml_tensor * qrot = ggml_view_3d(
  4504. ctx0, tmpq, hparams.n_rot, n_head, n_tokens,
  4505. ggml_element_size(tmpq) * n_embd_head,
  4506. ggml_element_size(tmpq) * n_embd_head * n_head,
  4507. 0
  4508. );
  4509. cb(qrot, "qrot", il);
  4510. struct ggml_tensor * krot = ggml_view_3d(
  4511. ctx0, tmpk, hparams.n_rot, n_head, n_tokens,
  4512. ggml_element_size(tmpk) * n_embd_head,
  4513. ggml_element_size(tmpk) * n_embd_head * n_head,
  4514. 0
  4515. );
  4516. cb(krot, "krot", il);
  4517. // get the second half of tmpq, e.g tmpq[n_rot:, :, :]
  4518. struct ggml_tensor * qpass = ggml_view_3d(
  4519. ctx0, tmpq, hparams.n_rot, n_head, n_tokens,
  4520. ggml_element_size(tmpq) * n_embd_head,
  4521. ggml_element_size(tmpq) * n_embd_head * n_head,
  4522. ggml_element_size(tmpq) * hparams.n_rot
  4523. );
  4524. cb(qpass, "qpass", il);
  4525. struct ggml_tensor * kpass = ggml_view_3d(
  4526. ctx0, tmpk, hparams.n_rot, n_head, n_tokens,
  4527. ggml_element_size(tmpk) * n_embd_head,
  4528. ggml_element_size(tmpk) * n_embd_head * n_head,
  4529. ggml_element_size(tmpk) * hparams.n_rot
  4530. );
  4531. cb(kpass, "kpass", il);
  4532. struct ggml_tensor * qrotated = ggml_rope_custom(
  4533. ctx0, qrot, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4534. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4535. );
  4536. cb(qrotated, "qrotated", il);
  4537. struct ggml_tensor * krotated = ggml_rope_custom(
  4538. ctx0, krot, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4539. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4540. );
  4541. cb(krotated, "krotated", il);
  4542. // ggml currently only supports concatenation on dim=2
  4543. // so we need to permute qrot, qpass, concat, then permute back.
  4544. qrotated = ggml_cont(ctx0, ggml_permute(ctx0, qrotated, 2, 1, 0, 3));
  4545. cb(qrotated, "qrotated", il);
  4546. krotated = ggml_cont(ctx0, ggml_permute(ctx0, krotated, 2, 1, 0, 3));
  4547. cb(krotated, "krotated", il);
  4548. qpass = ggml_cont(ctx0, ggml_permute(ctx0, qpass, 2, 1, 0, 3));
  4549. cb(qpass, "qpass", il);
  4550. kpass = ggml_cont(ctx0, ggml_permute(ctx0, kpass, 2, 1, 0, 3));
  4551. cb(kpass, "kpass", il);
  4552. struct ggml_tensor * Qcur = ggml_concat(ctx0, qrotated, qpass);
  4553. cb(Qcur, "Qcur", il);
  4554. struct ggml_tensor * Kcur = ggml_concat(ctx0, krotated, kpass);
  4555. cb(Kcur, "Kcur", il);
  4556. struct ggml_tensor * Q = ggml_cont(ctx0, ggml_permute(ctx0, Qcur, 2, 1, 0, 3));
  4557. cb(Q, "Q", il);
  4558. Kcur = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 2, 1, 0, 3));
  4559. cb(Kcur, "Kcur", il);
  4560. struct ggml_tensor * Vcur = ggml_view_3d(
  4561. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  4562. ggml_element_size(tmpqkv_perm) * n_embd_head,
  4563. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  4564. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens * 2
  4565. );
  4566. cb(Vcur, "Vcur", il);
  4567. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4568. model.layers[il].wo, model.layers[il].bo,
  4569. Kcur, Vcur, Q, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4570. cb(cur, "kqv_out", il);
  4571. }
  4572. struct ggml_tensor * ffn_inp = ggml_add(ctx0, residual, cur);
  4573. cb(ffn_inp, "ffn_inp", il);
  4574. // feed-forward network
  4575. {
  4576. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4577. model.layers[il].ffn_norm,
  4578. model.layers[il].ffn_norm_b,
  4579. LLM_NORM, cb, il);
  4580. cb(cur, "ffn_norm", il);
  4581. cur = llm_build_ffn(ctx0, cur,
  4582. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  4583. NULL, NULL,
  4584. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  4585. NULL,
  4586. LLM_FFN_RELU_SQR, LLM_FFN_SEQ, cb, il);
  4587. cb(cur, "ffn_out", il);
  4588. }
  4589. cur = ggml_add(ctx0, cur, ffn_inp);
  4590. cb(cur, "l_out", il);
  4591. inpL = cur;
  4592. }
  4593. cur = inpL;
  4594. cur = llm_build_norm(ctx0, cur, hparams,
  4595. model.output_norm,
  4596. model.output_norm_b,
  4597. LLM_NORM, cb, -1);
  4598. cb(cur, "result_norm", -1);
  4599. cur = ggml_mul_mat(ctx0, model.output, cur);
  4600. cb(cur, "result_output", -1);
  4601. ggml_build_forward_expand(gf, cur);
  4602. return gf;
  4603. }
  4604. struct ggml_cgraph * build_refact() {
  4605. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4606. const int64_t n_embd_head = hparams.n_embd_head_v;
  4607. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4608. struct ggml_tensor * cur;
  4609. struct ggml_tensor * inpL;
  4610. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4611. cb(inpL, "inp_embd", -1);
  4612. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4613. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  4614. cb(KQ_mask, "KQ_mask", -1);
  4615. for (int il = 0; il < n_layer; ++il) {
  4616. struct ggml_tensor * inpSA = inpL;
  4617. cur = llm_build_norm(ctx0, inpL, hparams,
  4618. model.layers[il].attn_norm, NULL,
  4619. LLM_NORM_RMS, cb, il);
  4620. cb(cur, "attn_norm", il);
  4621. // self-attention
  4622. {
  4623. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4624. cb(Qcur, "Qcur", il);
  4625. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4626. cb(Kcur, "Kcur", il);
  4627. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4628. cb(Vcur, "Vcur", il);
  4629. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  4630. cb(Kcur, "Kcur", il);
  4631. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4632. cb(Qcur, "Qcur", il);
  4633. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4634. model.layers[il].wo, NULL,
  4635. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, 8.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4636. cb(cur, "kqv_out", il);
  4637. }
  4638. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4639. cb(ffn_inp, "ffn_inp", il);
  4640. // feed-forward network
  4641. {
  4642. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4643. model.layers[il].ffn_norm, NULL,
  4644. LLM_NORM_RMS, cb, il);
  4645. cb(cur, "ffn_norm", il);
  4646. cur = llm_build_ffn(ctx0, cur,
  4647. model.layers[il].ffn_up, NULL,
  4648. model.layers[il].ffn_gate, NULL,
  4649. model.layers[il].ffn_down, NULL,
  4650. NULL,
  4651. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4652. cb(cur, "ffn_out", il);
  4653. }
  4654. cur = ggml_add(ctx0, cur, ffn_inp);
  4655. cb(cur, "l_out", il);
  4656. // input for next layer
  4657. inpL = cur;
  4658. }
  4659. cur = inpL;
  4660. cur = llm_build_norm(ctx0, cur, hparams,
  4661. model.output_norm, NULL,
  4662. LLM_NORM_RMS, cb, -1);
  4663. cb(cur, "result_norm", -1);
  4664. // lm_head
  4665. cur = ggml_mul_mat(ctx0, model.output, cur);
  4666. cb(cur, "result_output", -1);
  4667. ggml_build_forward_expand(gf, cur);
  4668. return gf;
  4669. }
  4670. struct ggml_cgraph * build_bloom() {
  4671. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4672. const int64_t n_embd_head = hparams.n_embd_head_v;
  4673. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4674. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4675. struct ggml_tensor * cur;
  4676. struct ggml_tensor * inpL;
  4677. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4678. cb(inpL, "inp_embd", -1);
  4679. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4680. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  4681. cb(KQ_mask, "KQ_mask", -1);
  4682. inpL = llm_build_norm(ctx0, inpL, hparams,
  4683. model.tok_norm,
  4684. model.tok_norm_b,
  4685. LLM_NORM, cb, -1);
  4686. cb(inpL, "inp_norm", -1);
  4687. for (int il = 0; il < n_layer; ++il) {
  4688. cur = llm_build_norm(ctx0, inpL, hparams,
  4689. model.layers[il].attn_norm,
  4690. model.layers[il].attn_norm_b,
  4691. LLM_NORM, cb, il);
  4692. cb(cur, "attn_norm", il);
  4693. // self-attention
  4694. {
  4695. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4696. cb(cur, "wqkv", il);
  4697. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4698. cb(cur, "bqkv", il);
  4699. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4700. 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)));
  4701. 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)));
  4702. cb(Qcur, "Qcur", il);
  4703. cb(Kcur, "Kcur", il);
  4704. cb(Vcur, "Vcur", il);
  4705. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4706. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4707. model.layers[il].wo, model.layers[il].bo,
  4708. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, 8.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4709. cb(cur, "kqv_out", il);
  4710. }
  4711. // Add the input
  4712. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  4713. cb(ffn_inp, "ffn_inp", il);
  4714. // FF
  4715. {
  4716. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4717. model.layers[il].ffn_norm,
  4718. model.layers[il].ffn_norm_b,
  4719. LLM_NORM, cb, il);
  4720. cb(cur, "ffn_norm", il);
  4721. cur = llm_build_ffn(ctx0, cur,
  4722. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  4723. NULL, NULL,
  4724. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  4725. NULL,
  4726. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4727. cb(cur, "ffn_out", il);
  4728. }
  4729. inpL = ggml_add(ctx0, cur, ffn_inp);
  4730. cb(inpL, "l_out", il);
  4731. }
  4732. cur = llm_build_norm(ctx0, inpL, hparams,
  4733. model.output_norm,
  4734. model.output_norm_b,
  4735. LLM_NORM, cb, -1);
  4736. cb(cur, "result_norm", -1);
  4737. cur = ggml_mul_mat(ctx0, model.output, cur);
  4738. cb(cur, "result_output", -1);
  4739. ggml_build_forward_expand(gf, cur);
  4740. return gf;
  4741. }
  4742. struct ggml_cgraph * build_mpt() {
  4743. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4744. const int64_t n_embd_head = hparams.n_embd_head_v;
  4745. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4746. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4747. struct ggml_tensor * cur;
  4748. struct ggml_tensor * inpL;
  4749. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4750. cb(inpL, "inp_embd", -1);
  4751. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4752. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  4753. cb(KQ_mask, "KQ_mask", -1);
  4754. for (int il = 0; il < n_layer; ++il) {
  4755. struct ggml_tensor * attn_norm;
  4756. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  4757. model.layers[il].attn_norm,
  4758. NULL,
  4759. LLM_NORM, cb, il);
  4760. cb(attn_norm, "attn_norm", il);
  4761. // self-attention
  4762. {
  4763. cur = attn_norm;
  4764. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4765. cb(cur, "wqkv", il);
  4766. if (hparams.f_clamp_kqv > 0.0f) {
  4767. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  4768. cb(cur, "wqkv_clamped", il);
  4769. }
  4770. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4771. 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)));
  4772. 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)));
  4773. cb(Qcur, "Qcur", il);
  4774. cb(Kcur, "Kcur", il);
  4775. cb(Vcur, "Vcur", il);
  4776. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4777. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4778. model.layers[il].wo, NULL,
  4779. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, hparams.f_max_alibi_bias, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4780. cb(cur, "kqv_out", il);
  4781. }
  4782. // Add the input
  4783. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  4784. cb(ffn_inp, "ffn_inp", il);
  4785. // feed forward
  4786. {
  4787. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4788. model.layers[il].ffn_norm,
  4789. NULL,
  4790. LLM_NORM, cb, il);
  4791. cb(cur, "ffn_norm", il);
  4792. cur = llm_build_ffn(ctx0, cur,
  4793. model.layers[il].ffn_up, NULL,
  4794. NULL, NULL,
  4795. model.layers[il].ffn_down, NULL,
  4796. model.layers[il].ffn_act,
  4797. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4798. cb(cur, "ffn_out", il);
  4799. }
  4800. cur = ggml_add(ctx0, cur, ffn_inp);
  4801. cb(cur, "l_out", il);
  4802. // input for next layer
  4803. inpL = cur;
  4804. }
  4805. cur = inpL;
  4806. cur = llm_build_norm(ctx0, cur, hparams,
  4807. model.output_norm,
  4808. NULL,
  4809. LLM_NORM, cb, -1);
  4810. cb(cur, "result_norm", -1);
  4811. cur = ggml_mul_mat(ctx0, model.output, cur);
  4812. cb(cur, "result_output", -1);
  4813. ggml_build_forward_expand(gf, cur);
  4814. return gf;
  4815. }
  4816. struct ggml_cgraph * build_stablelm() {
  4817. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  4818. const int64_t n_embd_head = hparams.n_embd_head_v;
  4819. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4820. struct ggml_tensor * cur;
  4821. struct ggml_tensor * inpL;
  4822. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4823. cb(inpL, "inp_embd", -1);
  4824. // inp_pos - contains the positions
  4825. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4826. cb(inp_pos, "inp_pos", -1);
  4827. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4828. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  4829. cb(KQ_mask, "KQ_mask", -1);
  4830. // shift the entire K-cache if needed
  4831. if (do_rope_shift) {
  4832. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  4833. }
  4834. for (int il = 0; il < n_layer; ++il) {
  4835. struct ggml_tensor * inpSA = inpL;
  4836. // norm
  4837. cur = llm_build_norm(ctx0, inpL, hparams,
  4838. model.layers[il].attn_norm,
  4839. model.layers[il].attn_norm_b,
  4840. LLM_NORM, cb, il);
  4841. cb(cur, "attn_norm", il);
  4842. // self-attention
  4843. {
  4844. // compute Q and K and RoPE them
  4845. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4846. cb(Qcur, "Qcur", il);
  4847. if (model.layers[il].bq) {
  4848. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  4849. cb(Qcur, "Qcur", il);
  4850. }
  4851. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4852. cb(Kcur, "Kcur", il);
  4853. if (model.layers[il].bk) {
  4854. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  4855. cb(Kcur, "Kcur", il);
  4856. }
  4857. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4858. cb(Vcur, "Vcur", il);
  4859. if (model.layers[il].bv) {
  4860. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  4861. cb(Vcur, "Vcur", il);
  4862. }
  4863. Qcur = ggml_rope_custom(
  4864. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  4865. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  4866. ext_factor, attn_factor, beta_fast, beta_slow
  4867. );
  4868. cb(Qcur, "Qcur", il);
  4869. Kcur = ggml_rope_custom(
  4870. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  4871. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  4872. ext_factor, attn_factor, beta_fast, beta_slow
  4873. );
  4874. cb(Kcur, "Kcur", il);
  4875. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4876. model.layers[il].wo, NULL,
  4877. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4878. cb(cur, "kqv_out", il);
  4879. }
  4880. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4881. cb(ffn_inp, "ffn_inp", il);
  4882. // feed-forward network
  4883. {
  4884. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4885. model.layers[il].ffn_norm,
  4886. model.layers[il].ffn_norm_b,
  4887. LLM_NORM, cb, il);
  4888. cb(cur, "ffn_norm", il);
  4889. cur = llm_build_ffn(ctx0, cur,
  4890. model.layers[il].ffn_up, NULL,
  4891. model.layers[il].ffn_gate, NULL,
  4892. model.layers[il].ffn_down, NULL,
  4893. NULL,
  4894. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4895. cb(cur, "ffn_out", il);
  4896. }
  4897. cur = ggml_add(ctx0, cur, ffn_inp);
  4898. cb(cur, "l_out", il);
  4899. // input for next layer
  4900. inpL = cur;
  4901. }
  4902. cur = inpL;
  4903. cur = llm_build_norm(ctx0, cur, hparams,
  4904. model.output_norm,
  4905. model.output_norm_b,
  4906. LLM_NORM, cb, -1);
  4907. cb(cur, "result_norm", -1);
  4908. // lm_head
  4909. cur = ggml_mul_mat(ctx0, model.output, cur);
  4910. cb(cur, "result_output", -1);
  4911. ggml_build_forward_expand(gf, cur);
  4912. return gf;
  4913. }
  4914. struct ggml_cgraph * build_qwen() {
  4915. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4916. const int64_t n_embd_head = hparams.n_embd_head_v;
  4917. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4918. struct ggml_tensor * cur;
  4919. struct ggml_tensor * inpL;
  4920. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4921. cb(inpL, "inp_embd", -1);
  4922. // inp_pos - contains the positions
  4923. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4924. cb(inp_pos, "inp_pos", -1);
  4925. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4926. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  4927. cb(KQ_mask, "KQ_mask", -1);
  4928. // shift the entire K-cache if needed
  4929. if (do_rope_shift) {
  4930. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  4931. }
  4932. for (int il = 0; il < n_layer; ++il) {
  4933. struct ggml_tensor * inpSA = inpL;
  4934. cur = llm_build_norm(ctx0, inpL, hparams,
  4935. model.layers[il].attn_norm, NULL,
  4936. LLM_NORM_RMS, cb, il);
  4937. cb(cur, "attn_norm", il);
  4938. // self-attention
  4939. {
  4940. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4941. cb(cur, "wqkv", il);
  4942. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4943. cb(cur, "bqkv", il);
  4944. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4945. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  4946. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 2*sizeof(float)*(n_embd)));
  4947. cb(Qcur, "Qcur", il);
  4948. cb(Kcur, "Kcur", il);
  4949. cb(Vcur, "Vcur", il);
  4950. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4951. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  4952. // using mode = 2 for neox mode
  4953. Qcur = ggml_rope_custom(
  4954. ctx0, Qcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4955. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4956. );
  4957. cb(Qcur, "Qcur", il);
  4958. Kcur = ggml_rope_custom(
  4959. ctx0, Kcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4960. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4961. );
  4962. cb(Kcur, "Kcur", il);
  4963. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4964. model.layers[il].wo, NULL,
  4965. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4966. cb(cur, "kqv_out", il);
  4967. }
  4968. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4969. cb(ffn_inp, "ffn_inp", il);
  4970. // feed-forward forward
  4971. {
  4972. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4973. model.layers[il].ffn_norm, NULL,
  4974. LLM_NORM_RMS, cb, il);
  4975. cb(cur, "ffn_norm", il);
  4976. cur = llm_build_ffn(ctx0, cur,
  4977. model.layers[il].ffn_up, NULL,
  4978. model.layers[il].ffn_gate, NULL,
  4979. model.layers[il].ffn_down, NULL,
  4980. NULL,
  4981. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4982. cb(cur, "ffn_out", il);
  4983. }
  4984. cur = ggml_add(ctx0, cur, ffn_inp);
  4985. cb(cur, "l_out", il);
  4986. // input for next layer
  4987. inpL = cur;
  4988. }
  4989. cur = inpL;
  4990. cur = llm_build_norm(ctx0, cur, hparams,
  4991. model.output_norm, NULL,
  4992. LLM_NORM_RMS, cb, -1);
  4993. cb(cur, "result_norm", -1);
  4994. // lm_head
  4995. cur = ggml_mul_mat(ctx0, model.output, cur);
  4996. cb(cur, "result_output", -1);
  4997. ggml_build_forward_expand(gf, cur);
  4998. return gf;
  4999. }
  5000. struct ggml_cgraph * build_qwen2() {
  5001. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5002. const int64_t n_embd_head = hparams.n_embd_head_v;
  5003. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5004. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5005. struct ggml_tensor * cur;
  5006. struct ggml_tensor * inpL;
  5007. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5008. cb(inpL, "inp_embd", -1);
  5009. // inp_pos - contains the positions
  5010. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5011. cb(inp_pos, "inp_pos", -1);
  5012. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5013. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  5014. cb(KQ_mask, "KQ_mask", -1);
  5015. // shift the entire K-cache if needed
  5016. if (do_rope_shift) {
  5017. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  5018. }
  5019. for (int il = 0; il < n_layer; ++il) {
  5020. struct ggml_tensor * inpSA = inpL;
  5021. // norm
  5022. cur = llm_build_norm(ctx0, inpL, hparams,
  5023. model.layers[il].attn_norm, NULL,
  5024. LLM_NORM_RMS, cb, il);
  5025. cb(cur, "attn_norm", il);
  5026. // self-attention
  5027. {
  5028. // compute Q and K and RoPE them
  5029. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5030. cb(Qcur, "Qcur", il);
  5031. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5032. cb(Qcur, "Qcur", il);
  5033. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5034. cb(Kcur, "Kcur", il);
  5035. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5036. cb(Kcur, "Kcur", il);
  5037. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5038. cb(Vcur, "Vcur", il);
  5039. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  5040. cb(Vcur, "Vcur", il);
  5041. // these nodes are added to the graph together so that they are not reordered
  5042. // by doing so, the number of splits in the graph is reduced
  5043. ggml_build_forward_expand(gf, Qcur);
  5044. ggml_build_forward_expand(gf, Kcur);
  5045. ggml_build_forward_expand(gf, Vcur);
  5046. Qcur = ggml_rope_custom(
  5047. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5048. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5049. ext_factor, attn_factor, beta_fast, beta_slow
  5050. );
  5051. cb(Qcur, "Qcur", il);
  5052. Kcur = ggml_rope_custom(
  5053. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5054. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5055. ext_factor, attn_factor, beta_fast, beta_slow
  5056. );
  5057. cb(Kcur, "Kcur", il);
  5058. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5059. model.layers[il].wo, model.layers[il].bo,
  5060. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5061. cb(cur, "kqv_out", il);
  5062. }
  5063. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5064. cb(ffn_inp, "ffn_inp", il);
  5065. // feed-forward network
  5066. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5067. model.layers[il].ffn_norm, NULL,
  5068. LLM_NORM_RMS, cb, il);
  5069. cb(cur, "ffn_norm", il);
  5070. cur = llm_build_ffn(ctx0, cur,
  5071. model.layers[il].ffn_up, NULL,
  5072. model.layers[il].ffn_gate, NULL,
  5073. model.layers[il].ffn_down, NULL,
  5074. NULL,
  5075. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5076. cb(cur, "ffn_out", il);
  5077. cur = ggml_add(ctx0, cur, ffn_inp);
  5078. cb(cur, "l_out", il);
  5079. // input for next layer
  5080. inpL = cur;
  5081. }
  5082. cur = inpL;
  5083. cur = llm_build_norm(ctx0, cur, hparams,
  5084. model.output_norm, NULL,
  5085. LLM_NORM_RMS, cb, -1);
  5086. cb(cur, "result_norm", -1);
  5087. // lm_head
  5088. cur = ggml_mul_mat(ctx0, model.output, cur);
  5089. cb(cur, "result_output", -1);
  5090. ggml_build_forward_expand(gf, cur);
  5091. return gf;
  5092. }
  5093. struct ggml_cgraph * build_phi2() {
  5094. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5095. const int64_t n_embd_head = hparams.n_embd_head_v;
  5096. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5097. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5098. struct ggml_tensor * cur;
  5099. struct ggml_tensor * attn_norm_output;
  5100. struct ggml_tensor * ffn_output;
  5101. struct ggml_tensor * inpL;
  5102. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5103. cb(inpL, "inp_embd", -1);
  5104. // inp_pos - contains the positions
  5105. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5106. cb(inp_pos, "inp_pos", -1);
  5107. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5108. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  5109. cb(KQ_mask, "KQ_mask", -1);
  5110. // shift the entire K-cache if needed
  5111. if (do_rope_shift) {
  5112. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  5113. }
  5114. for (int il = 0; il < n_layer; ++il) {
  5115. attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  5116. model.layers[il].attn_norm,
  5117. model.layers[il].attn_norm_b,
  5118. LLM_NORM, cb, il);
  5119. cb(attn_norm_output, "attn_norm", il);
  5120. // self-attention
  5121. {
  5122. struct ggml_tensor * Qcur = nullptr;
  5123. struct ggml_tensor * Kcur = nullptr;
  5124. struct ggml_tensor * Vcur = nullptr;
  5125. if (model.layers[il].wqkv) {
  5126. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, attn_norm_output);
  5127. cb(cur, "wqkv", il);
  5128. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5129. cb(cur, "bqkv", il);
  5130. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5131. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  5132. 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)));
  5133. } else {
  5134. Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  5135. Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  5136. Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  5137. }
  5138. cb(Qcur, "Qcur", il);
  5139. cb(Kcur, "Kcur", il);
  5140. cb(Vcur, "Vcur", il);
  5141. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5142. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  5143. Qcur = ggml_rope_custom(
  5144. ctx0, Qcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  5145. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5146. );
  5147. cb(Qcur, "Qcur", il);
  5148. // with phi2, we scale the Q to avoid precision issues
  5149. // ref: https://github.com/ml-explore/mlx-examples/blob/08e862336ade809bc37d1035f94b359e7d1a5152/phi2/phi2.py#L64-L66
  5150. Qcur = ggml_scale(ctx0, Qcur, 1.0f/sqrtf(float(n_embd_head)));
  5151. cb(Qcur, "Qcur", il);
  5152. Kcur = ggml_rope_custom(
  5153. ctx0, Kcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  5154. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5155. );
  5156. cb(Kcur, "Kcur", il);
  5157. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5158. model.layers[il].wo, model.layers[il].bo,
  5159. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f, cb, il);
  5160. cb(cur, "kqv_out", il);
  5161. }
  5162. // FF
  5163. {
  5164. ffn_output = llm_build_ffn(ctx0, attn_norm_output,
  5165. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5166. NULL, NULL,
  5167. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5168. NULL,
  5169. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5170. cb(ffn_output, "ffn_out", il);
  5171. }
  5172. cur = ggml_add(ctx0, cur, ffn_output);
  5173. cb(cur, "l_out", il);
  5174. cur = ggml_add(ctx0, cur, inpL);
  5175. cb(cur, "l_out", il);
  5176. inpL = cur;
  5177. }
  5178. cur = llm_build_norm(ctx0, inpL, hparams,
  5179. model.output_norm,
  5180. model.output_norm_b,
  5181. LLM_NORM, cb, -1);
  5182. cb(cur, "result_norm", -1);
  5183. cur = ggml_mul_mat(ctx0, model.output, cur);
  5184. cb(cur, "result_output_no_bias", -1);
  5185. cur = ggml_add(ctx0, cur, model.output_b);
  5186. cb(cur, "result_output", -1);
  5187. ggml_build_forward_expand(gf, cur);
  5188. return gf;
  5189. }
  5190. struct ggml_cgraph * build_plamo() {
  5191. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  5192. const int64_t n_embd_head = hparams.n_embd_head_v;
  5193. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5194. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5195. struct ggml_tensor * cur;
  5196. struct ggml_tensor * inpL;
  5197. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5198. cb(inpL, "inp_embd", -1);
  5199. // inp_pos - contains the positions
  5200. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5201. cb(inp_pos, "inp_pos", -1);
  5202. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5203. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  5204. cb(KQ_mask, "KQ_mask", -1);
  5205. // shift the entire K-cache if needed
  5206. if (do_rope_shift) {
  5207. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  5208. }
  5209. for (int il = 0; il < n_layer; ++il) {
  5210. // norm
  5211. cur = llm_build_norm(ctx0, inpL, hparams,
  5212. model.layers[il].attn_norm, NULL,
  5213. LLM_NORM_RMS, cb, il);
  5214. cb(cur, "attn_norm", il);
  5215. struct ggml_tensor * attention_norm = cur;
  5216. // self-attention
  5217. {
  5218. // compute Q and K and RoPE them
  5219. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5220. cb(Qcur, "Qcur", il);
  5221. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5222. cb(Kcur, "Kcur", il);
  5223. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5224. cb(Vcur, "Vcur", il);
  5225. Qcur = ggml_rope_custom(
  5226. ctx0, ggml_reshape_3d(ctx0, Qcur, hparams.n_rot, n_head, n_tokens), inp_pos,
  5227. n_embd_head, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5228. ext_factor, attn_factor, beta_fast, beta_slow);
  5229. cb(Qcur, "Qcur", il);
  5230. Kcur = ggml_rope_custom(
  5231. ctx0, ggml_reshape_3d(ctx0, Kcur, hparams.n_rot, n_head_kv, n_tokens), inp_pos,
  5232. n_embd_head, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5233. ext_factor, attn_factor, beta_fast, beta_slow);
  5234. cb(Kcur, "Kcur", il);
  5235. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5236. model.layers[il].wo, NULL,
  5237. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5238. cb(cur, "kqv_out", il);
  5239. }
  5240. struct ggml_tensor * sa_out = cur;
  5241. cur = attention_norm;
  5242. // feed-forward network
  5243. {
  5244. cur = llm_build_ffn(ctx0, cur,
  5245. model.layers[il].ffn_up, NULL,
  5246. model.layers[il].ffn_gate, NULL,
  5247. model.layers[il].ffn_down, NULL,
  5248. NULL,
  5249. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5250. cb(cur, "ffn_out", il);
  5251. }
  5252. cur = ggml_add(ctx0, cur, sa_out);
  5253. cb(cur, "l_out", il);
  5254. cur = ggml_add(ctx0, cur, inpL);
  5255. cb(cur, "l_out", il);
  5256. // input for next layer
  5257. inpL = cur;
  5258. }
  5259. cur = inpL;
  5260. cur = llm_build_norm(ctx0, cur, hparams,
  5261. model.output_norm, NULL,
  5262. LLM_NORM_RMS, cb, -1);
  5263. cb(cur, "result_norm", -1);
  5264. // lm_head
  5265. cur = ggml_mul_mat(ctx0, model.output, cur);
  5266. cb(cur, "result_output", -1);
  5267. ggml_build_forward_expand(gf, cur);
  5268. return gf;
  5269. }
  5270. struct ggml_cgraph * build_gpt2() {
  5271. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5272. const int64_t n_embd_head = hparams.n_embd_head_v;
  5273. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5274. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5275. struct ggml_tensor * cur;
  5276. struct ggml_tensor * pos;
  5277. struct ggml_tensor * inpL;
  5278. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5279. cb(inpL, "inp_embd", -1);
  5280. // inp_pos - contains the positions
  5281. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5282. cb(inp_pos, "inp_pos", -1);
  5283. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5284. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  5285. cb(KQ_mask, "KQ_mask", -1);
  5286. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  5287. cb(pos, "pos_embd", -1);
  5288. inpL = ggml_add(ctx0, inpL, pos);
  5289. cb(inpL, "inpL", -1);
  5290. for (int il = 0; il < n_layer; ++il) {
  5291. cur = llm_build_norm(ctx0, inpL, hparams,
  5292. model.layers[il].attn_norm,
  5293. model.layers[il].attn_norm_b,
  5294. LLM_NORM, cb, il);
  5295. cb(cur, "attn_norm", il);
  5296. // self-attention
  5297. {
  5298. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5299. cb(cur, "wqkv", il);
  5300. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5301. cb(cur, "bqkv", il);
  5302. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5303. 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)));
  5304. 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)));
  5305. cb(Qcur, "Qcur", il);
  5306. cb(Kcur, "Kcur", il);
  5307. cb(Vcur, "Vcur", il);
  5308. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5309. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5310. model.layers[il].wo, model.layers[il].bo,
  5311. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5312. cb(cur, "kqv_out", il);
  5313. }
  5314. // add the input
  5315. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5316. cb(ffn_inp, "ffn_inp", il);
  5317. // FF
  5318. {
  5319. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5320. model.layers[il].ffn_norm,
  5321. model.layers[il].ffn_norm_b,
  5322. LLM_NORM, cb, il);
  5323. cb(cur, "ffn_norm", il);
  5324. cur = llm_build_ffn(ctx0, cur,
  5325. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5326. NULL, NULL,
  5327. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5328. NULL,
  5329. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5330. cb(cur, "ffn_out", il);
  5331. }
  5332. inpL = ggml_add(ctx0, cur, ffn_inp);
  5333. cb(inpL, "l_out", il);
  5334. }
  5335. cur = llm_build_norm(ctx0, inpL, hparams,
  5336. model.output_norm,
  5337. model.output_norm_b,
  5338. LLM_NORM, cb, -1);
  5339. cb(cur, "result_norm", -1);
  5340. cur = ggml_mul_mat(ctx0, model.output, cur);
  5341. cb(cur, "result_output", -1);
  5342. ggml_build_forward_expand(gf, cur);
  5343. return gf;
  5344. }
  5345. struct ggml_cgraph * build_codeshell() {
  5346. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5347. const int64_t n_embd_head = hparams.n_embd_head_v;
  5348. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5349. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5350. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5351. struct ggml_tensor * cur;
  5352. struct ggml_tensor * inpL;
  5353. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5354. cb(inpL, "inp_embd", -1);
  5355. // inp_pos - contains the positions
  5356. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5357. cb(inp_pos, "inp_pos", -1);
  5358. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5359. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  5360. cb(KQ_mask, "KQ_mask", -1);
  5361. // shift the entire K-cache if needed
  5362. if (do_rope_shift) {
  5363. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  5364. }
  5365. for (int il = 0; il < n_layer; ++il) {
  5366. cur = llm_build_norm(ctx0, inpL, hparams,
  5367. model.layers[il].attn_norm,
  5368. model.layers[il].attn_norm_b,
  5369. LLM_NORM, cb, il);
  5370. cb(cur, "attn_norm", il);
  5371. // self-attention
  5372. {
  5373. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5374. cb(cur, "wqkv", il);
  5375. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5376. cb(cur, "bqkv", il);
  5377. struct ggml_tensor * tmpq = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5378. 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)));
  5379. 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)));
  5380. cb(tmpq, "tmpq", il);
  5381. cb(tmpk, "tmpk", il);
  5382. cb(Vcur, "Vcur", il);
  5383. struct ggml_tensor * Qcur = ggml_rope_custom(
  5384. ctx0, ggml_reshape_3d(ctx0, tmpq, n_embd_head, n_head, n_tokens), inp_pos,
  5385. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5386. ext_factor, attn_factor, beta_fast, beta_slow
  5387. );
  5388. cb(Qcur, "Qcur", il);
  5389. struct ggml_tensor * Kcur = ggml_rope_custom(
  5390. ctx0, ggml_reshape_3d(ctx0, tmpk, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5391. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5392. ext_factor, attn_factor, beta_fast, beta_slow
  5393. );
  5394. cb(Kcur, "Kcur", il);
  5395. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5396. model.layers[il].wo, model.layers[il].bo,
  5397. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5398. cb(cur, "kqv_out", il);
  5399. }
  5400. // add the input
  5401. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5402. cb(ffn_inp, "ffn_inp", il);
  5403. // FF
  5404. {
  5405. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5406. model.layers[il].ffn_norm,
  5407. model.layers[il].ffn_norm_b,
  5408. LLM_NORM, cb, il);
  5409. cb(cur, "ffn_norm", il);
  5410. cur = llm_build_ffn(ctx0, cur,
  5411. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5412. NULL, NULL,
  5413. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5414. NULL,
  5415. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5416. cb(cur, "ffn_out", il);
  5417. }
  5418. inpL = ggml_add(ctx0, cur, ffn_inp);
  5419. cb(inpL, "l_out", il);
  5420. }
  5421. cur = llm_build_norm(ctx0, inpL, hparams,
  5422. model.output_norm,
  5423. model.output_norm_b,
  5424. LLM_NORM, cb, -1);
  5425. cb(cur, "result_norm", -1);
  5426. cur = ggml_mul_mat(ctx0, model.output, cur);
  5427. cb(cur, "result_output", -1);
  5428. ggml_build_forward_expand(gf, cur);
  5429. return gf;
  5430. }
  5431. struct ggml_cgraph * build_orion() {
  5432. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5433. const int64_t n_embd_head = hparams.n_embd_head_v;
  5434. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5435. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5436. struct ggml_tensor * cur;
  5437. struct ggml_tensor * inpL;
  5438. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5439. cb(inpL, "inp_embd", -1);
  5440. // inp_pos - contains the positions
  5441. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5442. cb(inp_pos, "inp_pos", -1);
  5443. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5444. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  5445. cb(KQ_mask, "KQ_mask", -1);
  5446. // shift the entire K-cache if needed
  5447. if (do_rope_shift) {
  5448. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  5449. }
  5450. for (int il = 0; il < n_layer; ++il) {
  5451. struct ggml_tensor * inpSA = inpL;
  5452. // norm
  5453. cur = llm_build_norm(ctx0, inpL, hparams,
  5454. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  5455. LLM_NORM, cb, il);
  5456. cb(cur, "attn_norm", il);
  5457. // self-attention
  5458. {
  5459. // compute Q and K and RoPE them
  5460. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5461. cb(Qcur, "Qcur", il);
  5462. // if (model.layers[il].bq) {
  5463. // Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5464. // cb(Qcur, "Qcur", il);
  5465. // }
  5466. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5467. cb(Kcur, "Kcur", il);
  5468. // if (model.layers[il].bk) {
  5469. // Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5470. // cb(Kcur, "Kcur", il);
  5471. // }
  5472. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5473. cb(Vcur, "Vcur", il);
  5474. // if (model.layers[il].bv) {
  5475. // Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  5476. // cb(Vcur, "Vcur", il);
  5477. // }
  5478. Qcur = ggml_rope_custom(
  5479. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5480. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5481. ext_factor, attn_factor, beta_fast, beta_slow
  5482. );
  5483. cb(Qcur, "Qcur", il);
  5484. Kcur = ggml_rope_custom(
  5485. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5486. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5487. ext_factor, attn_factor, beta_fast, beta_slow
  5488. );
  5489. cb(Kcur, "Kcur", il);
  5490. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5491. model.layers[il].wo, NULL,
  5492. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5493. cb(cur, "kqv_out", il);
  5494. }
  5495. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5496. cb(ffn_inp, "ffn_inp", il);
  5497. // feed-forward network
  5498. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5499. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  5500. LLM_NORM, cb, il);
  5501. cb(cur, "ffn_norm", il);
  5502. cur = llm_build_ffn(ctx0, cur,
  5503. model.layers[il].ffn_up, NULL,
  5504. model.layers[il].ffn_gate, NULL,
  5505. model.layers[il].ffn_down, NULL,
  5506. NULL,
  5507. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5508. cb(cur, "ffn_out", il);
  5509. cur = ggml_add(ctx0, cur, ffn_inp);
  5510. cb(cur, "l_out", il);
  5511. // input for next layer
  5512. inpL = cur;
  5513. }
  5514. cur = inpL;
  5515. cur = llm_build_norm(ctx0, cur, hparams,
  5516. model.output_norm, model.output_norm_b,
  5517. LLM_NORM, cb, -1);
  5518. cb(cur, "result_norm", -1);
  5519. // lm_head
  5520. cur = ggml_mul_mat(ctx0, model.output, cur);
  5521. cb(cur, "result_output", -1);
  5522. ggml_build_forward_expand(gf, cur);
  5523. return gf;
  5524. }
  5525. struct ggml_cgraph * build_internlm2() {
  5526. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5527. const int64_t n_embd_head = hparams.n_embd_head_v;
  5528. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5529. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5530. struct ggml_tensor * cur;
  5531. struct ggml_tensor * inpL;
  5532. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5533. cb(inpL, "inp_embd", -1);
  5534. // inp_pos - contains the positions
  5535. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5536. cb(inp_pos, "inp_pos", -1);
  5537. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5538. struct ggml_tensor * KQ_mask = ggml_view_2d(ctx0, lctx.inp_KQ_mask, n_kv, n_tokens, n_kv*ggml_type_size(lctx.inp_KQ_mask->type), 0);
  5539. cb(KQ_mask, "KQ_mask", -1);
  5540. // shift the entire K-cache if needed
  5541. if (do_rope_shift) {
  5542. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  5543. }
  5544. for (int il = 0; il < n_layer; ++il) {
  5545. struct ggml_tensor * inpSA = inpL;
  5546. // norm
  5547. cur = llm_build_norm(ctx0, inpL, hparams,
  5548. model.layers[il].attn_norm, NULL,
  5549. LLM_NORM_RMS, cb, il);
  5550. cb(cur, "attn_norm", il);
  5551. // self-attention
  5552. {
  5553. // compute Q and K and RoPE them
  5554. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5555. cb(Qcur, "Qcur", il);
  5556. if (model.layers[il].bq) {
  5557. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5558. cb(Qcur, "Qcur", il);
  5559. }
  5560. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5561. cb(Kcur, "Kcur", il);
  5562. if (model.layers[il].bk) {
  5563. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5564. cb(Kcur, "Kcur", il);
  5565. }
  5566. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5567. cb(Vcur, "Vcur", il);
  5568. if (model.layers[il].bv) {
  5569. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  5570. cb(Vcur, "Vcur", il);
  5571. }
  5572. Qcur = ggml_rope_custom(
  5573. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5574. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  5575. ext_factor, attn_factor, beta_fast, beta_slow
  5576. );
  5577. cb(Qcur, "Qcur", il);
  5578. Kcur = ggml_rope_custom(
  5579. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5580. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  5581. ext_factor, attn_factor, beta_fast, beta_slow
  5582. );
  5583. cb(Kcur, "Kcur", il);
  5584. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5585. model.layers[il].wo, model.layers[il].bo,
  5586. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5587. cb(cur, "kqv_out", il);
  5588. }
  5589. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5590. cb(ffn_inp, "ffn_inp", il);
  5591. // feed-forward network
  5592. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5593. model.layers[il].ffn_norm, NULL,
  5594. LLM_NORM_RMS, cb, il);
  5595. cb(cur, "ffn_norm", il);
  5596. cur = llm_build_ffn(ctx0, cur,
  5597. model.layers[il].ffn_up, NULL,
  5598. model.layers[il].ffn_gate, NULL,
  5599. model.layers[il].ffn_down, NULL,
  5600. NULL,
  5601. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5602. cb(cur, "ffn_out", il);
  5603. cur = ggml_add(ctx0, cur, ffn_inp);
  5604. cb(cur, "l_out", il);
  5605. // input for next layer
  5606. inpL = cur;
  5607. }
  5608. cur = inpL;
  5609. cur = llm_build_norm(ctx0, cur, hparams,
  5610. model.output_norm, NULL,
  5611. LLM_NORM_RMS, cb, -1);
  5612. cb(cur, "result_norm", -1);
  5613. // lm_head
  5614. cur = ggml_mul_mat(ctx0, model.output, cur);
  5615. cb(cur, "result_output", -1);
  5616. ggml_build_forward_expand(gf, cur);
  5617. return gf;
  5618. }
  5619. };
  5620. static struct ggml_cgraph * llama_build_graph(
  5621. llama_context & lctx,
  5622. const llama_batch & batch) {
  5623. const auto & model = lctx.model;
  5624. // check if we should build the worst-case graph (for memory measurement)
  5625. const bool worst_case = ggml_tallocr_is_measure(lctx.alloc);
  5626. // this callback allows us to apply custom logic to each tensor (e.g. ggml-alloc, offloading, etc.)
  5627. llm_build_cb cb = [&](struct ggml_tensor * cur, const char * name, int il) {
  5628. if (il >= 0) {
  5629. ggml_format_name(cur, "%s-%d", name, il);
  5630. } else {
  5631. ggml_set_name(cur, name);
  5632. }
  5633. if (!lctx.cparams.offload_kqv) {
  5634. if (strcmp(name, "kqv_merged_cont") == 0) {
  5635. // all nodes between the KV store and the attention output are run on the CPU
  5636. ggml_backend_sched_set_node_backend(lctx.sched, cur, lctx.backend_cpu);
  5637. }
  5638. }
  5639. };
  5640. struct ggml_cgraph * result = NULL;
  5641. struct llm_build_context llm(lctx, batch, cb, worst_case);
  5642. //
  5643. // set input data
  5644. //
  5645. if (!ggml_tallocr_is_measure(lctx.alloc)) {
  5646. if (batch.token) {
  5647. const int64_t n_tokens = batch.n_tokens;
  5648. ggml_backend_tensor_set(lctx.inp_tokens, batch.token, 0, n_tokens*ggml_element_size(lctx.inp_tokens));
  5649. }
  5650. if (batch.embd) {
  5651. const int64_t n_embd = llm.n_embd;
  5652. const int64_t n_tokens = batch.n_tokens;
  5653. ggml_backend_tensor_set(lctx.inp_embd, batch.embd, 0, n_tokens*n_embd*ggml_element_size(lctx.inp_embd));
  5654. }
  5655. if (batch.pos) {
  5656. const int64_t n_tokens = batch.n_tokens;
  5657. ggml_backend_tensor_set(lctx.inp_pos, batch.pos, 0, n_tokens*ggml_element_size(lctx.inp_pos));
  5658. }
  5659. {
  5660. const int64_t n_kv = llm.n_kv;
  5661. const int64_t n_tokens = batch.n_tokens;
  5662. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  5663. float * data = (float *) lctx.inp_KQ_mask->data;
  5664. for (int h = 0; h < 1; ++h) {
  5665. for (int j = 0; j < n_tokens; ++j) {
  5666. const llama_pos pos = batch.pos[j];
  5667. const llama_seq_id seq_id = batch.seq_id[j][0];
  5668. for (int i = 0; i < n_kv; ++i) {
  5669. float f;
  5670. if (!lctx.kv_self.cells[i].has_seq_id(seq_id) || lctx.kv_self.cells[i].pos > pos) {
  5671. f = -INFINITY;
  5672. } else {
  5673. f = 0;
  5674. }
  5675. data[h*(n_kv*n_tokens) + j*n_kv + i] = f;
  5676. }
  5677. }
  5678. }
  5679. }
  5680. if (llm.do_rope_shift) {
  5681. const int64_t n_ctx = llm.n_ctx;
  5682. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_K_shift->buffer));
  5683. int32_t * data = (int32_t *) lctx.inp_K_shift->data;
  5684. for (int i = 0; i < n_ctx; ++i) {
  5685. data[i] = lctx.kv_self.cells[i].delta;
  5686. }
  5687. }
  5688. }
  5689. llm.init();
  5690. switch (model.arch) {
  5691. case LLM_ARCH_LLAMA:
  5692. {
  5693. result = llm.build_llama();
  5694. } break;
  5695. case LLM_ARCH_BAICHUAN:
  5696. {
  5697. result = llm.build_baichuan();
  5698. } break;
  5699. case LLM_ARCH_FALCON:
  5700. {
  5701. result = llm.build_falcon();
  5702. } break;
  5703. case LLM_ARCH_STARCODER:
  5704. {
  5705. result = llm.build_starcoder();
  5706. } break;
  5707. case LLM_ARCH_PERSIMMON:
  5708. {
  5709. result = llm.build_persimmon();
  5710. } break;
  5711. case LLM_ARCH_REFACT:
  5712. {
  5713. result = llm.build_refact();
  5714. } break;
  5715. case LLM_ARCH_BLOOM:
  5716. {
  5717. result = llm.build_bloom();
  5718. } break;
  5719. case LLM_ARCH_MPT:
  5720. {
  5721. result = llm.build_mpt();
  5722. } break;
  5723. case LLM_ARCH_STABLELM:
  5724. {
  5725. result = llm.build_stablelm();
  5726. } break;
  5727. case LLM_ARCH_QWEN:
  5728. {
  5729. result = llm.build_qwen();
  5730. } break;
  5731. case LLM_ARCH_QWEN2:
  5732. {
  5733. result = llm.build_qwen2();
  5734. } break;
  5735. case LLM_ARCH_PHI2:
  5736. {
  5737. result = llm.build_phi2();
  5738. } break;
  5739. case LLM_ARCH_PLAMO:
  5740. {
  5741. result = llm.build_plamo();
  5742. } break;
  5743. case LLM_ARCH_GPT2:
  5744. {
  5745. result = llm.build_gpt2();
  5746. } break;
  5747. case LLM_ARCH_CODESHELL:
  5748. {
  5749. result = llm.build_codeshell();
  5750. } break;
  5751. case LLM_ARCH_ORION:
  5752. {
  5753. result = llm.build_orion();
  5754. } break;
  5755. case LLM_ARCH_INTERNLM2:
  5756. {
  5757. result = llm.build_internlm2();
  5758. } break;
  5759. default:
  5760. GGML_ASSERT(false);
  5761. }
  5762. llm.free();
  5763. return result;
  5764. }
  5765. // decode a batch of tokens by evaluating the transformer
  5766. //
  5767. // - lctx: llama context
  5768. // - batch: batch to evaluate
  5769. //
  5770. // return 0 on success
  5771. // return positive int on warning
  5772. // return negative int on error
  5773. //
  5774. static int llama_decode_internal(
  5775. llama_context & lctx,
  5776. llama_batch batch) {
  5777. const uint32_t n_tokens = batch.n_tokens;
  5778. if (n_tokens == 0) {
  5779. LLAMA_LOG_ERROR("%s: n_tokens == 0", __func__);
  5780. return -1;
  5781. }
  5782. const auto & model = lctx.model;
  5783. const auto & hparams = model.hparams;
  5784. const auto & cparams = lctx.cparams;
  5785. const auto n_batch = cparams.n_batch;
  5786. GGML_ASSERT(n_tokens <= n_batch);
  5787. int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  5788. GGML_ASSERT((!batch.token && batch.embd) || (batch.token && !batch.embd)); // NOLINT
  5789. const int64_t t_start_us = ggml_time_us();
  5790. #ifdef GGML_USE_MPI
  5791. // TODO: needs fix after #3228
  5792. GGML_ASSERT(false && "not implemented");
  5793. //ggml_mpi_eval_init(lctx.ctx_mpi, &n_tokens, &n_past, &n_threads);
  5794. #endif
  5795. GGML_ASSERT(n_threads > 0);
  5796. auto & kv_self = lctx.kv_self;
  5797. const int64_t n_embd = hparams.n_embd;
  5798. const int64_t n_vocab = hparams.n_vocab;
  5799. // helpers for smoother batch API transition
  5800. // after deprecating the llama_eval calls, these will be removed
  5801. std::vector<llama_pos> pos;
  5802. std::vector<int32_t> n_seq_id;
  5803. std::vector<llama_seq_id *> seq_id_arr;
  5804. std::vector<std::vector<llama_seq_id>> seq_id;
  5805. if (batch.pos == nullptr) {
  5806. pos.resize(n_tokens);
  5807. for (uint32_t i = 0; i < n_tokens; i++) {
  5808. pos[i] = batch.all_pos_0 + i*batch.all_pos_1;
  5809. }
  5810. batch.pos = pos.data();
  5811. }
  5812. if (batch.seq_id == nullptr) {
  5813. n_seq_id.resize(n_tokens);
  5814. seq_id.resize(n_tokens);
  5815. seq_id_arr.resize(n_tokens);
  5816. for (uint32_t i = 0; i < n_tokens; i++) {
  5817. n_seq_id[i] = 1;
  5818. seq_id[i].resize(1);
  5819. seq_id[i][0] = batch.all_seq_id;
  5820. seq_id_arr[i] = seq_id[i].data();
  5821. }
  5822. batch.n_seq_id = n_seq_id.data();
  5823. batch.seq_id = seq_id_arr.data();
  5824. }
  5825. // if we have enough unused cells before the current head ->
  5826. // better to start searching from the beginning of the cache, hoping to fill it
  5827. if (kv_self.head > kv_self.used + 2*n_tokens) {
  5828. kv_self.head = 0;
  5829. }
  5830. if (!llama_kv_cache_find_slot(kv_self, batch)) {
  5831. return 1;
  5832. }
  5833. // a heuristic, to avoid attending the full cache if it is not yet utilized
  5834. // after enough generations, the benefit from this heuristic disappears
  5835. // if we start defragmenting the cache, the benefit from this will be more important
  5836. kv_self.n = std::min((int32_t) cparams.n_ctx, std::max(32, GGML_PAD(llama_kv_cache_cell_max(kv_self), 32)));
  5837. //kv_self.n = llama_kv_cache_cell_max(kv_self);
  5838. //printf("kv_self.n = %5d, kv_self.used = %5d, kv_self.head = %5d\n", kv_self.n, kv_self.used, kv_self.head);
  5839. ggml_backend_sched_reset(lctx.sched);
  5840. ggml_backend_sched_set_eval_callback(lctx.sched, lctx.cparams.cb_eval, lctx.cparams.cb_eval_user_data);
  5841. ggml_cgraph * gf = llama_build_graph(lctx, batch);
  5842. // the output is always the last tensor in the graph
  5843. struct ggml_tensor * res = gf->nodes[gf->n_nodes - 1];
  5844. GGML_ASSERT(strcmp(res->name, "result_output") == 0);
  5845. // the embeddings could be the second to last tensor, or the third to last tensor
  5846. struct ggml_tensor * embeddings = gf->nodes[gf->n_nodes - 2];
  5847. if (strcmp(embeddings->name, "result_norm") != 0) {
  5848. embeddings = gf->nodes[gf->n_nodes - 3];
  5849. GGML_ASSERT(strcmp(embeddings->name, "result_norm") == 0);
  5850. }
  5851. // 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);
  5852. // for big prompts, if BLAS is enabled, it is better to use only one thread
  5853. // otherwise, the threads are spin-lock waiting for the BLAS calls and are degrading the performance
  5854. // TODO: this is mostly important for Apple Silicon where CBLAS is still performing very well
  5855. // we still need some threads to process all non-mul_mat ops, but not too much to avoid interfering
  5856. // with the BLAS calls. need a better solution
  5857. if (n_tokens >= 32 && ggml_cpu_has_blas() && !ggml_cpu_has_gpublas()) {
  5858. n_threads = std::min(4, n_threads);
  5859. }
  5860. #ifdef GGML_USE_MPI
  5861. const int64_t n_layer = hparams.n_layer;
  5862. ggml_mpi_graph_compute_pre(lctx.ctx_mpi, gf, n_layer);
  5863. #endif
  5864. #ifdef GGML_USE_METAL
  5865. if (ggml_backend_is_metal(lctx.backend_metal)) {
  5866. ggml_backend_metal_set_n_cb(lctx.backend_metal, n_threads);
  5867. }
  5868. #endif
  5869. if (lctx.backend_cpu != nullptr) {
  5870. ggml_backend_cpu_set_n_threads(lctx.backend_cpu, n_threads);
  5871. }
  5872. ggml_backend_sched_graph_compute(lctx.sched, gf);
  5873. // fprintf(stderr, "splits: %d\n", ggml_backend_sched_get_n_splits(lctx.sched));
  5874. #ifdef GGML_USE_MPI
  5875. ggml_mpi_graph_compute_post(lctx.ctx_mpi, gf, n_layer);
  5876. #endif
  5877. // update the kv ring buffer
  5878. {
  5879. if (kv_self.has_shift) {
  5880. kv_self.has_shift = false;
  5881. for (uint32_t i = 0; i < kv_self.size; ++i) {
  5882. kv_self.cells[i].delta = 0;
  5883. }
  5884. }
  5885. kv_self.head += n_tokens;
  5886. // Ensure kv cache head points to a valid index.
  5887. if (kv_self.head >= kv_self.size) {
  5888. kv_self.head = 0;
  5889. }
  5890. }
  5891. #ifdef GGML_PERF
  5892. // print timing information per ggml operation (for debugging purposes)
  5893. // requires GGML_PERF to be defined
  5894. ggml_graph_print(gf);
  5895. #endif
  5896. // plot the computation graph in dot format (for debugging purposes)
  5897. //if (n_past%100 == 0) {
  5898. // ggml_graph_dump_dot(gf, NULL, "llama.dot");
  5899. //}
  5900. // extract logits
  5901. // TODO: do not compute and extract logits if only embeddings are needed
  5902. // need to update the graphs to skip "result_output"
  5903. {
  5904. auto & logits_out = lctx.logits;
  5905. #ifndef NDEBUG
  5906. auto & logits_valid = lctx.logits_valid;
  5907. logits_valid.clear();
  5908. logits_valid.resize(n_tokens);
  5909. logits_out.clear();
  5910. #endif
  5911. ggml_backend_t res_backend = ggml_backend_sched_get_node_backend(lctx.sched, res);
  5912. GGML_ASSERT(res_backend != nullptr);
  5913. if (batch.logits) {
  5914. logits_out.resize(n_vocab * n_tokens);
  5915. for (uint32_t i = 0; i < n_tokens; i++) {
  5916. if (batch.logits[i] == 0) {
  5917. continue;
  5918. }
  5919. ggml_backend_tensor_get_async(res_backend, res, logits_out.data() + (n_vocab*i), (n_vocab*i)*sizeof(float), n_vocab*sizeof(float));
  5920. #ifndef NDEBUG
  5921. logits_valid[i] = true;
  5922. #endif
  5923. }
  5924. } else if (lctx.logits_all) {
  5925. logits_out.resize(n_vocab * n_tokens);
  5926. ggml_backend_tensor_get_async(res_backend, res, logits_out.data(), 0, n_vocab*n_tokens*sizeof(float));
  5927. #ifndef NDEBUG
  5928. std::fill(logits_valid.begin(), logits_valid.end(), true);
  5929. #endif
  5930. } else {
  5931. logits_out.resize(n_vocab);
  5932. ggml_backend_tensor_get_async(res_backend, res, logits_out.data(), (n_vocab*(n_tokens - 1))*sizeof(float), n_vocab*sizeof(float));
  5933. #ifndef NDEBUG
  5934. logits_valid[0] = true;
  5935. #endif
  5936. }
  5937. ggml_backend_synchronize(res_backend);
  5938. }
  5939. // extract embeddings
  5940. if (!lctx.embedding.empty()) {
  5941. auto & embedding_out = lctx.embedding;
  5942. embedding_out.resize(n_embd);
  5943. ggml_backend_t embeddings_backend = ggml_backend_sched_get_node_backend(lctx.sched, embeddings);
  5944. ggml_backend_tensor_get_async(embeddings_backend, embeddings, embedding_out.data(), (n_embd*(n_tokens - 1))*sizeof(float), n_embd*sizeof(float));
  5945. ggml_backend_synchronize(embeddings_backend);
  5946. }
  5947. // measure the performance only for the single-token evals
  5948. if (n_tokens == 1) {
  5949. lctx.t_eval_us += ggml_time_us() - t_start_us;
  5950. lctx.n_eval++;
  5951. }
  5952. else if (n_tokens > 1) {
  5953. lctx.t_p_eval_us += ggml_time_us() - t_start_us;
  5954. lctx.n_p_eval += n_tokens;
  5955. }
  5956. // get a more accurate load time, upon first eval
  5957. // TODO: fix this
  5958. if (!lctx.has_evaluated_once) {
  5959. lctx.t_load_us = ggml_time_us() - lctx.t_start_us;
  5960. lctx.has_evaluated_once = true;
  5961. }
  5962. return 0;
  5963. }
  5964. //
  5965. // tokenizer
  5966. //
  5967. static enum llama_vocab_type llama_vocab_get_type(const llama_vocab & vocab) {
  5968. return vocab.type;
  5969. }
  5970. static bool llama_is_normal_token(const llama_vocab & vocab, llama_token id) {
  5971. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL;
  5972. }
  5973. static bool llama_is_unknown_token(const llama_vocab & vocab, llama_token id) {
  5974. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_UNKNOWN;
  5975. }
  5976. static bool llama_is_control_token(const llama_vocab & vocab, llama_token id) {
  5977. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_CONTROL;
  5978. }
  5979. static bool llama_is_byte_token(const llama_vocab & vocab, llama_token id) {
  5980. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_BYTE;
  5981. }
  5982. static bool llama_is_user_defined_token(const llama_vocab& vocab, llama_token id) {
  5983. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_USER_DEFINED;
  5984. }
  5985. static uint8_t llama_token_to_byte(const llama_vocab& vocab, llama_token id) {
  5986. GGML_ASSERT(llama_is_byte_token(vocab, id));
  5987. const auto& token_data = vocab.id_to_token.at(id);
  5988. switch (llama_vocab_get_type(vocab)) {
  5989. case LLAMA_VOCAB_TYPE_SPM: {
  5990. auto buf = token_data.text.substr(3, 2);
  5991. return strtol(buf.c_str(), NULL, 16);
  5992. }
  5993. case LLAMA_VOCAB_TYPE_BPE: {
  5994. GGML_ASSERT(false);
  5995. return unicode_to_bytes_bpe(token_data.text);
  5996. }
  5997. default:
  5998. GGML_ASSERT(false);
  5999. }
  6000. }
  6001. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch) {
  6002. static const char * hex = "0123456789ABCDEF";
  6003. switch (llama_vocab_get_type(vocab)) {
  6004. case LLAMA_VOCAB_TYPE_SPM: {
  6005. const char buf[7] = { '<', '0', 'x', hex[ch >> 4], hex[ch & 15], '>', 0 };
  6006. return vocab.token_to_id.at(buf);
  6007. }
  6008. case LLAMA_VOCAB_TYPE_BPE: {
  6009. return vocab.token_to_id.at(bytes_to_unicode_bpe(ch));
  6010. }
  6011. default:
  6012. GGML_ASSERT(false);
  6013. }
  6014. }
  6015. static void llama_escape_whitespace(std::string & text) {
  6016. replace_all(text, " ", "\xe2\x96\x81");
  6017. }
  6018. static void llama_unescape_whitespace(std::string & word) {
  6019. replace_all(word, "\xe2\x96\x81", " ");
  6020. }
  6021. struct llm_symbol {
  6022. using index = int;
  6023. index prev;
  6024. index next;
  6025. const char * text;
  6026. size_t n;
  6027. };
  6028. static_assert(std::is_trivially_copyable<llm_symbol>::value, "llm_symbol is not trivially copyable");
  6029. // SPM tokenizer
  6030. // original implementation:
  6031. // https://github.com/ggerganov/llama.cpp/commit/074bea2eb1f1349a0118239c4152914aecaa1be4
  6032. struct llm_bigram_spm {
  6033. struct comparator {
  6034. bool operator()(llm_bigram_spm & l, llm_bigram_spm & r) {
  6035. return (l.score < r.score) || (l.score == r.score && l.left > r.left);
  6036. }
  6037. };
  6038. using queue_storage = std::vector<llm_bigram_spm>;
  6039. using queue = std::priority_queue<llm_bigram_spm, queue_storage, comparator>;
  6040. llm_symbol::index left;
  6041. llm_symbol::index right;
  6042. float score;
  6043. size_t size;
  6044. };
  6045. struct llm_tokenizer_spm {
  6046. llm_tokenizer_spm(const llama_vocab & vocab): vocab(vocab) {}
  6047. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  6048. // split string into utf8 chars
  6049. int index = 0;
  6050. size_t offs = 0;
  6051. while (offs < text.size()) {
  6052. llm_symbol sym;
  6053. size_t len = utf8_len(text[offs]);
  6054. sym.text = text.c_str() + offs;
  6055. sym.n = std::min(len, text.size() - offs);
  6056. offs += sym.n;
  6057. sym.prev = index - 1;
  6058. sym.next = offs == text.size() ? -1 : index + 1;
  6059. index++;
  6060. symbols.emplace_back(sym);
  6061. }
  6062. // seed the work queue with all possible 2-character tokens.
  6063. for (size_t i = 1; i < symbols.size(); ++i) {
  6064. try_add_bigram(i - 1, i);
  6065. }
  6066. // keep substituting the highest frequency pairs for as long as we can.
  6067. while (!work_queue.empty()) {
  6068. auto bigram = work_queue.top();
  6069. work_queue.pop();
  6070. auto & left_sym = symbols[bigram.left];
  6071. auto & right_sym = symbols[bigram.right];
  6072. // if one of the symbols already got merged, skip it.
  6073. if (left_sym.n == 0 || right_sym.n == 0 ||
  6074. left_sym.n + right_sym.n != bigram.size) {
  6075. continue;
  6076. }
  6077. // merge the right sym into the left one
  6078. left_sym.n += right_sym.n;
  6079. right_sym.n = 0;
  6080. //LLAMA_LOG_INFO("left = '%*s' size = %zu\n", (int) left_sym.n, left_sym.text, bigram.size);
  6081. // remove the right sym from the chain
  6082. left_sym.next = right_sym.next;
  6083. if (right_sym.next >= 0) {
  6084. symbols[right_sym.next].prev = bigram.left;
  6085. }
  6086. // find more substitutions
  6087. try_add_bigram(left_sym.prev, bigram.left);
  6088. try_add_bigram(bigram.left, left_sym.next);
  6089. }
  6090. for (int i = 0; i != -1; i = symbols[i].next) {
  6091. auto & symbol = symbols[i];
  6092. resegment(symbol, output);
  6093. }
  6094. }
  6095. private:
  6096. void resegment(llm_symbol & symbol, std::vector<llama_vocab::id> & output) {
  6097. auto text = std::string(symbol.text, symbol.n);
  6098. auto token = vocab.token_to_id.find(text);
  6099. // Do we need to support is_unused?
  6100. if (token != vocab.token_to_id.end()) {
  6101. output.push_back((*token).second);
  6102. return;
  6103. }
  6104. const auto p = rev_merge.find(text);
  6105. if (p == rev_merge.end()) {
  6106. // output any symbols that did not form tokens as bytes.
  6107. for (int j = 0; j < (int)symbol.n; ++j) {
  6108. llama_vocab::id token_id = llama_byte_to_token(vocab, symbol.text[j]);
  6109. output.push_back(token_id);
  6110. }
  6111. return;
  6112. }
  6113. resegment(symbols[p->second.first], output);
  6114. resegment(symbols[p->second.second], output);
  6115. }
  6116. void try_add_bigram(int left, int right) {
  6117. if (left == -1 || right == -1) {
  6118. return;
  6119. }
  6120. const std::string text = std::string(symbols[left].text, symbols[left].n + symbols[right].n);
  6121. auto token = vocab.token_to_id.find(text);
  6122. if (token == vocab.token_to_id.end()) {
  6123. return;
  6124. }
  6125. if (static_cast<size_t>((*token).second) >= vocab.id_to_token.size()) {
  6126. return;
  6127. }
  6128. const auto & tok_data = vocab.id_to_token[(*token).second];
  6129. llm_bigram_spm bigram;
  6130. bigram.left = left;
  6131. bigram.right = right;
  6132. bigram.score = tok_data.score;
  6133. bigram.size = text.size();
  6134. work_queue.push(bigram);
  6135. // Do we need to support is_unused?
  6136. rev_merge[text] = std::make_pair(left, right);
  6137. }
  6138. const llama_vocab & vocab;
  6139. std::vector<llm_symbol> symbols;
  6140. llm_bigram_spm::queue work_queue;
  6141. std::map<std::string, std::pair<int, int>> rev_merge;
  6142. };
  6143. // BPE tokenizer
  6144. // adapted from https://github.com/cmp-nct/ggllm.cpp [MIT License]
  6145. // tried to simplify unicode stuff, so most likely does not work 100% correctly!
  6146. // TODO: there are a lot of common parts between spm and bpe tokenizers, should be refactored and reused
  6147. struct llm_bigram_bpe {
  6148. struct comparator {
  6149. bool operator()(const llm_bigram_bpe & l, const llm_bigram_bpe & r) const {
  6150. return l.rank > r.rank || (l.rank == r.rank && l.left > r.left);
  6151. }
  6152. };
  6153. using queue_storage = std::vector<llm_bigram_bpe>;
  6154. using queue = std::priority_queue<llm_bigram_bpe, queue_storage, comparator>;
  6155. llm_symbol::index left;
  6156. llm_symbol::index right;
  6157. std::string text;
  6158. int rank;
  6159. size_t size;
  6160. };
  6161. struct llm_tokenizer_bpe {
  6162. llm_tokenizer_bpe(const llama_vocab & vocab): vocab(vocab) {}
  6163. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  6164. int final_prev_index = -1;
  6165. auto word_collection = bpe_gpt2_preprocess(text);
  6166. symbols_final.clear();
  6167. for (auto & word : word_collection) {
  6168. work_queue = llm_bigram_bpe::queue();
  6169. symbols.clear();
  6170. int index = 0;
  6171. size_t offset = 0;
  6172. while (offset < word.size()) {
  6173. llm_symbol sym;
  6174. size_t char_len = std::min(word.size() - offset, (size_t) ::utf8_len(word[offset]));
  6175. sym.text = word.c_str() + offset;
  6176. sym.n = char_len;
  6177. offset += sym.n;
  6178. sym.prev = index - 1;
  6179. sym.next = offset == word.size() ? -1 : index + 1;
  6180. index++;
  6181. symbols.emplace_back(sym);
  6182. }
  6183. for (size_t i = 1; i < symbols.size(); ++i) {
  6184. add_new_bigram(i - 1, i);
  6185. }
  6186. // build token(s)
  6187. while (!work_queue.empty()) {
  6188. auto bigram = work_queue.top();
  6189. work_queue.pop();
  6190. auto & left_symbol = symbols[bigram.left];
  6191. auto & right_symbol = symbols[bigram.right];
  6192. if (left_symbol.n == 0 || right_symbol.n == 0) {
  6193. continue;
  6194. }
  6195. std::string left_token = std::string(left_symbol.text, left_symbol.n);
  6196. std::string right_token = std::string(right_symbol.text, right_symbol.n);
  6197. if (left_token + right_token != bigram.text) {
  6198. continue; // Skip this bigram if it's outdated
  6199. }
  6200. // merge the right sym into the left one
  6201. left_symbol.n += right_symbol.n;
  6202. right_symbol.n = 0;
  6203. // remove the right sym from the chain
  6204. left_symbol.next = right_symbol.next;
  6205. if (right_symbol.next >= 0) {
  6206. symbols[right_symbol.next].prev = bigram.left;
  6207. }
  6208. add_new_bigram(left_symbol.prev, bigram.left); // left side of current symbol
  6209. add_new_bigram(bigram.left, left_symbol.next); // right side of current symbol
  6210. }
  6211. // add the fnished tokens to the final list keeping correct order for next and prev
  6212. for (auto & sym : symbols) {
  6213. if (sym.n > 0) {
  6214. sym.prev = final_prev_index;
  6215. sym.next = -1;
  6216. if (final_prev_index != -1) {
  6217. symbols_final[final_prev_index].next = symbols_final.size();
  6218. }
  6219. symbols_final.emplace_back(sym);
  6220. final_prev_index = symbols_final.size() - 1;
  6221. }
  6222. }
  6223. }
  6224. symbols = symbols_final;
  6225. if (!symbols.empty()) {
  6226. for (int i = 0; i != -1; i = symbols[i].next) {
  6227. auto & symbol = symbols[i];
  6228. if (symbol.n == 0) {
  6229. continue;
  6230. }
  6231. const std::string str = std::string(symbol.text, symbol.n);
  6232. const auto token = vocab.token_to_id.find(str);
  6233. if (token == vocab.token_to_id.end()) {
  6234. for (auto j = str.begin(); j != str.end(); ++j) {
  6235. std::string byte_str(1, *j);
  6236. auto token_multibyte = vocab.token_to_id.find(byte_str);
  6237. if (token_multibyte == vocab.token_to_id.end()) {
  6238. throw std::runtime_error("ERROR: byte not found in vocab");
  6239. }
  6240. output.push_back((*token_multibyte).second);
  6241. }
  6242. } else {
  6243. output.push_back((*token).second);
  6244. }
  6245. }
  6246. }
  6247. }
  6248. private:
  6249. void add_new_bigram(int left, int right) {
  6250. if (left == -1 || right == -1) {
  6251. return;
  6252. }
  6253. std::string left_token = std::string(symbols[left].text, symbols[left].n);
  6254. std::string right_token = std::string(symbols[right].text, symbols[right].n);
  6255. int rank_found = -1;
  6256. rank_found = vocab.find_bpe_rank(left_token, right_token);
  6257. if (rank_found < 0) {
  6258. return;
  6259. }
  6260. llm_bigram_bpe bigram;
  6261. bigram.left = left;
  6262. bigram.right = right;
  6263. bigram.text = left_token + right_token;
  6264. bigram.size = left_token.size() + right_token.size();
  6265. bigram.rank = rank_found;
  6266. work_queue.push(bigram);
  6267. }
  6268. std::vector<std::string> bpe_gpt2_preprocess(const std::string & text) {
  6269. std::vector<std::string> bpe_words;
  6270. std::vector<std::string> bpe_encoded_words;
  6271. std::string token = "";
  6272. // GPT2 system regex: 's|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+
  6273. bool collecting_numeric = false;
  6274. bool collecting_letter = false;
  6275. bool collecting_special = false;
  6276. bool collecting_whitespace_lookahead = false;
  6277. bool collecting = false;
  6278. std::vector<std::string> text_utf;
  6279. text_utf.reserve(text.size());
  6280. bpe_words.reserve(text.size());
  6281. bpe_encoded_words.reserve(text.size());
  6282. auto cps = codepoints_from_utf8(text);
  6283. for (size_t i = 0; i < cps.size(); ++i)
  6284. text_utf.emplace_back(codepoint_to_utf8(cps[i]));
  6285. for (int i = 0; i < (int)text_utf.size(); i++) {
  6286. const std::string & utf_char = text_utf[i];
  6287. bool split_condition = false;
  6288. int bytes_remain = text_utf.size() - i;
  6289. // forward backward lookups
  6290. const std::string & utf_char_next = (i + 1 < (int)text_utf.size()) ? text_utf[i + 1] : "";
  6291. const std::string & utf_char_next_next = (i + 2 < (int)text_utf.size()) ? text_utf[i + 2] : "";
  6292. // handling contractions
  6293. if (!split_condition && bytes_remain >= 2) {
  6294. // 's|'t|'m|'d
  6295. if (utf_char == "\'" && (utf_char_next == "s" || utf_char_next == "t" || utf_char_next == "m" || utf_char_next == "d")) {
  6296. split_condition = true;
  6297. }
  6298. if (split_condition) {
  6299. if (token.size()) {
  6300. bpe_words.emplace_back(token); // push previous content as token
  6301. }
  6302. token = utf_char + utf_char_next;
  6303. bpe_words.emplace_back(token);
  6304. token = "";
  6305. i++;
  6306. continue;
  6307. }
  6308. }
  6309. if (!split_condition && bytes_remain >= 3) {
  6310. // 're|'ve|'ll
  6311. if (utf_char == "\'" && (
  6312. (utf_char_next == "r" && utf_char_next_next == "e") ||
  6313. (utf_char_next == "v" && utf_char_next_next == "e") ||
  6314. (utf_char_next == "l" && utf_char_next_next == "l"))
  6315. ) {
  6316. split_condition = true;
  6317. }
  6318. if (split_condition) {
  6319. // current token + next token can be defined
  6320. if (token.size()) {
  6321. bpe_words.emplace_back(token); // push previous content as token
  6322. }
  6323. token = utf_char + utf_char_next + utf_char_next_next;
  6324. bpe_words.emplace_back(token); // the contraction
  6325. token = "";
  6326. i += 2;
  6327. continue;
  6328. }
  6329. }
  6330. if (!split_condition && !collecting) {
  6331. if (codepoint_type(utf_char) == CODEPOINT_TYPE_LETTER || (!token.size() && utf_char == " " && codepoint_type(utf_char_next) == CODEPOINT_TYPE_LETTER)) {
  6332. collecting_letter = true;
  6333. collecting = true;
  6334. }
  6335. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_DIGIT || (!token.size() && utf_char == " " && codepoint_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  6336. collecting_numeric = true;
  6337. collecting = true;
  6338. }
  6339. else if (
  6340. ((codepoint_type(utf_char) != CODEPOINT_TYPE_LETTER && codepoint_type(utf_char) != CODEPOINT_TYPE_DIGIT) && (codepoint_type(utf_char) != CODEPOINT_TYPE_WHITESPACE)) ||
  6341. (!token.size() && utf_char == " " && codepoint_type(utf_char_next) != CODEPOINT_TYPE_LETTER && codepoint_type(utf_char_next) != CODEPOINT_TYPE_DIGIT && codepoint_type(utf_char_next) != CODEPOINT_TYPE_WHITESPACE)
  6342. ) {
  6343. collecting_special = true;
  6344. collecting = true;
  6345. }
  6346. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_WHITESPACE && codepoint_type(utf_char_next) == CODEPOINT_TYPE_WHITESPACE) {
  6347. collecting_whitespace_lookahead = true;
  6348. collecting = true;
  6349. }
  6350. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_WHITESPACE) {
  6351. split_condition = true;
  6352. }
  6353. }
  6354. else if (!split_condition && collecting) {
  6355. if (collecting_letter && codepoint_type(utf_char) != CODEPOINT_TYPE_LETTER) {
  6356. split_condition = true;
  6357. }
  6358. else if (collecting_numeric && codepoint_type(utf_char) != CODEPOINT_TYPE_DIGIT) {
  6359. split_condition = true;
  6360. }
  6361. else if (collecting_special && (codepoint_type(utf_char) == CODEPOINT_TYPE_LETTER || codepoint_type(utf_char) == CODEPOINT_TYPE_DIGIT || codepoint_type(utf_char) == CODEPOINT_TYPE_WHITESPACE)) {
  6362. split_condition = true;
  6363. }
  6364. else if (collecting_whitespace_lookahead && (codepoint_type(utf_char_next) == CODEPOINT_TYPE_LETTER || codepoint_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  6365. split_condition = true;
  6366. }
  6367. }
  6368. if (utf_char_next == "") {
  6369. split_condition = true; // final
  6370. token += utf_char;
  6371. }
  6372. if (split_condition) {
  6373. if (token.size()) {
  6374. bpe_words.emplace_back(token);
  6375. }
  6376. token = utf_char;
  6377. collecting = false;
  6378. collecting_letter = false;
  6379. collecting_numeric = false;
  6380. collecting_special = false;
  6381. collecting_whitespace_lookahead = false;
  6382. }
  6383. else {
  6384. token += utf_char;
  6385. }
  6386. }
  6387. for (std::string & word : bpe_words) {
  6388. std::string encoded_token = "";
  6389. for (char & c : word) {
  6390. encoded_token += bytes_to_unicode_bpe(c);
  6391. }
  6392. bpe_encoded_words.emplace_back(encoded_token);
  6393. }
  6394. return bpe_encoded_words;
  6395. }
  6396. const llama_vocab & vocab;
  6397. std::vector<llm_symbol> symbols;
  6398. std::vector<llm_symbol> symbols_final;
  6399. llm_bigram_bpe::queue work_queue;
  6400. };
  6401. typedef enum FRAGMENT_BUFFER_VARIANT_TYPE{
  6402. FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN,
  6403. FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT
  6404. } FRAGMENT_BUFFER_VARIANT_TYPE;
  6405. struct fragment_buffer_variant{
  6406. fragment_buffer_variant(llama_vocab::id _token)
  6407. :
  6408. type(FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN),
  6409. token(_token),
  6410. raw_text(_dummy),
  6411. offset(0),
  6412. length(0){}
  6413. fragment_buffer_variant(const std::string & _raw_text, int64_t _offset, int64_t _length)
  6414. :
  6415. type(FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT),
  6416. token((llama_vocab::id)-1),
  6417. raw_text(_raw_text),
  6418. offset(_offset),
  6419. length(_length){
  6420. GGML_ASSERT( _offset >= 0 );
  6421. GGML_ASSERT( _length >= 1 );
  6422. GGML_ASSERT( offset + length <= raw_text.length() );
  6423. }
  6424. const FRAGMENT_BUFFER_VARIANT_TYPE type;
  6425. const llama_vocab::id token;
  6426. const std::string _dummy;
  6427. const std::string & raw_text;
  6428. const uint64_t offset;
  6429. const uint64_t length;
  6430. };
  6431. // #define PRETOKENIZERDEBUG
  6432. static void tokenizer_st_partition(const llama_vocab & vocab, std::forward_list<fragment_buffer_variant> & buffer)
  6433. {
  6434. // for each special token
  6435. for (const auto & st: vocab.special_tokens_cache) {
  6436. const auto & special_token = st.first;
  6437. const auto & special_id = st.second;
  6438. // for each text fragment
  6439. std::forward_list<fragment_buffer_variant>::iterator it = buffer.begin();
  6440. while (it != buffer.end()) {
  6441. auto & fragment = (*it);
  6442. // if a fragment is text ( not yet processed )
  6443. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  6444. auto * raw_text = &(fragment.raw_text);
  6445. auto raw_text_base_offset = fragment.offset;
  6446. auto raw_text_base_length = fragment.length;
  6447. // loop over the text
  6448. while (true) {
  6449. // find the first occurrence of a given special token in this fragment
  6450. // passing offset argument only limit the "search area" but match coordinates
  6451. // are still relative to the source full raw_text
  6452. auto match = raw_text->find(special_token, raw_text_base_offset);
  6453. // no occurrences found, stop processing this fragment for a given special token
  6454. if (match == std::string::npos) break;
  6455. // check if match is within bounds of offset <-> length
  6456. if (match + special_token.length() > raw_text_base_offset + raw_text_base_length) break;
  6457. #ifdef PRETOKENIZERDEBUG
  6458. 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());
  6459. #endif
  6460. auto source = std::distance(buffer.begin(), it);
  6461. // if match is further than base offset
  6462. // then we have some text to the left of it
  6463. if (match > raw_text_base_offset) {
  6464. // left
  6465. const int64_t left_reminder_offset = raw_text_base_offset + 0;
  6466. const int64_t left_reminder_length = match - raw_text_base_offset;
  6467. buffer.emplace_after(it, (*raw_text), left_reminder_offset, left_reminder_length);
  6468. #ifdef PRETOKENIZERDEBUG
  6469. 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());
  6470. #endif
  6471. it++;
  6472. }
  6473. // special token
  6474. buffer.emplace_after(it, special_id);
  6475. it++;
  6476. // right
  6477. if (match + special_token.length() < raw_text_base_offset + raw_text_base_length) {
  6478. const int64_t right_reminder_offset = match + special_token.length();
  6479. const int64_t right_reminder_length = raw_text_base_length - ((match - raw_text_base_offset) + special_token.length());
  6480. buffer.emplace_after(it, (*raw_text), right_reminder_offset, right_reminder_length);
  6481. #ifdef PRETOKENIZERDEBUG
  6482. 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());
  6483. #endif
  6484. it++;
  6485. if (source == 0) {
  6486. buffer.erase_after(buffer.before_begin());
  6487. } else {
  6488. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  6489. }
  6490. // repeat for the right side
  6491. raw_text_base_offset = right_reminder_offset;
  6492. raw_text_base_length = right_reminder_length;
  6493. #ifdef PRETOKENIZERDEBUG
  6494. 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());
  6495. #endif
  6496. } else {
  6497. if (source == 0) {
  6498. buffer.erase_after(buffer.before_begin());
  6499. } else {
  6500. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  6501. }
  6502. break;
  6503. }
  6504. }
  6505. }
  6506. it++;
  6507. }
  6508. }
  6509. }
  6510. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special) {
  6511. std::vector<llama_vocab::id> output;
  6512. // OG tokenizer behavior:
  6513. //
  6514. // tokenizer.encode('', add_bos=True) returns [1]
  6515. // tokenizer.encode('', add_bos=False) returns []
  6516. if (bos && vocab.special_bos_id != -1) {
  6517. output.push_back(vocab.special_bos_id);
  6518. }
  6519. if (raw_text.empty()) {
  6520. return output;
  6521. }
  6522. std::forward_list<fragment_buffer_variant> fragment_buffer;
  6523. fragment_buffer.emplace_front( raw_text, 0, raw_text.length() );
  6524. if (special) tokenizer_st_partition( vocab, fragment_buffer );
  6525. switch (vocab.type) {
  6526. case LLAMA_VOCAB_TYPE_SPM:
  6527. {
  6528. for (const auto & fragment: fragment_buffer)
  6529. {
  6530. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT)
  6531. {
  6532. // without adding this leading whitespace, we do not get the same results as the original tokenizer
  6533. // TODO: It's likely possible to get rid of this string copy entirely
  6534. // by modifying llm_tokenizer_x to operate with string offsets like pre-tokenizer
  6535. // and passing 'add space prefix' as bool argument
  6536. //
  6537. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  6538. if (&fragment == &fragment_buffer.front()) {
  6539. if (vocab.add_space_prefix) {
  6540. raw_text = " " + raw_text; // prefix with space if the first token is not special
  6541. }
  6542. }
  6543. #ifdef PRETOKENIZERDEBUG
  6544. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  6545. #endif
  6546. llm_tokenizer_spm tokenizer(vocab);
  6547. llama_escape_whitespace(raw_text);
  6548. tokenizer.tokenize(raw_text, output);
  6549. }
  6550. else // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  6551. {
  6552. output.push_back(fragment.token);
  6553. }
  6554. }
  6555. } break;
  6556. case LLAMA_VOCAB_TYPE_BPE:
  6557. {
  6558. for (const auto & fragment: fragment_buffer)
  6559. {
  6560. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT)
  6561. {
  6562. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  6563. #ifdef PRETOKENIZERDEBUG
  6564. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  6565. #endif
  6566. llm_tokenizer_bpe tokenizer(vocab);
  6567. tokenizer.tokenize(raw_text, output);
  6568. }
  6569. else // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  6570. {
  6571. output.push_back(fragment.token);
  6572. }
  6573. }
  6574. } break;
  6575. }
  6576. return output;
  6577. }
  6578. //
  6579. // grammar - internal
  6580. //
  6581. struct llama_partial_utf8 {
  6582. uint32_t value; // bit value so far (unshifted)
  6583. int n_remain; // num bytes remaining; -1 indicates invalid sequence
  6584. };
  6585. struct llama_grammar {
  6586. const std::vector<std::vector<llama_grammar_element>> rules;
  6587. std::vector<std::vector<const llama_grammar_element *>> stacks;
  6588. // buffer for partially generated UTF-8 sequence from accepted tokens
  6589. llama_partial_utf8 partial_utf8;
  6590. };
  6591. struct llama_grammar_candidate {
  6592. size_t index;
  6593. const uint32_t * code_points;
  6594. llama_partial_utf8 partial_utf8;
  6595. };
  6596. // Decodes a UTF-8 string which may end in an incomplete sequence. Adds a terminating 0 for use as
  6597. // pointer. If an invalid sequence is encountered, returns `llama_partial_utf8.n_remain == -1`.
  6598. static std::pair<std::vector<uint32_t>, llama_partial_utf8> decode_utf8(
  6599. const std::string & src,
  6600. llama_partial_utf8 partial_start) {
  6601. static const int lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 3, 4 };
  6602. const char * pos = src.c_str();
  6603. std::vector<uint32_t> code_points;
  6604. // common english strings have the same number of codepoints and bytes. `+ 1` for the terminating 0.
  6605. code_points.reserve(src.size() + 1);
  6606. uint32_t value = partial_start.value;
  6607. int n_remain = partial_start.n_remain;
  6608. // continue previous decode, if applicable
  6609. while (*pos != 0 && n_remain > 0) {
  6610. uint8_t next_byte = static_cast<uint8_t>(*pos);
  6611. if ((next_byte >> 6) != 2) {
  6612. // invalid sequence, abort
  6613. code_points.push_back(0);
  6614. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, -1 });
  6615. }
  6616. value = (value << 6) + (next_byte & 0x3F);
  6617. ++pos;
  6618. --n_remain;
  6619. }
  6620. if (partial_start.n_remain > 0 && n_remain == 0) {
  6621. code_points.push_back(value);
  6622. }
  6623. // decode any subsequent utf-8 sequences, which may end in an incomplete one
  6624. while (*pos != 0) {
  6625. uint8_t first_byte = static_cast<uint8_t>(*pos);
  6626. uint8_t highbits = first_byte >> 4;
  6627. n_remain = lookup[highbits] - 1;
  6628. if (n_remain < 0) {
  6629. // invalid sequence, abort
  6630. code_points.clear();
  6631. code_points.push_back(0);
  6632. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, n_remain });
  6633. }
  6634. uint8_t mask = (1 << (7 - n_remain)) - 1;
  6635. value = first_byte & mask;
  6636. ++pos;
  6637. while (*pos != 0 && n_remain > 0) {
  6638. value = (value << 6) + (static_cast<uint8_t>(*pos) & 0x3F);
  6639. ++pos;
  6640. --n_remain;
  6641. }
  6642. if (n_remain == 0) {
  6643. code_points.push_back(value);
  6644. }
  6645. }
  6646. code_points.push_back(0);
  6647. return std::make_pair(std::move(code_points), llama_partial_utf8{ value, n_remain });
  6648. }
  6649. // returns true iff pos points to the end of one of the definitions of a rule
  6650. static bool llama_grammar_is_end_of_sequence(const llama_grammar_element * pos) {
  6651. switch (pos->type) {
  6652. case LLAMA_GRETYPE_END: return true; // NOLINT
  6653. case LLAMA_GRETYPE_ALT: return true; // NOLINT
  6654. default: return false;
  6655. }
  6656. }
  6657. // returns true iff chr satisfies the char range at pos (regular or inverse range)
  6658. // asserts that pos is pointing to a char range element
  6659. static std::pair<bool, const llama_grammar_element *> llama_grammar_match_char(
  6660. const llama_grammar_element * pos,
  6661. const uint32_t chr) {
  6662. bool found = false;
  6663. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  6664. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT); // NOLINT
  6665. do {
  6666. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  6667. // inclusive range, e.g. [a-z]
  6668. found = found || (pos->value <= chr && chr <= pos[1].value);
  6669. pos += 2;
  6670. } else {
  6671. // exact char match, e.g. [a] or "a"
  6672. found = found || pos->value == chr;
  6673. pos += 1;
  6674. }
  6675. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  6676. return std::make_pair(found == is_positive_char, pos);
  6677. }
  6678. // returns true iff some continuation of the given partial UTF-8 sequence could satisfy the char
  6679. // range at pos (regular or inverse range)
  6680. // asserts that pos is pointing to a char range element
  6681. static bool llama_grammar_match_partial_char(
  6682. const llama_grammar_element * pos,
  6683. const llama_partial_utf8 partial_utf8) {
  6684. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  6685. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT);
  6686. uint32_t partial_value = partial_utf8.value;
  6687. int n_remain = partial_utf8.n_remain;
  6688. // invalid sequence or 7-bit char split across 2 bytes (overlong)
  6689. if (n_remain < 0 || (n_remain == 1 && partial_value < 2)) {
  6690. return false;
  6691. }
  6692. // range of possible code points this partial UTF-8 sequence could complete to
  6693. uint32_t low = partial_value << (n_remain * 6);
  6694. uint32_t high = low | ((1 << (n_remain * 6)) - 1);
  6695. if (low == 0) {
  6696. if (n_remain == 2) {
  6697. low = 1 << 11;
  6698. } else if (n_remain == 3) {
  6699. low = 1 << 16;
  6700. }
  6701. }
  6702. do {
  6703. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  6704. // inclusive range, e.g. [a-z]
  6705. if (pos->value <= high && low <= pos[1].value) {
  6706. return is_positive_char;
  6707. }
  6708. pos += 2;
  6709. } else {
  6710. // exact char match, e.g. [a] or "a"
  6711. if (low <= pos->value && pos->value <= high) {
  6712. return is_positive_char;
  6713. }
  6714. pos += 1;
  6715. }
  6716. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  6717. return !is_positive_char;
  6718. }
  6719. // transforms a grammar pushdown stack into N possible stacks, all ending
  6720. // at a character range (terminal element)
  6721. static void llama_grammar_advance_stack(
  6722. const std::vector<std::vector<llama_grammar_element>> & rules,
  6723. const std::vector<const llama_grammar_element *> & stack,
  6724. std::vector<std::vector<const llama_grammar_element *>> & new_stacks) {
  6725. if (stack.empty()) {
  6726. new_stacks.emplace_back(stack);
  6727. return;
  6728. }
  6729. const llama_grammar_element * pos = stack.back();
  6730. switch (pos->type) {
  6731. case LLAMA_GRETYPE_RULE_REF: {
  6732. const size_t rule_id = static_cast<size_t>(pos->value);
  6733. const llama_grammar_element * subpos = rules[rule_id].data();
  6734. do {
  6735. // init new stack without the top (pos)
  6736. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  6737. if (!llama_grammar_is_end_of_sequence(pos + 1)) {
  6738. // if this rule ref is followed by another element, add that to stack
  6739. new_stack.push_back(pos + 1);
  6740. }
  6741. if (!llama_grammar_is_end_of_sequence(subpos)) {
  6742. // if alternate is nonempty, add to stack
  6743. new_stack.push_back(subpos);
  6744. }
  6745. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  6746. while (!llama_grammar_is_end_of_sequence(subpos)) {
  6747. // scan to end of alternate def
  6748. subpos++;
  6749. }
  6750. if (subpos->type == LLAMA_GRETYPE_ALT) {
  6751. // there's another alternate def of this rule to process
  6752. subpos++;
  6753. } else {
  6754. break;
  6755. }
  6756. } while (true);
  6757. break;
  6758. }
  6759. case LLAMA_GRETYPE_CHAR:
  6760. case LLAMA_GRETYPE_CHAR_NOT:
  6761. new_stacks.emplace_back(stack);
  6762. break;
  6763. default:
  6764. // end of alternate (LLAMA_GRETYPE_END, LLAMA_GRETYPE_ALT) or middle of char range
  6765. // (LLAMA_GRETYPE_CHAR_ALT, LLAMA_GRETYPE_CHAR_RNG_UPPER); stack should never be left on
  6766. // those
  6767. GGML_ASSERT(false);
  6768. }
  6769. }
  6770. // takes a set of possible pushdown stacks on a grammar, which are required to
  6771. // be positioned at a character range (see `llama_grammar_advance_stack`), and
  6772. // produces the N possible stacks if the given char is accepted at those
  6773. // positions
  6774. static std::vector<std::vector<const llama_grammar_element *>> llama_grammar_accept(
  6775. const std::vector<std::vector<llama_grammar_element>> & rules,
  6776. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  6777. const uint32_t chr) {
  6778. std::vector<std::vector<const llama_grammar_element *>> new_stacks;
  6779. for (const auto & stack : stacks) {
  6780. if (stack.empty()) {
  6781. continue;
  6782. }
  6783. auto match = llama_grammar_match_char(stack.back(), chr);
  6784. if (match.first) {
  6785. const llama_grammar_element * pos = match.second;
  6786. // update top of stack to next element, if any
  6787. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  6788. if (!llama_grammar_is_end_of_sequence(pos)) {
  6789. new_stack.push_back(pos);
  6790. }
  6791. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  6792. }
  6793. }
  6794. return new_stacks;
  6795. }
  6796. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  6797. const std::vector<std::vector<llama_grammar_element>> & rules,
  6798. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  6799. const std::vector<llama_grammar_candidate> & candidates);
  6800. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates_for_stack(
  6801. const std::vector<std::vector<llama_grammar_element>> & rules,
  6802. const std::vector<const llama_grammar_element *> & stack,
  6803. const std::vector<llama_grammar_candidate> & candidates) {
  6804. std::vector<llama_grammar_candidate> rejects;
  6805. if (stack.empty()) {
  6806. for (const auto & tok : candidates) {
  6807. if (*tok.code_points != 0 || tok.partial_utf8.n_remain != 0) {
  6808. rejects.push_back(tok);
  6809. }
  6810. }
  6811. return rejects;
  6812. }
  6813. const llama_grammar_element * stack_pos = stack.back();
  6814. std::vector<llama_grammar_candidate> next_candidates;
  6815. for (const auto & tok : candidates) {
  6816. if (*tok.code_points == 0) {
  6817. // reached end of full codepoints in token, reject iff it ended in a partial sequence
  6818. // that cannot satisfy this position in grammar
  6819. if (tok.partial_utf8.n_remain != 0 &&
  6820. !llama_grammar_match_partial_char(stack_pos, tok.partial_utf8)) {
  6821. rejects.push_back(tok);
  6822. }
  6823. } else if (llama_grammar_match_char(stack_pos, *tok.code_points).first) {
  6824. next_candidates.push_back({ tok.index, tok.code_points + 1, tok.partial_utf8 });
  6825. } else {
  6826. rejects.push_back(tok);
  6827. }
  6828. }
  6829. const auto * stack_pos_after = llama_grammar_match_char(stack_pos, 0).second;
  6830. // update top of stack to next element, if any
  6831. std::vector<const llama_grammar_element *> stack_after(stack.begin(), stack.end() - 1);
  6832. if (!llama_grammar_is_end_of_sequence(stack_pos_after)) {
  6833. stack_after.push_back(stack_pos_after);
  6834. }
  6835. std::vector<std::vector<const llama_grammar_element *>> next_stacks;
  6836. llama_grammar_advance_stack(rules, stack_after, next_stacks);
  6837. auto next_rejects = llama_grammar_reject_candidates(rules, next_stacks, next_candidates);
  6838. for (const auto & tok : next_rejects) {
  6839. rejects.push_back({ tok.index, tok.code_points - 1, tok.partial_utf8 });
  6840. }
  6841. return rejects;
  6842. }
  6843. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  6844. const std::vector<std::vector<llama_grammar_element>> & rules,
  6845. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  6846. const std::vector<llama_grammar_candidate> & candidates) {
  6847. GGML_ASSERT(!stacks.empty()); // REVIEW
  6848. if (candidates.empty()) {
  6849. return std::vector<llama_grammar_candidate>();
  6850. }
  6851. auto rejects = llama_grammar_reject_candidates_for_stack(rules, stacks.front(), candidates);
  6852. for (size_t i = 1, size = stacks.size(); i < size; ++i) {
  6853. rejects = llama_grammar_reject_candidates_for_stack(rules, stacks[i], rejects);
  6854. }
  6855. return rejects;
  6856. }
  6857. //
  6858. // grammar - external
  6859. //
  6860. struct llama_grammar * llama_grammar_init(
  6861. const llama_grammar_element ** rules,
  6862. size_t n_rules,
  6863. size_t start_rule_index) {
  6864. const llama_grammar_element * pos;
  6865. // copy rule definitions into vectors
  6866. std::vector<std::vector<llama_grammar_element>> vec_rules(n_rules);
  6867. for (size_t i = 0; i < n_rules; i++) {
  6868. for (pos = rules[i]; pos->type != LLAMA_GRETYPE_END; pos++) {
  6869. vec_rules[i].push_back(*pos);
  6870. }
  6871. vec_rules[i].push_back({LLAMA_GRETYPE_END, 0});
  6872. }
  6873. // loop over alternates of start rule to build initial stacks
  6874. std::vector<std::vector<const llama_grammar_element *>> stacks;
  6875. pos = rules[start_rule_index];
  6876. do {
  6877. std::vector<const llama_grammar_element *> stack;
  6878. if (!llama_grammar_is_end_of_sequence(pos)) {
  6879. // if alternate is nonempty, add to stack
  6880. stack.push_back(pos);
  6881. }
  6882. llama_grammar_advance_stack(vec_rules, stack, stacks);
  6883. while (!llama_grammar_is_end_of_sequence(pos)) {
  6884. // scan to end of alternate def
  6885. pos++;
  6886. }
  6887. if (pos->type == LLAMA_GRETYPE_ALT) {
  6888. // there's another alternate def of this rule to process
  6889. pos++;
  6890. } else {
  6891. break;
  6892. }
  6893. } while (true);
  6894. return new llama_grammar{ std::move(vec_rules), std::move(stacks), {} };
  6895. }
  6896. void llama_grammar_free(struct llama_grammar * grammar) {
  6897. delete grammar;
  6898. }
  6899. struct llama_grammar * llama_grammar_copy(const struct llama_grammar * grammar) {
  6900. llama_grammar * result = new llama_grammar{ grammar->rules, grammar->stacks, grammar->partial_utf8 };
  6901. // redirect elements in stacks to point to new rules
  6902. for (size_t is = 0; is < result->stacks.size(); is++) {
  6903. for (size_t ie = 0; ie < result->stacks[is].size(); ie++) {
  6904. for (size_t ir0 = 0; ir0 < grammar->rules.size(); ir0++) {
  6905. for (size_t ir1 = 0; ir1 < grammar->rules[ir0].size(); ir1++) {
  6906. if (grammar->stacks[is][ie] == &grammar->rules[ir0][ir1]) {
  6907. result->stacks[is][ie] = &result->rules[ir0][ir1];
  6908. }
  6909. }
  6910. }
  6911. }
  6912. }
  6913. return result;
  6914. }
  6915. //
  6916. // sampling
  6917. //
  6918. void llama_set_rng_seed(struct llama_context * ctx, uint32_t seed) {
  6919. if (seed == LLAMA_DEFAULT_SEED) {
  6920. seed = time(NULL);
  6921. }
  6922. ctx->rng.seed(seed);
  6923. }
  6924. void llama_sample_softmax(struct llama_context * ctx, llama_token_data_array * candidates) {
  6925. GGML_ASSERT(candidates->size > 0);
  6926. const int64_t t_start_sample_us = ggml_time_us();
  6927. // Sort the logits in descending order
  6928. if (!candidates->sorted) {
  6929. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  6930. return a.logit > b.logit;
  6931. });
  6932. candidates->sorted = true;
  6933. }
  6934. float max_l = candidates->data[0].logit;
  6935. float cum_sum = 0.0f;
  6936. for (size_t i = 0; i < candidates->size; ++i) {
  6937. float p = expf(candidates->data[i].logit - max_l);
  6938. candidates->data[i].p = p;
  6939. cum_sum += p;
  6940. }
  6941. for (size_t i = 0; i < candidates->size; ++i) {
  6942. candidates->data[i].p /= cum_sum;
  6943. }
  6944. if (ctx) {
  6945. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6946. }
  6947. }
  6948. void llama_sample_top_k(struct llama_context * ctx, llama_token_data_array * candidates, int32_t k, size_t min_keep) {
  6949. // TODO: move bucket sort to separate function so that top_p/tail_free/typical/softmax first is equally fast
  6950. // if (k >= (int32_t)candidates->size) {
  6951. // return;
  6952. // }
  6953. const int64_t t_start_sample_us = ggml_time_us();
  6954. k = std::max(k, (int) min_keep);
  6955. k = std::min(k, (int) candidates->size);
  6956. // Sort scores in descending order
  6957. if (!candidates->sorted) {
  6958. auto comp = [](const llama_token_data & a, const llama_token_data & b) {
  6959. return a.logit > b.logit;
  6960. };
  6961. if (k <= 128) {
  6962. std::partial_sort(candidates->data, candidates->data + k, candidates->data + candidates->size, comp);
  6963. } else {
  6964. constexpr int nbuckets = 128;
  6965. constexpr float bucket_low = -10.0f;
  6966. constexpr float bucket_high = 10.0f;
  6967. constexpr float bucket_scale = nbuckets/(bucket_high - bucket_low);
  6968. constexpr float bucker_inter = -bucket_low * bucket_scale;
  6969. std::vector<int> bucket_idx(candidates->size);
  6970. std::vector<int> histo(nbuckets, 0);
  6971. for (int i = 0; i < (int)candidates->size; ++i) {
  6972. const float val = candidates->data[i].logit;
  6973. int ib = int(bucket_scale * val + bucker_inter); //nbuckets * (val - bucket_low) / (bucket_high - bucket_low);
  6974. ib = std::max(0, std::min(nbuckets-1, ib));
  6975. bucket_idx[i] = ib;
  6976. ++histo[ib];
  6977. }
  6978. int nhave = 0;
  6979. int ib = nbuckets - 1;
  6980. for ( ; ib >= 0; --ib) {
  6981. nhave += histo[ib];
  6982. if (nhave >= k) break;
  6983. }
  6984. std::vector<llama_token_data> tmp_tokens(nhave);
  6985. auto ptr = tmp_tokens.data();
  6986. std::vector<llama_token_data*> bucket_ptrs;
  6987. bucket_ptrs.reserve(nbuckets - ib);
  6988. for (int j = nbuckets - 1; j >= ib; --j) {
  6989. bucket_ptrs.push_back(ptr);
  6990. ptr += histo[j];
  6991. }
  6992. for (int i = 0; i < (int)candidates->size; ++i) {
  6993. int j = bucket_idx[i];
  6994. if (j >= ib) {
  6995. *bucket_ptrs[nbuckets-1-j]++ = candidates->data[i];
  6996. }
  6997. }
  6998. ptr = tmp_tokens.data();
  6999. int ndone = 0;
  7000. for (int j = nbuckets-1; j > ib; --j) {
  7001. std::sort(ptr, ptr + histo[j], comp);
  7002. ptr += histo[j];
  7003. ndone += histo[j];
  7004. }
  7005. std::partial_sort(ptr, ptr + k - ndone, ptr + histo[ib], comp);
  7006. std::memcpy(candidates->data, tmp_tokens.data(), k*sizeof(llama_token_data));
  7007. }
  7008. candidates->sorted = true;
  7009. }
  7010. candidates->size = k;
  7011. if (ctx) {
  7012. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7013. }
  7014. }
  7015. void llama_sample_top_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  7016. if (p >= 1.0f) {
  7017. return;
  7018. }
  7019. llama_sample_softmax(ctx, candidates);
  7020. const int64_t t_start_sample_us = ggml_time_us();
  7021. // Compute the cumulative probabilities
  7022. float cum_sum = 0.0f;
  7023. size_t last_idx = candidates->size;
  7024. for (size_t i = 0; i < candidates->size; ++i) {
  7025. cum_sum += candidates->data[i].p;
  7026. // Check if the running sum is at least p or if we have kept at least min_keep tokens
  7027. // we set the last index to i+1 to indicate that the current iterate should be included in the set
  7028. if (cum_sum >= p && i + 1 >= min_keep) {
  7029. last_idx = i + 1;
  7030. break;
  7031. }
  7032. }
  7033. // Resize the output vector to keep only the top-p tokens
  7034. candidates->size = last_idx;
  7035. if (ctx) {
  7036. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7037. }
  7038. }
  7039. void llama_sample_min_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  7040. if (p <= 0.0f || !candidates->size) {
  7041. return;
  7042. }
  7043. const int64_t t_start_sample_us = ggml_time_us();
  7044. bool min_p_applied = false;
  7045. // if the candidates aren't sorted, try the unsorted implementation first
  7046. if (!candidates->sorted) {
  7047. std::vector<llama_token_data> filtered_tokens;
  7048. float max_logit = -FLT_MAX;
  7049. for (size_t i = 0; i < candidates->size; ++i) {
  7050. max_logit = std::max(max_logit, candidates->data[i].logit);
  7051. }
  7052. const float min_logit = max_logit + logf(p); // min logit for p_i >= p * p_max
  7053. for (size_t i = 0; i < candidates->size; ++i) {
  7054. if (candidates->data[i].logit >= min_logit) {
  7055. filtered_tokens.push_back(candidates->data[i]);
  7056. }
  7057. }
  7058. // if we have enough values the operation was a success
  7059. if (filtered_tokens.size() >= min_keep) {
  7060. memcpy(candidates->data, filtered_tokens.data(), filtered_tokens.size()*sizeof(llama_token_data));
  7061. candidates->size = filtered_tokens.size();
  7062. min_p_applied = true;
  7063. }
  7064. }
  7065. // if the candidates are sorted or the unsorted implementation failed, use this implementation
  7066. if (!min_p_applied) {
  7067. // Sort the logits in descending order
  7068. if (!candidates->sorted) {
  7069. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  7070. return a.logit > b.logit;
  7071. });
  7072. candidates->sorted = true;
  7073. }
  7074. const float min_logit = candidates->data[0].logit + logf(p); // min logit for p_i >= p * p_max
  7075. size_t i = 1; // first token always matches
  7076. for (; i < candidates->size; ++i) {
  7077. if (candidates->data[i].logit < min_logit && i >= min_keep) {
  7078. break; // prob too small
  7079. }
  7080. }
  7081. // Resize the output vector to keep only the matching tokens
  7082. candidates->size = i;
  7083. }
  7084. if (ctx) {
  7085. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7086. }
  7087. }
  7088. void llama_sample_tail_free(struct llama_context * ctx, llama_token_data_array * candidates, float z, size_t min_keep) {
  7089. if (z >= 1.0f || candidates->size <= 2) {
  7090. return;
  7091. }
  7092. llama_sample_softmax(nullptr, candidates);
  7093. const int64_t t_start_sample_us = ggml_time_us();
  7094. // Compute the first and second derivatives
  7095. std::vector<float> first_derivatives(candidates->size - 1);
  7096. std::vector<float> second_derivatives(candidates->size - 2);
  7097. for (size_t i = 0; i < first_derivatives.size(); ++i) {
  7098. first_derivatives[i] = candidates->data[i].p - candidates->data[i + 1].p;
  7099. }
  7100. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  7101. second_derivatives[i] = first_derivatives[i] - first_derivatives[i + 1];
  7102. }
  7103. // Calculate absolute value of second derivatives
  7104. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  7105. second_derivatives[i] = std::abs(second_derivatives[i]);
  7106. }
  7107. // Normalize the second derivatives
  7108. {
  7109. const float second_derivatives_sum = std::accumulate(second_derivatives.begin(), second_derivatives.end(), 0.0f);
  7110. if (second_derivatives_sum > 1e-6f) {
  7111. for (float & value : second_derivatives) {
  7112. value /= second_derivatives_sum;
  7113. }
  7114. } else {
  7115. for (float & value : second_derivatives) {
  7116. value = 1.0f / second_derivatives.size();
  7117. }
  7118. }
  7119. }
  7120. float cum_sum = 0.0f;
  7121. size_t last_idx = candidates->size;
  7122. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  7123. cum_sum += second_derivatives[i];
  7124. // Check if the running sum is greater than z or if we have kept at least min_keep tokens
  7125. if (cum_sum > z && i >= min_keep) {
  7126. last_idx = i;
  7127. break;
  7128. }
  7129. }
  7130. // Resize the output vector to keep only the tokens above the tail location
  7131. candidates->size = last_idx;
  7132. if (ctx) {
  7133. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7134. }
  7135. }
  7136. void llama_sample_typical(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  7137. // Reference implementation:
  7138. // https://github.com/huggingface/transformers/compare/main...cimeister:typical-sampling:typical-pr
  7139. if (p >= 1.0f) {
  7140. return;
  7141. }
  7142. // Compute the softmax of logits and calculate entropy
  7143. llama_sample_softmax(nullptr, candidates);
  7144. const int64_t t_start_sample_us = ggml_time_us();
  7145. float entropy = 0.0f;
  7146. for (size_t i = 0; i < candidates->size; ++i) {
  7147. entropy += -candidates->data[i].p * logf(candidates->data[i].p);
  7148. }
  7149. // Compute the absolute difference between negative log probability and entropy for each candidate
  7150. std::vector<float> shifted_scores;
  7151. for (size_t i = 0; i < candidates->size; ++i) {
  7152. float shifted_score = fabsf(-logf(candidates->data[i].p) - entropy);
  7153. shifted_scores.push_back(shifted_score);
  7154. }
  7155. // Sort tokens based on the shifted_scores and their corresponding indices
  7156. std::vector<size_t> indices(candidates->size);
  7157. std::iota(indices.begin(), indices.end(), 0);
  7158. std::sort(indices.begin(), indices.end(), [&](size_t a, size_t b) {
  7159. return shifted_scores[a] < shifted_scores[b];
  7160. });
  7161. // Compute the cumulative probabilities
  7162. float cum_sum = 0.0f;
  7163. size_t last_idx = indices.size();
  7164. for (size_t i = 0; i < indices.size(); ++i) {
  7165. size_t idx = indices[i];
  7166. cum_sum += candidates->data[idx].p;
  7167. // Check if the running sum is greater than typical or if we have kept at least min_keep tokens
  7168. if (cum_sum > p && i >= min_keep - 1) {
  7169. last_idx = i + 1;
  7170. break;
  7171. }
  7172. }
  7173. // Resize the output vector to keep only the locally typical tokens
  7174. std::vector<llama_token_data> new_candidates;
  7175. for (size_t i = 0; i < last_idx; ++i) {
  7176. size_t idx = indices[i];
  7177. new_candidates.push_back(candidates->data[idx]);
  7178. }
  7179. // Replace the data in candidates with the new_candidates data
  7180. std::copy(new_candidates.begin(), new_candidates.end(), candidates->data);
  7181. candidates->size = new_candidates.size();
  7182. candidates->sorted = false;
  7183. if (ctx) {
  7184. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7185. }
  7186. }
  7187. void llama_sample_entropy(struct llama_context * ctx, llama_token_data_array * candidates_p, float min_temp, float max_temp, float exponent_val) {
  7188. const int64_t t_start_sample_us = ggml_time_us();
  7189. // no need to do anything if there is only one (or zero) candidates
  7190. if(candidates_p->size <= 1) {
  7191. return;
  7192. }
  7193. // Calculate maximum possible entropy
  7194. float max_entropy = -logf(1.0f / candidates_p->size);
  7195. llama_sample_softmax(nullptr, candidates_p);
  7196. // Calculate entropy of the softmax probabilities
  7197. float entropy = 0.0f;
  7198. for (size_t i = 0; i < candidates_p->size; ++i) {
  7199. float prob = candidates_p->data[i].p;
  7200. if (prob > 0.0f) { // Ensure no log(0)
  7201. entropy -= prob * logf(prob);
  7202. }
  7203. }
  7204. // Normalize the entropy (max_entropy cannot be 0 here because we checked candidates_p->size != 1 above)
  7205. float normalized_entropy = entropy / max_entropy;
  7206. // Map the normalized entropy to the desired temperature range using the power function
  7207. float dyn_temp = min_temp + (max_temp - min_temp) * powf(normalized_entropy, exponent_val);
  7208. #ifdef DEBUG
  7209. LLAMA_LOG_INFO("Your text maxtemp value is: %f\n", max_temp);
  7210. LLAMA_LOG_INFO("Entropy: %f\n", entropy);
  7211. LLAMA_LOG_INFO("Max Possible Entropy: %f\n", max_entropy);
  7212. LLAMA_LOG_INFO("Normalized Entropy: %f\n", normalized_entropy);
  7213. LLAMA_LOG_INFO("Exponent: %f\n", exponent_val);
  7214. LLAMA_LOG_INFO("Dynamic Temperature (dyn_temp): %f\n", dyn_temp);
  7215. #endif
  7216. // Apply the dynamically calculated temperature scaling
  7217. for (size_t i = 0; i < candidates_p->size; ++i) {
  7218. candidates_p->data[i].logit /= dyn_temp;
  7219. }
  7220. // Re-compute softmax probabilities after scaling logits with dynamic temperature
  7221. double max_l_double = candidates_p->data[0].logit;
  7222. double cum_sum_double = 0.0;
  7223. for (size_t i = 0; i < candidates_p->size; ++i) {
  7224. double p = exp(candidates_p->data[i].logit - max_l_double);
  7225. candidates_p->data[i].p = p; // Store the scaled probability
  7226. cum_sum_double += p;
  7227. }
  7228. for (size_t i = 0; i < candidates_p->size; ++i) {
  7229. candidates_p->data[i].p /= cum_sum_double; // Re-normalize the probabilities
  7230. }
  7231. #ifdef DEBUG
  7232. // Print the updated top 25 probabilities after temperature scaling
  7233. LLAMA_LOG_INFO("\nUpdated Top 25 Probabilities After Dynamic Temperature Scaling (in percentages):\n");
  7234. for (size_t i = 0; i < 25 && i < candidates_p->size; ++i) {
  7235. LLAMA_LOG_INFO("Token %zu: %f%%\n", i + 1, candidates_p->data[i].p * 100.0f);
  7236. }
  7237. #endif
  7238. if (ctx) {
  7239. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7240. }
  7241. }
  7242. void llama_sample_temp(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  7243. const int64_t t_start_sample_us = ggml_time_us();
  7244. for (size_t i = 0; i < candidates_p->size; ++i) {
  7245. candidates_p->data[i].logit /= temp;
  7246. }
  7247. if (ctx) {
  7248. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7249. }
  7250. }
  7251. void llama_sample_temperature(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  7252. llama_sample_temp(ctx, candidates_p, temp);
  7253. }
  7254. void llama_sample_repetition_penalties(
  7255. struct llama_context * ctx,
  7256. llama_token_data_array * candidates,
  7257. const llama_token * last_tokens,
  7258. size_t penalty_last_n,
  7259. float penalty_repeat,
  7260. float penalty_freq,
  7261. float penalty_present) {
  7262. if (penalty_last_n == 0 || (penalty_repeat == 1.0f && penalty_freq == 0.0f && penalty_present == 0.0f)) {
  7263. return;
  7264. }
  7265. const int64_t t_start_sample_us = ggml_time_us();
  7266. // Create a frequency map to count occurrences of each token in last_tokens
  7267. std::unordered_map<llama_token, int> token_count;
  7268. for (size_t i = 0; i < penalty_last_n; ++i) {
  7269. token_count[last_tokens[i]]++;
  7270. }
  7271. // Apply frequency and presence penalties to the candidates
  7272. for (size_t i = 0; i < candidates->size; ++i) {
  7273. const auto token_iter = token_count.find(candidates->data[i].id);
  7274. if (token_iter == token_count.end()) {
  7275. continue;
  7276. }
  7277. const int count = token_iter->second;
  7278. // 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.
  7279. // This is common fix for this problem, which is to multiply by the penalty instead of dividing.
  7280. if (candidates->data[i].logit <= 0) {
  7281. candidates->data[i].logit *= penalty_repeat;
  7282. } else {
  7283. candidates->data[i].logit /= penalty_repeat;
  7284. }
  7285. candidates->data[i].logit -= float(count) * penalty_freq + float(count > 0) * penalty_present;
  7286. }
  7287. candidates->sorted = false;
  7288. if (ctx) {
  7289. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7290. }
  7291. }
  7292. void llama_sample_grammar(struct llama_context * ctx, llama_token_data_array * candidates, const struct llama_grammar * grammar) {
  7293. GGML_ASSERT(ctx);
  7294. const int64_t t_start_sample_us = ggml_time_us();
  7295. bool allow_eos = false;
  7296. for (const auto & stack : grammar->stacks) {
  7297. if (stack.empty()) {
  7298. allow_eos = true;
  7299. break;
  7300. }
  7301. }
  7302. const llama_token eos = llama_token_eos(&ctx->model);
  7303. std::vector<std::pair<std::vector<uint32_t>, llama_partial_utf8>> candidates_decoded;
  7304. candidates_decoded.reserve(candidates->size);
  7305. std::vector<llama_grammar_candidate> candidates_grammar;
  7306. candidates_grammar.reserve(candidates->size);
  7307. for (size_t i = 0; i < candidates->size; ++i) {
  7308. const llama_token id = candidates->data[i].id;
  7309. const std::string piece = llama_token_to_piece(ctx, id);
  7310. if (id == eos) {
  7311. if (!allow_eos) {
  7312. candidates->data[i].logit = -INFINITY;
  7313. }
  7314. } else if (piece.empty() || piece[0] == 0) {
  7315. candidates->data[i].logit = -INFINITY;
  7316. } else {
  7317. candidates_decoded.push_back(decode_utf8(piece, grammar->partial_utf8));
  7318. candidates_grammar.push_back({ i, candidates_decoded.back().first.data(), candidates_decoded.back().second });
  7319. }
  7320. }
  7321. const auto rejects = llama_grammar_reject_candidates(grammar->rules, grammar->stacks, candidates_grammar);
  7322. for (const auto & reject : rejects) {
  7323. candidates->data[reject.index].logit = -INFINITY;
  7324. }
  7325. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7326. }
  7327. static void llama_log_softmax(float * array, size_t size) {
  7328. float max_l = *std::max_element(array, array + size);
  7329. float sum = 0.f;
  7330. for (size_t i = 0; i < size; ++i) {
  7331. float p = expf(array[i] - max_l);
  7332. sum += p;
  7333. array[i] = p;
  7334. }
  7335. for (size_t i = 0; i < size; ++i) {
  7336. array[i] = logf(array[i] / sum);
  7337. }
  7338. }
  7339. void llama_sample_apply_guidance(
  7340. struct llama_context * ctx,
  7341. float * logits,
  7342. float * logits_guidance,
  7343. float scale) {
  7344. GGML_ASSERT(ctx);
  7345. const auto t_start_sample_us = ggml_time_us();
  7346. const auto n_vocab = llama_n_vocab(llama_get_model(ctx));
  7347. llama_log_softmax(logits, n_vocab);
  7348. llama_log_softmax(logits_guidance, n_vocab);
  7349. for (int i = 0; i < n_vocab; ++i) {
  7350. auto & l = logits[i];
  7351. const auto & g = logits_guidance[i];
  7352. l = scale * (l - g) + g;
  7353. }
  7354. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7355. }
  7356. void llama_sample_classifier_free_guidance(
  7357. struct llama_context * ctx,
  7358. llama_token_data_array * candidates,
  7359. struct llama_context * guidance_ctx,
  7360. float scale) {
  7361. GGML_ASSERT(ctx);
  7362. int64_t t_start_sample_us;
  7363. t_start_sample_us = ggml_time_us();
  7364. const size_t n_vocab = llama_n_vocab(llama_get_model(ctx));
  7365. GGML_ASSERT(n_vocab == candidates->size);
  7366. GGML_ASSERT(!candidates->sorted);
  7367. std::vector<float> logits_base(n_vocab);
  7368. for (size_t i = 0; i < n_vocab; ++i) {
  7369. logits_base[i] = candidates->data[i].logit;
  7370. }
  7371. float * logits_guidance = llama_get_logits(guidance_ctx);
  7372. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7373. llama_sample_apply_guidance(ctx, logits_base.data(), logits_guidance, scale);
  7374. t_start_sample_us = ggml_time_us();
  7375. for (size_t i = 0; i < n_vocab; ++i) {
  7376. candidates->data[i].logit = logits_base[i];
  7377. }
  7378. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7379. }
  7380. llama_token llama_sample_token_mirostat(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, int32_t m, float * mu) {
  7381. GGML_ASSERT(ctx);
  7382. auto N = float(llama_n_vocab(llama_get_model(ctx)));
  7383. int64_t t_start_sample_us;
  7384. t_start_sample_us = ggml_time_us();
  7385. llama_sample_softmax(nullptr, candidates);
  7386. // Estimate s_hat using the most probable m tokens
  7387. float s_hat = 0.0;
  7388. float sum_ti_bi = 0.0;
  7389. float sum_ti_sq = 0.0;
  7390. for (size_t i = 0; i < size_t(m - 1) && i < candidates->size - 1; ++i) {
  7391. float t_i = logf(float(i + 2) / float(i + 1));
  7392. float b_i = logf(candidates->data[i].p / candidates->data[i + 1].p);
  7393. sum_ti_bi += t_i * b_i;
  7394. sum_ti_sq += t_i * t_i;
  7395. }
  7396. s_hat = sum_ti_bi / sum_ti_sq;
  7397. // Compute k from the estimated s_hat and target surprise value
  7398. float epsilon_hat = s_hat - 1;
  7399. float k = powf((epsilon_hat * powf(2, *mu)) / (1 - powf(N, -epsilon_hat)), 1 / s_hat);
  7400. // Sample the next word X using top-k sampling
  7401. llama_sample_top_k(nullptr, candidates, int(k), 1);
  7402. if (ctx) {
  7403. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7404. }
  7405. llama_token X = llama_sample_token(ctx, candidates);
  7406. t_start_sample_us = ggml_time_us();
  7407. // Compute error as the difference between observed surprise and target surprise value
  7408. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  7409. return candidate.id == X;
  7410. }));
  7411. float observed_surprise = -log2f(candidates->data[X_idx].p);
  7412. float e = observed_surprise - tau;
  7413. // Update mu using the learning rate and error
  7414. *mu = *mu - eta * e;
  7415. if (ctx) {
  7416. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7417. }
  7418. return X;
  7419. }
  7420. llama_token llama_sample_token_mirostat_v2(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, float * mu) {
  7421. int64_t t_start_sample_us;
  7422. t_start_sample_us = ggml_time_us();
  7423. llama_sample_softmax(ctx, candidates);
  7424. // Truncate the words with surprise values greater than mu
  7425. candidates->size = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  7426. return -log2f(candidate.p) > *mu;
  7427. }));
  7428. if (candidates->size == 0) {
  7429. candidates->size = 1;
  7430. }
  7431. if (ctx) {
  7432. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7433. }
  7434. // Normalize the probabilities of the remaining words
  7435. llama_sample_softmax(ctx, candidates);
  7436. // Sample the next word X from the remaining words
  7437. llama_token X = llama_sample_token(ctx, candidates);
  7438. t_start_sample_us = ggml_time_us();
  7439. // Compute error as the difference between observed surprise and target surprise value
  7440. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  7441. return candidate.id == X;
  7442. }));
  7443. float observed_surprise = -log2f(candidates->data[X_idx].p);
  7444. float e = observed_surprise - tau;
  7445. // Update mu using the learning rate and error
  7446. *mu = *mu - eta * e;
  7447. if (ctx) {
  7448. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7449. }
  7450. return X;
  7451. }
  7452. llama_token llama_sample_token_greedy(struct llama_context * ctx, llama_token_data_array * candidates) {
  7453. const int64_t t_start_sample_us = ggml_time_us();
  7454. // Find max element
  7455. auto * max_iter = std::max_element(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  7456. return a.logit < b.logit;
  7457. });
  7458. llama_token result = max_iter->id;
  7459. if (ctx) {
  7460. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7461. ctx->n_sample++;
  7462. }
  7463. return result;
  7464. }
  7465. llama_token llama_sample_token(struct llama_context * ctx, llama_token_data_array * candidates) {
  7466. GGML_ASSERT(ctx);
  7467. const int64_t t_start_sample_us = ggml_time_us();
  7468. llama_sample_softmax(nullptr, candidates);
  7469. std::vector<float> probs;
  7470. probs.reserve(candidates->size);
  7471. for (size_t i = 0; i < candidates->size; ++i) {
  7472. probs.push_back(candidates->data[i].p);
  7473. }
  7474. std::discrete_distribution<> dist(probs.begin(), probs.end());
  7475. auto & rng = ctx->rng;
  7476. int idx = dist(rng);
  7477. llama_token result = candidates->data[idx].id;
  7478. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7479. ctx->n_sample++;
  7480. return result;
  7481. }
  7482. void llama_grammar_accept_token(struct llama_context * ctx, struct llama_grammar * grammar, llama_token token) {
  7483. const int64_t t_start_sample_us = ggml_time_us();
  7484. if (token == llama_token_eos(&ctx->model)) {
  7485. for (const auto & stack : grammar->stacks) {
  7486. if (stack.empty()) {
  7487. return;
  7488. }
  7489. }
  7490. GGML_ASSERT(false);
  7491. }
  7492. const std::string piece = llama_token_to_piece(ctx, token);
  7493. // Note terminating 0 in decoded string
  7494. const auto decoded = decode_utf8(piece, grammar->partial_utf8);
  7495. const auto & code_points = decoded.first;
  7496. for (auto it = code_points.begin(), end = code_points.end() - 1; it != end; ++it) {
  7497. grammar->stacks = llama_grammar_accept(grammar->rules, grammar->stacks, *it);
  7498. }
  7499. grammar->partial_utf8 = decoded.second;
  7500. GGML_ASSERT(!grammar->stacks.empty());
  7501. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7502. }
  7503. //
  7504. // Beam search
  7505. //
  7506. struct llama_beam {
  7507. std::vector<llama_token> tokens;
  7508. float p; // Cumulative beam probability (renormalized relative to all beams)
  7509. bool eob; // Initialize end-of-beam to false. Callback sets this to true.
  7510. // Sort beams by probability. In case of ties, prefer beams at eob.
  7511. bool operator<(const llama_beam & rhs) const {
  7512. return std::make_pair(p, eob) < std::make_pair(rhs.p, rhs.eob);
  7513. }
  7514. // Shift off first n tokens and discard them.
  7515. void shift_tokens(const size_t n) {
  7516. if (n) {
  7517. std::copy(tokens.begin() + n, tokens.end(), tokens.begin());
  7518. tokens.resize(tokens.size() - n);
  7519. }
  7520. }
  7521. llama_beam_view view() const { return {tokens.data(), tokens.size(), p, eob}; }
  7522. };
  7523. // A struct for calculating logit-related info.
  7524. struct llama_logit_info {
  7525. const float * const logits;
  7526. const int n_vocab;
  7527. const float max_l;
  7528. const float normalizer;
  7529. struct sum_exp {
  7530. float max_l;
  7531. float operator()(float sum, float l) const { return sum + std::exp(l - max_l); }
  7532. };
  7533. llama_logit_info(llama_context * ctx)
  7534. : logits(llama_get_logits(ctx))
  7535. , n_vocab(llama_n_vocab(llama_get_model(ctx)))
  7536. , max_l(*std::max_element(logits, logits + n_vocab))
  7537. , normalizer(1.0f / std::accumulate(logits, logits + n_vocab, 0.0f, sum_exp{max_l}))
  7538. { }
  7539. llama_token_data get_token_data(const llama_token token_id) const {
  7540. constexpr auto p = std::numeric_limits<float>::quiet_NaN(); // never used
  7541. return {token_id, logits[token_id], p};
  7542. }
  7543. // Return top k token_data by logit.
  7544. std::vector<llama_token_data> top_k(size_t k) {
  7545. std::vector<llama_token_data> min_heap; // min-heap by logit
  7546. const llama_token k_min = std::min(static_cast<llama_token>(k), n_vocab);
  7547. min_heap.reserve(k_min);
  7548. for (llama_token token_id = 0 ; token_id < k_min ; ++token_id) {
  7549. min_heap.push_back(get_token_data(token_id));
  7550. }
  7551. auto comp = [](const llama_token_data & a, const llama_token_data & b) { return a.logit > b.logit; };
  7552. std::make_heap(min_heap.begin(), min_heap.end(), comp);
  7553. for (llama_token token_id = k_min ; token_id < n_vocab ; ++token_id) {
  7554. if (min_heap.front().logit < logits[token_id]) {
  7555. std::pop_heap(min_heap.begin(), min_heap.end(), comp);
  7556. min_heap.back().id = token_id;
  7557. min_heap.back().logit = logits[token_id];
  7558. std::push_heap(min_heap.begin(), min_heap.end(), comp);
  7559. }
  7560. }
  7561. return min_heap;
  7562. }
  7563. float probability_from_logit(float logit) const {
  7564. return normalizer * std::exp(logit - max_l);
  7565. }
  7566. };
  7567. struct llama_beam_search_data {
  7568. llama_context * ctx;
  7569. size_t n_beams;
  7570. int n_past;
  7571. int n_predict;
  7572. std::vector<llama_beam> beams;
  7573. std::vector<llama_beam> next_beams;
  7574. // Re-calculated on each loop iteration
  7575. size_t common_prefix_length;
  7576. // Used to communicate to/from callback on beams state.
  7577. std::vector<llama_beam_view> beam_views;
  7578. llama_beam_search_data(llama_context * ctx, size_t n_beams, int n_past, int n_predict)
  7579. : ctx(ctx)
  7580. , n_beams(n_beams)
  7581. , n_past(n_past)
  7582. , n_predict(n_predict)
  7583. , beam_views(n_beams) {
  7584. beams.reserve(n_beams);
  7585. next_beams.reserve(n_beams);
  7586. }
  7587. // Collapse beams to a single beam given by index.
  7588. void collapse_beams(const size_t beam_idx) {
  7589. if (0u < beam_idx) {
  7590. std::swap(beams[0], beams[beam_idx]);
  7591. }
  7592. beams.resize(1);
  7593. }
  7594. // Min-heaps are used to efficiently collect the top-k elements (k=n_beams).
  7595. // The repetitive patterns below reflect the 2 stages of heaps:
  7596. // * Gather elements until the vector is full, then call std::make_heap() on it.
  7597. // * If the heap is full and a new element is found that should be included, pop the
  7598. // least element to the back(), replace it with the new, then push it into the heap.
  7599. void fill_next_beams_by_top_probabilities(llama_beam & beam) {
  7600. // Min-heaps use a greater-than comparator.
  7601. const auto comp = [](const llama_beam & a, const llama_beam & b) { return a.p > b.p; };
  7602. if (beam.eob) {
  7603. // beam is at end-of-sentence, so just copy it to next_beams if its probability is high enough.
  7604. if (next_beams.size() < n_beams) {
  7605. next_beams.push_back(std::move(beam));
  7606. if (next_beams.size() == n_beams) {
  7607. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  7608. }
  7609. } else if (next_beams.front().p < beam.p) {
  7610. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  7611. next_beams.back() = std::move(beam);
  7612. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  7613. }
  7614. } else {
  7615. // beam is not at end-of-sentence, so branch with next top_k tokens.
  7616. if (!beam.tokens.empty()) {
  7617. llama_decode(ctx, llama_batch_get_one(beam.tokens.data(), beam.tokens.size(), n_past, 0));
  7618. }
  7619. llama_logit_info logit_info(ctx);
  7620. std::vector<llama_token_data> next_tokens = logit_info.top_k(n_beams);
  7621. size_t i=0;
  7622. if (next_beams.size() < n_beams) {
  7623. for (; next_beams.size() < n_beams ; ++i) {
  7624. llama_beam next_beam = beam;
  7625. next_beam.tokens.push_back(next_tokens[i].id);
  7626. next_beam.p *= logit_info.probability_from_logit(next_tokens[i].logit);
  7627. next_beams.push_back(std::move(next_beam));
  7628. }
  7629. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  7630. } else {
  7631. for (; next_beams.front().p == 0.0f ; ++i) {
  7632. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  7633. next_beams.back() = beam;
  7634. next_beams.back().tokens.push_back(next_tokens[i].id);
  7635. next_beams.back().p *= logit_info.probability_from_logit(next_tokens[i].logit);
  7636. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  7637. }
  7638. }
  7639. for (; i < n_beams ; ++i) {
  7640. const float next_p = beam.p * logit_info.probability_from_logit(next_tokens[i].logit);
  7641. if (next_beams.front().p < next_p) {
  7642. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  7643. next_beams.back() = beam;
  7644. next_beams.back().tokens.push_back(next_tokens[i].id);
  7645. next_beams.back().p = next_p;
  7646. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  7647. }
  7648. }
  7649. }
  7650. }
  7651. // Find common_prefix_length based on beams.
  7652. // Requires beams is not empty.
  7653. size_t find_common_prefix_length() {
  7654. size_t common_prefix_length = beams[0].tokens.size();
  7655. for (size_t i = 1 ; i < beams.size() ; ++i) {
  7656. common_prefix_length = std::min(common_prefix_length, beams[i].tokens.size());
  7657. for (size_t j = 0 ; j < common_prefix_length ; ++j) {
  7658. if (beams[0].tokens[j] != beams[i].tokens[j]) {
  7659. common_prefix_length = j;
  7660. break;
  7661. }
  7662. }
  7663. }
  7664. return common_prefix_length;
  7665. }
  7666. // Construct beams_state to send back to caller via the callback function.
  7667. // Side effect: set common_prefix_length = find_common_prefix_length();
  7668. llama_beams_state get_beams_state(const bool last_call) {
  7669. for (size_t i = 0 ; i < beams.size() ; ++i) {
  7670. beam_views[i] = beams[i].view();
  7671. }
  7672. common_prefix_length = find_common_prefix_length();
  7673. return {beam_views.data(), beams.size(), common_prefix_length, last_call};
  7674. }
  7675. // Loop:
  7676. // * while i < n_predict, AND
  7677. // * any of the beams have not yet reached end-of-beam (eob), AND
  7678. // * the highest probability beam(s) (plural in case of ties) are not at end-of-sentence
  7679. // (since all other beam probabilities can only decrease)
  7680. void loop(const llama_beam_search_callback_fn_t callback, void * const callback_data) {
  7681. beams.push_back({{}, 1.0f, false}); // Start with one empty beam w/ probability = 1.0 and !eob.
  7682. const auto not_eob = [](const llama_beam & beam) { return !beam.eob; };
  7683. for (int i = 0 ; i < n_predict && std::any_of(beams.begin(),beams.end(),not_eob) &&
  7684. !beams[top_beam_index()].eob ; ++i) {
  7685. callback(callback_data, get_beams_state(false)); // Sets common_prefix_length
  7686. update_beams_from_beam_views(); // Update values (p,eob) that callback may have changed.
  7687. if (common_prefix_length) {
  7688. llama_decode(ctx, llama_batch_get_one(beams[0].tokens.data(), common_prefix_length, n_past, 0));
  7689. n_past += common_prefix_length;
  7690. }
  7691. // Zero-out next_beam probabilities to place them last in following min-heap.
  7692. std::for_each(next_beams.begin(), next_beams.end(), [](llama_beam & beam) { beam.p = 0.0f; });
  7693. for (llama_beam & beam : beams) {
  7694. beam.shift_tokens(common_prefix_length);
  7695. fill_next_beams_by_top_probabilities(beam);
  7696. }
  7697. // next_beams become the beams of next/final iteration. Swap them to re-use memory.
  7698. beams.swap(next_beams);
  7699. renormalize_beam_probabilities(beams);
  7700. }
  7701. collapse_beams(top_beam_index());
  7702. callback(callback_data, get_beams_state(true));
  7703. }
  7704. // As beams grow, the cumulative probabilities decrease.
  7705. // Renormalize them to avoid floating point underflow.
  7706. static void renormalize_beam_probabilities(std::vector<llama_beam> & beams) {
  7707. const auto sum_p = [](float sum, llama_beam & beam) { return sum + beam.p; };
  7708. const float inv_sum = 1.0f / std::accumulate(beams.begin(), beams.end(), 0.0f, sum_p);
  7709. std::for_each(beams.begin(), beams.end(), [=](llama_beam & beam) { beam.p *= inv_sum; });
  7710. }
  7711. // Assumes beams is non-empty. Uses llama_beam::operator<() for ordering.
  7712. size_t top_beam_index() {
  7713. return std::max_element(beams.begin(), beams.end()) - beams.begin();
  7714. }
  7715. // Copy (p,eob) for each beam which may have been changed by the callback.
  7716. void update_beams_from_beam_views() {
  7717. for (size_t i = 0 ; i < beams.size() ; ++i) {
  7718. beams[i].p = beam_views[i].p;
  7719. beams[i].eob = beam_views[i].eob;
  7720. }
  7721. }
  7722. };
  7723. void llama_beam_search(llama_context * ctx,
  7724. llama_beam_search_callback_fn_t callback, void * callback_data,
  7725. size_t n_beams, int n_past, int n_predict) {
  7726. assert(ctx);
  7727. const int64_t t_start_sample_us = ggml_time_us();
  7728. llama_beam_search_data beam_search_data(ctx, n_beams, n_past, n_predict);
  7729. beam_search_data.loop(callback, callback_data);
  7730. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7731. ctx->n_sample++;
  7732. }
  7733. //
  7734. // quantization
  7735. //
  7736. struct quantize_state_internal {
  7737. const llama_model & model;
  7738. const llama_model_quantize_params * params;
  7739. int n_attention_wv = 0;
  7740. int n_ffn_down = 0;
  7741. int n_ffn_gate = 0;
  7742. int n_ffn_up = 0;
  7743. int i_attention_wv = 0;
  7744. int i_ffn_down = 0;
  7745. int i_ffn_gate = 0;
  7746. int i_ffn_up = 0;
  7747. int n_k_quantized = 0;
  7748. int n_fallback = 0;
  7749. bool has_imatrix = false;
  7750. quantize_state_internal(const llama_model & model, const llama_model_quantize_params * params)
  7751. : model(model)
  7752. , params(params)
  7753. {}
  7754. };
  7755. static void llama_convert_tensor_internal(
  7756. struct ggml_tensor * tensor, std::vector<no_init<float>> & output, std::vector<std::thread> & workers,
  7757. const size_t nelements, const int nthread
  7758. ) {
  7759. if (output.size() < nelements) {
  7760. output.resize(nelements);
  7761. }
  7762. float * f32_output = (float *) output.data();
  7763. ggml_type_traits_t qtype;
  7764. if (ggml_is_quantized(tensor->type)) {
  7765. qtype = ggml_internal_get_type_traits(tensor->type);
  7766. if (qtype.to_float == NULL) {
  7767. throw std::runtime_error(format("type %s unsupported for integer quantization: no dequantization available", ggml_type_name(tensor->type)));
  7768. }
  7769. } else if (tensor->type != GGML_TYPE_F16) {
  7770. throw std::runtime_error(format("cannot dequantize/convert tensor type %s", ggml_type_name(tensor->type)));
  7771. }
  7772. if (nthread < 2) {
  7773. if (tensor->type == GGML_TYPE_F16) {
  7774. ggml_fp16_to_fp32_row((ggml_fp16_t *)tensor->data, f32_output, nelements);
  7775. } else if (ggml_is_quantized(tensor->type)) {
  7776. qtype.to_float(tensor->data, f32_output, nelements);
  7777. } else {
  7778. GGML_ASSERT(false); // unreachable
  7779. }
  7780. return;
  7781. }
  7782. size_t block_size = tensor->type == GGML_TYPE_F16 ? 1 : (size_t)ggml_blck_size(tensor->type);
  7783. size_t block_size_bytes = ggml_type_size(tensor->type);
  7784. GGML_ASSERT(nelements % block_size == 0);
  7785. size_t nblocks = nelements / block_size;
  7786. size_t blocks_per_thread = nblocks / nthread;
  7787. size_t spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count
  7788. size_t in_buff_offs = 0;
  7789. size_t out_buff_offs = 0;
  7790. for (int tnum = 0; tnum < nthread; tnum++) {
  7791. size_t thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread
  7792. size_t thr_elems = thr_blocks * block_size; // number of elements for this thread
  7793. size_t thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread
  7794. auto compute = [qtype] (ggml_type typ, uint8_t * inbuf, float * outbuf, int nels) {
  7795. if (typ == GGML_TYPE_F16) {
  7796. ggml_fp16_to_fp32_row((ggml_fp16_t *)inbuf, outbuf, nels);
  7797. } else {
  7798. qtype.to_float(inbuf, outbuf, nels);
  7799. }
  7800. };
  7801. workers.emplace_back(compute, tensor->type, (uint8_t *) tensor->data + in_buff_offs, f32_output + out_buff_offs, thr_elems);
  7802. in_buff_offs += thr_block_bytes;
  7803. out_buff_offs += thr_elems;
  7804. }
  7805. for (auto & w : workers) { w.join(); }
  7806. workers.clear();
  7807. }
  7808. static ggml_type get_k_quant_type(quantize_state_internal & qs, ggml_type new_type, const ggml_tensor * tensor, llama_ftype ftype) {
  7809. const std::string name = ggml_get_name(tensor);
  7810. // TODO: avoid hardcoded tensor names - use the TN_* constants
  7811. const llm_arch arch = qs.model.arch;
  7812. const auto tn = LLM_TN(arch);
  7813. auto use_more_bits = [](int i_layer, int num_layers) -> bool {
  7814. return i_layer < num_layers/8 || i_layer >= 7*num_layers/8 || (i_layer - num_layers/8)%3 == 2;
  7815. };
  7816. const int n_expert = std::max(1, (int)qs.model.hparams.n_expert);
  7817. auto layer_info = [n_expert] (int i_layer, int n_layer, const char * name) {
  7818. if (n_expert > 1) {
  7819. // Believe it or not, "experts" in the FFN of Mixtral-8x7B are not consecutive, but iccasionally randomly
  7820. // sprinkled in the model. Hence, simply dividing i_ffn_down by n_expert does not work
  7821. // for getting the current layer as I initially thought, and we need to resort to parsing the
  7822. // tensor name.
  7823. n_layer /= n_expert;
  7824. if (sscanf(name, "blk.%d.", &i_layer) != 1) {
  7825. throw std::runtime_error(format("Failed to determine layer for tensor %s", name));
  7826. }
  7827. if (i_layer < 0 || i_layer >= n_layer) {
  7828. throw std::runtime_error(format("Bad layer %d for tensor %s. Must be in [0, %d)", i_layer, name, n_layer));
  7829. }
  7830. }
  7831. return std::make_pair(i_layer, n_layer);
  7832. };
  7833. if (name == tn(LLM_TENSOR_OUTPUT, "weight")) {
  7834. int nx = tensor->ne[0];
  7835. if (arch == LLM_ARCH_FALCON || nx % QK_K != 0) {
  7836. new_type = GGML_TYPE_Q8_0;
  7837. }
  7838. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS) {
  7839. new_type = GGML_TYPE_Q5_K;
  7840. }
  7841. else if (new_type != GGML_TYPE_Q8_0) {
  7842. new_type = GGML_TYPE_Q6_K;
  7843. }
  7844. } else if (name == "token_embd.weight") {
  7845. if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS) {
  7846. new_type = GGML_TYPE_Q2_K;
  7847. }
  7848. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  7849. new_type = GGML_TYPE_Q4_K;
  7850. }
  7851. } else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS) {
  7852. if (name.find("attn_v.weight") != std::string::npos) {
  7853. if (qs.model.hparams.n_gqa() >= 4 || qs.model.hparams.n_expert >= 4) new_type = GGML_TYPE_Q4_K;
  7854. else new_type = GGML_TYPE_Q2_K;
  7855. ++qs.i_attention_wv;
  7856. }
  7857. else if (name.find("ffn_down") != std::string::npos) {
  7858. if (qs.i_ffn_down < qs.n_ffn_down/8) new_type = GGML_TYPE_Q2_K;
  7859. ++qs.i_ffn_down;
  7860. }
  7861. } else if (name.find("attn_v.weight") != std::string::npos) {
  7862. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) {
  7863. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  7864. }
  7865. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && qs.model.hparams.n_gqa() >= 4) {
  7866. new_type = GGML_TYPE_Q4_K;
  7867. }
  7868. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS && qs.model.hparams.n_gqa() >= 4) {
  7869. new_type = GGML_TYPE_Q4_K;
  7870. }
  7871. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  7872. new_type = qs.i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  7873. }
  7874. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  7875. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
  7876. use_more_bits(qs.i_attention_wv, qs.n_attention_wv)) new_type = GGML_TYPE_Q6_K;
  7877. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && qs.i_attention_wv < 4) new_type = GGML_TYPE_Q5_K;
  7878. else if (QK_K == 64 && (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S) &&
  7879. (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;
  7880. if (qs.model.type == MODEL_70B) {
  7881. // In the 70B model we have 8 heads sharing the same attn_v weights. As a result, the attn_v.weight tensor is
  7882. // 8x smaller compared to attn_q.weight. Hence, we can get a nice boost in quantization accuracy with
  7883. // nearly negligible increase in model size by quantizing this tensor with more bits:
  7884. if (new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K) new_type = GGML_TYPE_Q5_K;
  7885. }
  7886. if (qs.model.hparams.n_expert == 8) {
  7887. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  7888. // TODO: explore better strategies
  7889. new_type = GGML_TYPE_Q8_0;
  7890. }
  7891. ++qs.i_attention_wv;
  7892. } else if (name.find("attn_k.weight") != std::string::npos) {
  7893. if (qs.model.hparams.n_expert == 8) {
  7894. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  7895. // TODO: explore better strategies
  7896. new_type = GGML_TYPE_Q8_0;
  7897. }
  7898. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_XS) {
  7899. new_type = GGML_TYPE_Q2_K;
  7900. }
  7901. } else if (name.find("ffn_down") != std::string::npos) {
  7902. auto info = layer_info(qs.i_ffn_down, qs.n_ffn_down, name.c_str());
  7903. int i_layer = info.first, n_layer = info.second;
  7904. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  7905. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_XS) {
  7906. if (i_layer < n_layer/8) new_type = GGML_TYPE_Q4_K;
  7907. }
  7908. //else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  7909. // if (i_layer < n_layer/8) new_type = GGML_TYPE_Q5_K;
  7910. //}
  7911. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  7912. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q5_K
  7913. : arch != LLM_ARCH_FALCON || use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q4_K
  7914. : GGML_TYPE_Q3_K;
  7915. }
  7916. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) {
  7917. new_type = arch == LLM_ARCH_FALCON ? GGML_TYPE_Q4_K : GGML_TYPE_Q5_K;
  7918. }
  7919. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  7920. if (arch == LLM_ARCH_FALCON) {
  7921. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q6_K :
  7922. use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  7923. } else {
  7924. if (use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  7925. }
  7926. }
  7927. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M && use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  7928. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && arch != LLM_ARCH_FALCON && i_layer < n_layer/8) {
  7929. new_type = GGML_TYPE_Q5_K;
  7930. }
  7931. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_0 || ftype == LLAMA_FTYPE_MOSTLY_Q5_0)
  7932. && qs.has_imatrix && i_layer < n_layer/8) {
  7933. // Guard against craziness in the first few ffn_down layers that can happen even with imatrix for Q4_0/Q5_0.
  7934. // We only do it when an imatrix is provided because a) we want to make sure that one can always get the
  7935. // same quantization as before imatrix stuff, and b) Q4_1/Q5_1 do go crazy on ffn_down without an imatrix.
  7936. new_type = ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ? GGML_TYPE_Q4_1 : GGML_TYPE_Q5_1;
  7937. }
  7938. ++qs.i_ffn_down;
  7939. } else if (name.find("attn_output.weight") != std::string::npos) {
  7940. if (arch != LLM_ARCH_FALCON) {
  7941. if (qs.model.hparams.n_expert == 8) {
  7942. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  7943. ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M ||
  7944. ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  7945. new_type = GGML_TYPE_Q5_K;
  7946. }
  7947. } else {
  7948. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K ) new_type = GGML_TYPE_Q3_K;
  7949. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) new_type = GGML_TYPE_Q3_K;
  7950. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) new_type = GGML_TYPE_Q4_K;
  7951. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  7952. }
  7953. } else {
  7954. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  7955. }
  7956. }
  7957. else if (name.find("attn_qkv.weight") != std::string::npos) {
  7958. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  7959. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) new_type = GGML_TYPE_Q5_K;
  7960. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) new_type = GGML_TYPE_Q6_K;
  7961. }
  7962. else if (name.find("ffn_gate") != std::string::npos) {
  7963. auto info = layer_info(qs.i_ffn_gate, qs.n_ffn_gate, name.c_str());
  7964. int i_layer = info.first, n_layer = info.second;
  7965. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_XS && !use_more_bits(i_layer, n_layer)) {
  7966. new_type = GGML_TYPE_Q2_K;
  7967. }
  7968. ++qs.i_ffn_gate;
  7969. }
  7970. else if (name.find("ffn_up") != std::string::npos) {
  7971. auto info = layer_info(qs.i_ffn_up, qs.n_ffn_up, name.c_str());
  7972. int i_layer = info.first, n_layer = info.second;
  7973. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_XS && !use_more_bits(i_layer, n_layer)) {
  7974. new_type = GGML_TYPE_Q2_K;
  7975. }
  7976. ++qs.i_ffn_up;
  7977. }
  7978. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  7979. //}
  7980. // IK: let's remove this, else Q2_K is almost the same as Q3_K_S
  7981. //else if (name.find("ffn_gate") != std::string::npos || name.find("ffn_up") != std::string::npos) {
  7982. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  7983. //}
  7984. // This can be used to reduce the size of the Q5_K_S model.
  7985. // The associated PPL increase is fully in line with the size reduction
  7986. //else {
  7987. // if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_S) new_type = GGML_TYPE_Q4_K;
  7988. //}
  7989. bool convert_incompatible_tensor = false;
  7990. if (new_type == GGML_TYPE_Q2_K || new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K ||
  7991. new_type == GGML_TYPE_Q5_K || new_type == GGML_TYPE_Q6_K ||
  7992. new_type == GGML_TYPE_IQ2_XS || new_type == GGML_TYPE_IQ2_XXS ||
  7993. new_type == GGML_TYPE_IQ3_XXS) {
  7994. int nx = tensor->ne[0];
  7995. int ny = tensor->ne[1];
  7996. if (nx % QK_K != 0) {
  7997. 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));
  7998. convert_incompatible_tensor = true;
  7999. } else {
  8000. ++qs.n_k_quantized;
  8001. }
  8002. }
  8003. if (convert_incompatible_tensor) {
  8004. switch (new_type) {
  8005. case GGML_TYPE_IQ2_XXS:
  8006. case GGML_TYPE_IQ2_XS:
  8007. case GGML_TYPE_IQ3_XXS:
  8008. case GGML_TYPE_Q2_K: new_type = GGML_TYPE_Q4_0; break;
  8009. case GGML_TYPE_Q3_K: new_type = GGML_TYPE_Q4_1; break;
  8010. case GGML_TYPE_Q4_K: new_type = GGML_TYPE_Q5_0; break;
  8011. case GGML_TYPE_Q5_K: new_type = GGML_TYPE_Q5_1; break;
  8012. case GGML_TYPE_Q6_K: new_type = GGML_TYPE_Q8_0; break;
  8013. default: throw std::runtime_error("\nUnsupported tensor size encountered\n");
  8014. }
  8015. LLAMA_LOG_WARN(" - using fallback quantization %s\n", ggml_type_name(new_type));
  8016. ++qs.n_fallback;
  8017. }
  8018. return new_type;
  8019. }
  8020. static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) {
  8021. ggml_type quantized_type;
  8022. llama_ftype ftype = params->ftype;
  8023. switch (params->ftype) {
  8024. case LLAMA_FTYPE_MOSTLY_Q4_0: quantized_type = GGML_TYPE_Q4_0; break;
  8025. case LLAMA_FTYPE_MOSTLY_Q4_1: quantized_type = GGML_TYPE_Q4_1; break;
  8026. case LLAMA_FTYPE_MOSTLY_Q5_0: quantized_type = GGML_TYPE_Q5_0; break;
  8027. case LLAMA_FTYPE_MOSTLY_Q5_1: quantized_type = GGML_TYPE_Q5_1; break;
  8028. case LLAMA_FTYPE_MOSTLY_Q8_0: quantized_type = GGML_TYPE_Q8_0; break;
  8029. case LLAMA_FTYPE_MOSTLY_F16: quantized_type = GGML_TYPE_F16; break;
  8030. case LLAMA_FTYPE_ALL_F32: quantized_type = GGML_TYPE_F32; break;
  8031. // K-quants
  8032. case LLAMA_FTYPE_MOSTLY_Q2_K_S:
  8033. case LLAMA_FTYPE_MOSTLY_Q2_K: quantized_type = GGML_TYPE_Q2_K; break;
  8034. case LLAMA_FTYPE_MOSTLY_Q3_K_XS:
  8035. case LLAMA_FTYPE_MOSTLY_Q3_K_S:
  8036. case LLAMA_FTYPE_MOSTLY_Q3_K_M:
  8037. case LLAMA_FTYPE_MOSTLY_Q3_K_L: quantized_type = GGML_TYPE_Q3_K; break;
  8038. case LLAMA_FTYPE_MOSTLY_Q4_K_S:
  8039. case LLAMA_FTYPE_MOSTLY_Q4_K_M: quantized_type = GGML_TYPE_Q4_K; break;
  8040. case LLAMA_FTYPE_MOSTLY_Q5_K_S:
  8041. case LLAMA_FTYPE_MOSTLY_Q5_K_M: quantized_type = GGML_TYPE_Q5_K; break;
  8042. case LLAMA_FTYPE_MOSTLY_Q6_K: quantized_type = GGML_TYPE_Q6_K; break;
  8043. case LLAMA_FTYPE_MOSTLY_IQ2_XXS:quantized_type = GGML_TYPE_IQ2_XXS; break;
  8044. case LLAMA_FTYPE_MOSTLY_IQ2_XS :quantized_type = GGML_TYPE_IQ2_XS; break;
  8045. case LLAMA_FTYPE_MOSTLY_IQ3_XXS:quantized_type = GGML_TYPE_IQ3_XXS; break;
  8046. default: throw std::runtime_error(format("invalid output file type %d\n", ftype));
  8047. }
  8048. int nthread = params->nthread;
  8049. if (nthread <= 0) {
  8050. nthread = std::thread::hardware_concurrency();
  8051. }
  8052. // mmap consistently increases speed Linux, and also increases speed on Windows with
  8053. // hot cache. It may cause a slowdown on macOS, possibly related to free memory.
  8054. #if defined(__linux__) || defined(_WIN32)
  8055. constexpr bool use_mmap = true;
  8056. #else
  8057. constexpr bool use_mmap = false;
  8058. #endif
  8059. llama_model_loader ml(fname_inp, use_mmap, NULL);
  8060. ml.init_mapping(false); // no prefetching?
  8061. llama_model model;
  8062. llm_load_arch(ml, model);
  8063. llm_load_hparams(ml, model);
  8064. struct quantize_state_internal qs(model, params);
  8065. if (params->only_copy) {
  8066. ftype = model.ftype;
  8067. }
  8068. const std::unordered_map<std::string, std::vector<float>> * imatrix_data = nullptr;
  8069. if (params->imatrix) {
  8070. imatrix_data = static_cast<const std::unordered_map<std::string, std::vector<float>>*>(params->imatrix);
  8071. if (imatrix_data) {
  8072. LLAMA_LOG_INFO("================================ Have weights data with %d entries\n",int(imatrix_data->size()));
  8073. qs.has_imatrix = true;
  8074. }
  8075. }
  8076. const size_t align = GGUF_DEFAULT_ALIGNMENT;
  8077. struct gguf_context * ctx_out = gguf_init_empty();
  8078. // copy the KV pairs from the input file
  8079. gguf_set_kv (ctx_out, ml.ctx_gguf);
  8080. gguf_set_val_u32(ctx_out, "general.quantization_version", GGML_QNT_VERSION);
  8081. gguf_set_val_u32(ctx_out, "general.file_type", ftype);
  8082. for (int i = 0; i < ml.n_tensors; ++i) {
  8083. struct ggml_tensor * meta = ml.get_tensor_meta(i);
  8084. const std::string name = ggml_get_name(meta);
  8085. // TODO: avoid hardcoded tensor names - use the TN_* constants
  8086. if (name.find("attn_v.weight") != std::string::npos || name.find("attn_qkv.weight") != std::string::npos) {
  8087. ++qs.n_attention_wv;
  8088. }
  8089. else if (name.find("ffn_down") != std::string::npos) {
  8090. ++qs.n_ffn_down;
  8091. }
  8092. else if (name.find("ffn_gate") != std::string::npos) {
  8093. ++qs.n_ffn_gate;
  8094. }
  8095. else if (name.find("ffn_up") != std::string::npos) {
  8096. ++qs.n_ffn_up;
  8097. }
  8098. }
  8099. if (qs.n_attention_wv != qs.n_ffn_down || (uint32_t)qs.n_attention_wv != model.hparams.n_layer) {
  8100. LLAMA_LOG_WARN("%s ============ Strange model: n_attention_wv = %d, n_ffn_down = %d, hparams.n_layer = %d\n",
  8101. __func__, qs.n_attention_wv, qs.n_ffn_down, model.hparams.n_layer);
  8102. }
  8103. size_t total_size_org = 0;
  8104. size_t total_size_new = 0;
  8105. std::vector<int64_t> hist_all(1 << 4, 0);
  8106. std::vector<std::thread> workers;
  8107. workers.reserve(nthread);
  8108. std::mutex mutex;
  8109. int idx = 0;
  8110. std::vector<no_init<uint8_t>> read_data;
  8111. std::vector<no_init<uint8_t>> work;
  8112. std::vector<no_init<float>> f32_conv_buf;
  8113. // populate the original tensors so we get an initial meta data
  8114. for (int i = 0; i < ml.n_tensors; ++i) {
  8115. struct ggml_tensor * meta = ml.get_tensor_meta(i);
  8116. gguf_add_tensor(ctx_out, meta);
  8117. }
  8118. std::ofstream fout(fname_out, std::ios::binary);
  8119. fout.exceptions(std::ofstream::failbit); // fail fast on write errors
  8120. const size_t meta_size = gguf_get_meta_size(ctx_out);
  8121. LLAMA_LOG_INFO("%s: meta size = %zu bytes\n", __func__, meta_size);
  8122. // placeholder for the meta data
  8123. ::zeros(fout, meta_size);
  8124. for (int i = 0; i < ml.n_tensors; ++i) {
  8125. struct ggml_tensor * tensor = ml.get_tensor_meta(i);
  8126. const std::string name = ggml_get_name(tensor);
  8127. if (!ml.use_mmap) {
  8128. if (read_data.size() < ggml_nbytes(tensor)) {
  8129. read_data.resize(ggml_nbytes(tensor));
  8130. }
  8131. tensor->data = read_data.data();
  8132. }
  8133. ml.load_data_for(tensor);
  8134. LLAMA_LOG_INFO("[%4d/%4d] %36s - [%s], type = %6s, ",
  8135. ++idx, ml.n_tensors,
  8136. ggml_get_name(tensor),
  8137. llama_format_tensor_shape(tensor).c_str(),
  8138. ggml_type_name(tensor->type));
  8139. // This used to be a regex, but <regex> has an extreme cost to compile times.
  8140. bool quantize = name.rfind("weight") == name.size() - 6; // ends with 'weight'?
  8141. // quantize only 2D tensors
  8142. quantize &= (ggml_n_dims(tensor) == 2);
  8143. quantize &= params->quantize_output_tensor || name != "output.weight";
  8144. quantize &= !params->only_copy;
  8145. // do not quantize expert gating tensors
  8146. quantize &= name.find("ffn_gate_inp.weight") == std::string::npos;
  8147. enum ggml_type new_type;
  8148. void * new_data;
  8149. size_t new_size;
  8150. if (quantize) {
  8151. new_type = quantized_type;
  8152. if (!params->pure) {
  8153. new_type = get_k_quant_type(qs, new_type, tensor, ftype);
  8154. }
  8155. // If we've decided to quantize to the same type the tensor is already
  8156. // in then there's nothing to do.
  8157. quantize = tensor->type != new_type;
  8158. }
  8159. if (!quantize) {
  8160. new_type = tensor->type;
  8161. new_data = tensor->data;
  8162. new_size = ggml_nbytes(tensor);
  8163. LLAMA_LOG_INFO("size = %8.3f MB\n", ggml_nbytes(tensor)/1024.0/1024.0);
  8164. } else {
  8165. const size_t nelements = ggml_nelements(tensor);
  8166. const float * imatrix = nullptr;
  8167. if (imatrix_data) {
  8168. auto it = imatrix_data->find(tensor->name);
  8169. if (it == imatrix_data->end()) {
  8170. LLAMA_LOG_INFO("\n====== %s: did not find weights for %s\n", __func__, tensor->name);
  8171. } else {
  8172. if (it->second.size() == (size_t)tensor->ne[0]) {
  8173. imatrix = it->second.data();
  8174. } else {
  8175. LLAMA_LOG_INFO("\n====== %s: imatrix size %d is different from tensor size %d for %s\n", __func__,
  8176. int(it->second.size()), int(tensor->ne[0]), tensor->name);
  8177. }
  8178. }
  8179. }
  8180. if ((new_type == GGML_TYPE_IQ2_XXS ||
  8181. new_type == GGML_TYPE_IQ2_XS ||
  8182. (new_type == GGML_TYPE_Q2_K && params->ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && strcmp(tensor->name, "token_embd.weight") != 0)) && !imatrix) {
  8183. LLAMA_LOG_ERROR("\n\n============================================================\n");
  8184. LLAMA_LOG_ERROR("Missing importance matrix for tensor %s in a very low-bit quantization\n", tensor->name);
  8185. LLAMA_LOG_ERROR("The result will be garbage, so bailing out\n");
  8186. LLAMA_LOG_ERROR("============================================================\n\n");
  8187. throw std::runtime_error(format("Missing importance matrix for tensor %s in a very low-bit quantization", tensor->name));
  8188. }
  8189. float * f32_data;
  8190. if (tensor->type == GGML_TYPE_F32) {
  8191. f32_data = (float *) tensor->data;
  8192. } else if (ggml_is_quantized(tensor->type) && !params->allow_requantize) {
  8193. throw std::runtime_error(format("requantizing from type %s is disabled", ggml_type_name(tensor->type)));
  8194. } else {
  8195. llama_convert_tensor_internal(tensor, f32_conv_buf, workers, nelements, nthread);
  8196. f32_data = (float *) f32_conv_buf.data();
  8197. }
  8198. LLAMA_LOG_INFO("quantizing to %s .. ", ggml_type_name(new_type));
  8199. fflush(stdout);
  8200. if (work.size() < nelements * 4) {
  8201. work.resize(nelements * 4); // upper bound on size
  8202. }
  8203. new_data = work.data();
  8204. std::array<int64_t, 1 << 4> hist_cur = {};
  8205. const int n_per_row = tensor->ne[0];
  8206. const int nrows = nelements / n_per_row;
  8207. static const int min_chunk_size = 32 * 512;
  8208. 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);
  8209. const int nchunk = (nelements + chunk_size - 1)/chunk_size;
  8210. const int nthread_use = nthread > 1 ? std::max(1, std::min(nthread, nchunk)) : 1;
  8211. if (nthread_use < 2) {
  8212. new_size = ggml_quantize_chunk(new_type, f32_data, new_data, 0, nrows, n_per_row, hist_cur.data(), imatrix);
  8213. } else {
  8214. int counter = 0;
  8215. new_size = 0;
  8216. auto compute = [&mutex, &counter, &hist_cur, &new_size, new_type, f32_data, new_data, chunk_size,
  8217. nrows, n_per_row, imatrix]() {
  8218. std::array<int64_t, 1 << 4> local_hist = {};
  8219. const int nrows_per_chunk = chunk_size / n_per_row;
  8220. size_t local_size = 0;
  8221. while (true) {
  8222. std::unique_lock<std::mutex> lock(mutex);
  8223. int first_row = counter; counter += nrows_per_chunk;
  8224. if (first_row >= nrows) {
  8225. if (local_size > 0) {
  8226. for (int j=0; j<int(local_hist.size()); ++j) {
  8227. hist_cur[j] += local_hist[j];
  8228. }
  8229. new_size += local_size;
  8230. }
  8231. break;
  8232. }
  8233. lock.unlock();
  8234. const int this_nrow = std::min(nrows - first_row, nrows_per_chunk);
  8235. local_size += ggml_quantize_chunk(new_type, f32_data, new_data,
  8236. first_row * n_per_row, this_nrow, n_per_row, local_hist.data(), imatrix);
  8237. }
  8238. };
  8239. for (int it = 0; it < nthread_use - 1; ++it) {
  8240. workers.emplace_back(compute);
  8241. }
  8242. compute();
  8243. for (auto & w : workers) { w.join(); }
  8244. workers.clear();
  8245. }
  8246. LLAMA_LOG_INFO("size = %8.2f MiB -> %8.2f MiB", ggml_nbytes(tensor)/1024.0/1024.0, new_size/1024.0/1024.0);
  8247. int64_t tot_count = 0;
  8248. for (size_t i = 0; i < hist_cur.size(); i++) {
  8249. hist_all[i] += hist_cur[i];
  8250. tot_count += hist_cur[i];
  8251. }
  8252. if (tot_count > 0) {
  8253. LLAMA_LOG_INFO(" | hist: ");
  8254. for (size_t i = 0; i < hist_cur.size(); i++) {
  8255. LLAMA_LOG_INFO("%5.3f ", hist_cur[i] / float(nelements));
  8256. }
  8257. }
  8258. LLAMA_LOG_INFO("\n");
  8259. }
  8260. total_size_org += ggml_nbytes(tensor);
  8261. total_size_new += new_size;
  8262. // update the gguf meta data as we go
  8263. gguf_set_tensor_type(ctx_out, name.c_str(), new_type);
  8264. gguf_set_tensor_data(ctx_out, name.c_str(), new_data, new_size);
  8265. // write tensor data + padding
  8266. fout.write((const char *) new_data, new_size);
  8267. zeros(fout, GGML_PAD(new_size, align) - new_size);
  8268. }
  8269. // go back to beginning of file and write the updated meta data
  8270. {
  8271. fout.seekp(0);
  8272. std::vector<uint8_t> data(gguf_get_meta_size(ctx_out));
  8273. gguf_get_meta_data(ctx_out, data.data());
  8274. fout.write((const char *) data.data(), data.size());
  8275. }
  8276. fout.close();
  8277. gguf_free(ctx_out);
  8278. LLAMA_LOG_INFO("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  8279. LLAMA_LOG_INFO("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  8280. // print histogram for all tensors
  8281. {
  8282. int64_t sum_all = 0;
  8283. for (size_t i = 0; i < hist_all.size(); i++) {
  8284. sum_all += hist_all[i];
  8285. }
  8286. if (sum_all > 0) {
  8287. LLAMA_LOG_INFO("%s: hist: ", __func__);
  8288. for (size_t i = 0; i < hist_all.size(); i++) {
  8289. LLAMA_LOG_INFO("%5.3f ", hist_all[i] / float(sum_all));
  8290. }
  8291. LLAMA_LOG_INFO("\n");
  8292. }
  8293. }
  8294. if (qs.n_fallback > 0) {
  8295. LLAMA_LOG_WARN("%s: WARNING: %d of %d tensor(s) incompatible with k-quants and required fallback quantization\n",
  8296. __func__, qs.n_fallback, qs.n_k_quantized + qs.n_fallback);
  8297. }
  8298. }
  8299. static int llama_apply_lora_from_file_internal(
  8300. const struct llama_model & model, const char * path_lora, float scale, const char * path_base_model, int n_threads
  8301. ) {
  8302. LLAMA_LOG_INFO("%s: applying lora adapter from '%s' - please wait ...\n", __func__, path_lora);
  8303. const int64_t t_start_lora_us = ggml_time_us();
  8304. llama_file fin(path_lora, "rb");
  8305. // verify magic and version
  8306. {
  8307. uint32_t magic = fin.read_u32();
  8308. if (magic != LLAMA_FILE_MAGIC_GGLA) {
  8309. LLAMA_LOG_ERROR("%s: bad file magic\n", __func__);
  8310. return 1;
  8311. }
  8312. uint32_t format_version = fin.read_u32();
  8313. if (format_version != 1) {
  8314. LLAMA_LOG_ERROR("%s: unsupported file version\n", __func__ );
  8315. return 1;
  8316. }
  8317. }
  8318. int32_t lora_r = fin.read_u32();
  8319. int32_t lora_alpha = fin.read_u32();
  8320. float scaling = scale * (float)lora_alpha / (float)lora_r;
  8321. LLAMA_LOG_INFO("%s: r = %d, alpha = %d, scaling = %.2f\n", __func__, lora_r, lora_alpha, scaling);
  8322. // load base model
  8323. std::unique_ptr<llama_model_loader> ml;
  8324. if (path_base_model) {
  8325. LLAMA_LOG_INFO("%s: loading base model from '%s'\n", __func__, path_base_model);
  8326. ml.reset(new llama_model_loader(path_base_model, /*use_mmap*/ true, /*kv_overrides*/ nullptr));
  8327. ml->init_mapping(/*prefetch*/ false); // no prefetching
  8328. }
  8329. struct tensor_meta {
  8330. std::string name;
  8331. ggml_type type;
  8332. int32_t ne[2];
  8333. size_t offset;
  8334. };
  8335. std::map<std::string, tensor_meta> tensor_meta_map;
  8336. // load all tensor meta
  8337. while (true) {
  8338. if (fin.tell() == fin.size) {
  8339. // eof
  8340. break;
  8341. }
  8342. int32_t n_dims;
  8343. int32_t name_len;
  8344. int32_t ftype;
  8345. fin.read_raw(&n_dims, sizeof(n_dims));
  8346. fin.read_raw(&name_len, sizeof(name_len));
  8347. fin.read_raw(&ftype, sizeof(ftype));
  8348. if (n_dims != 1 && n_dims != 2) {
  8349. LLAMA_LOG_ERROR("%s: unsupported tensor dimension %d\n", __func__, n_dims);
  8350. return 1;
  8351. }
  8352. int32_t ne[2] = { 1, 1 };
  8353. for (int i = 0; i < n_dims; ++i) {
  8354. fin.read_raw(&ne[i], sizeof(ne[i]));
  8355. }
  8356. std::string name;
  8357. {
  8358. GGML_ASSERT(name_len < GGML_MAX_NAME);
  8359. char buf[GGML_MAX_NAME];
  8360. fin.read_raw(buf, name_len);
  8361. name = std::string(buf, name_len);
  8362. }
  8363. // check for lora suffix
  8364. std::string lora_suffix;
  8365. if (name.length() > 6) {
  8366. lora_suffix = name.substr(name.length() - 6);
  8367. }
  8368. if (lora_suffix != ".loraA" && lora_suffix != ".loraB") {
  8369. LLAMA_LOG_ERROR("%s: error: '%s' is not a lora tensor\n", __func__, name.c_str());
  8370. return 1;
  8371. }
  8372. // tensor type
  8373. ggml_type wtype;
  8374. switch (ftype) {
  8375. case 0: wtype = GGML_TYPE_F32; break;
  8376. case 1: wtype = GGML_TYPE_F16; break;
  8377. default:
  8378. {
  8379. LLAMA_LOG_ERROR("%s: invalid tensor data type '%d'\n",
  8380. __func__, ftype);
  8381. return false;
  8382. }
  8383. }
  8384. // data offset
  8385. size_t offset = fin.tell();
  8386. offset = (offset + 31) & -32;
  8387. // skip tensor data
  8388. fin.seek(offset + ggml_row_size(wtype, ne[0]) * ne[1], SEEK_SET);
  8389. tensor_meta_map.emplace(name, tensor_meta{ name, wtype, { ne[0], ne[1] }, offset });
  8390. }
  8391. bool warned = false;
  8392. int n_tensors = 0;
  8393. // apply
  8394. ggml_backend_t backend_cpu = ggml_backend_cpu_init();
  8395. if (backend_cpu == nullptr) {
  8396. LLAMA_LOG_ERROR("%s: error: failed to initialize cpu backend\n", __func__);
  8397. return 1;
  8398. }
  8399. ggml_backend_cpu_set_n_threads(backend_cpu, n_threads);
  8400. std::vector<no_init<uint8_t>> read_buf;
  8401. for (const auto & it : model.tensors_by_name) {
  8402. const std::string & base_name = it.first;
  8403. ggml_tensor * model_t = it.second;
  8404. if (tensor_meta_map.find(base_name + ".loraA") == tensor_meta_map.end() ||
  8405. tensor_meta_map.find(base_name + ".loraB") == tensor_meta_map.end()) {
  8406. continue;
  8407. }
  8408. tensor_meta & metaA = tensor_meta_map.at(base_name + ".loraA");
  8409. tensor_meta & metaB = tensor_meta_map.at(base_name + ".loraB");
  8410. ggml_init_params lora_init_params = {
  8411. /* .mem_size */ ggml_tensor_overhead()*128 + ggml_graph_overhead(),
  8412. /* .mem_buffer */ nullptr,
  8413. /* .no_alloc */ true,
  8414. };
  8415. ggml_context * lora_ctx = ggml_init(lora_init_params);
  8416. if (lora_ctx == nullptr) {
  8417. LLAMA_LOG_ERROR("%s: error: failed to initialize lora context\n", __func__);
  8418. ggml_backend_free(backend_cpu);
  8419. return 1;
  8420. }
  8421. // create tensors
  8422. ggml_tensor * loraA = ggml_new_tensor_2d(lora_ctx, metaA.type, metaA.ne[0], metaA.ne[1]);
  8423. ggml_tensor * loraB = ggml_new_tensor_2d(lora_ctx, metaB.type, metaB.ne[0], metaB.ne[1]);
  8424. ggml_set_name(loraA, metaA.name.c_str());
  8425. ggml_set_name(loraB, metaB.name.c_str());
  8426. ggml_tensor * base_t;
  8427. if (ml) {
  8428. if (gguf_find_tensor(ml->ctx_gguf, base_name.c_str()) < 0) {
  8429. LLAMA_LOG_ERROR("%s: error: tensor '%s' not found in base model\n", __func__, base_name.c_str());
  8430. return 1;
  8431. }
  8432. base_t = ggml_dup_tensor(lora_ctx, ml->get_tensor_meta(base_name.c_str()));
  8433. } else {
  8434. base_t = ggml_dup_tensor(lora_ctx, model_t);
  8435. }
  8436. ggml_set_name(base_t, base_name.c_str());
  8437. // allocate in backend buffer
  8438. ggml_backend_buffer_t lora_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  8439. if (lora_buf == nullptr) {
  8440. LLAMA_LOG_ERROR("%s: error: failed to allocate lora tensors\n", __func__);
  8441. return 1;
  8442. }
  8443. // load tensor data
  8444. auto load_tensor = [&read_buf, &fin](const tensor_meta & tensor_meta, ggml_tensor * tensor) {
  8445. read_buf.resize(ggml_nbytes(tensor));
  8446. fin.seek(tensor_meta.offset, SEEK_SET);
  8447. fin.read_raw(read_buf.data(), ggml_nbytes(tensor));
  8448. ggml_backend_tensor_set(tensor, read_buf.data(), 0, read_buf.size());
  8449. };
  8450. load_tensor(metaA, loraA);
  8451. load_tensor(metaB, loraB);
  8452. // load base model tensor data
  8453. if (ml) {
  8454. ml->load_data_for(base_t);
  8455. } else {
  8456. ggml_backend_tensor_copy(model_t, base_t);
  8457. }
  8458. if (ggml_is_quantized(base_t->type) && !warned) {
  8459. LLAMA_LOG_WARN("%s: warning: using a lora adapter with a quantized model may result in poor quality, "
  8460. "use a f16 or f32 base model with --lora-base\n", __func__);
  8461. warned = true;
  8462. }
  8463. if (base_t->ne[0] != loraA->ne[1] || base_t->ne[1] != loraB->ne[1]) {
  8464. LLAMA_LOG_ERROR("%s: incompatible tensor dimensions (%" PRId64 " and %" PRId64 ");"
  8465. " are you sure that this adapter is for this model?\n", __func__, base_t->ne[0], loraA->ne[1]);
  8466. ggml_free(lora_ctx);
  8467. ggml_backend_buffer_free(lora_buf);
  8468. ggml_backend_free(backend_cpu);
  8469. return 1;
  8470. }
  8471. auto build_lora_graph = [&]() {
  8472. // w = w + BA*s
  8473. ggml_tensor * BA = ggml_mul_mat(lora_ctx, loraA, loraB);
  8474. ggml_set_name(BA, "BA");
  8475. if (scaling != 1.0f) {
  8476. BA = ggml_scale(lora_ctx, BA, scaling);
  8477. ggml_set_name(BA, "BA_scaled");
  8478. }
  8479. ggml_tensor * r;
  8480. r = ggml_add_inplace(lora_ctx, base_t, BA);
  8481. ggml_set_name(r, "r_add");
  8482. if (base_t->type != model_t->type) {
  8483. // convert the result to the model type
  8484. r = ggml_cast(lora_ctx, r, model_t->type);
  8485. ggml_set_name(r, "r_cast");
  8486. }
  8487. return r;
  8488. };
  8489. ggml_cgraph * gf = ggml_new_graph(lora_ctx);
  8490. ggml_tensor * r = build_lora_graph();
  8491. ggml_build_forward_expand(gf, r);
  8492. ggml_backend_buffer_t graph_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  8493. if (graph_buf == nullptr) {
  8494. LLAMA_LOG_ERROR("%s: error: failed to allocate graph tensors\n", __func__);
  8495. ggml_free(lora_ctx);
  8496. ggml_backend_buffer_free(lora_buf);
  8497. ggml_backend_free(backend_cpu);
  8498. return 1;
  8499. }
  8500. ggml_backend_graph_compute(backend_cpu, gf);
  8501. ggml_backend_tensor_set(model_t, r->data, 0, ggml_nbytes(r));
  8502. #if 0
  8503. // TODO: use scheduler with fallback to CPU for less copies between CPU and GPU
  8504. //ggml_backend_sched_t sched = ggml_backend_sched_new(backends.data(), backends.size(), GGML_DEFAULT_GRAPH_SIZE);
  8505. // sched compute
  8506. ggml_build_forward_expand(gf, build_graph());
  8507. ggml_backend_sched_init_measure(sched, gf);
  8508. // create the graph again, since the previous one was destroyed by the measure
  8509. ggml_graph_clear(gf);
  8510. ggml_build_forward_expand(gf, build_graph());
  8511. ggml_backend_sched_graph_compute(sched, gf);
  8512. ggml_backend_sched_free(sched);
  8513. #endif
  8514. ggml_backend_buffer_free(lora_buf);
  8515. ggml_backend_buffer_free(graph_buf);
  8516. ggml_free(lora_ctx);
  8517. n_tensors++;
  8518. if (n_tensors % 4 == 0) {
  8519. LLAMA_LOG_INFO(".");
  8520. }
  8521. }
  8522. ggml_backend_free(backend_cpu);
  8523. const int64_t t_lora_us = ggml_time_us() - t_start_lora_us;
  8524. LLAMA_LOG_INFO(" done (%.2f ms)\n", t_lora_us / 1000.0);
  8525. return 0;
  8526. }
  8527. //
  8528. // interface implementation
  8529. //
  8530. struct llama_model_params llama_model_default_params() {
  8531. struct llama_model_params result = {
  8532. /*.n_gpu_layers =*/ 0,
  8533. /*.split_mode =*/ LLAMA_SPLIT_LAYER,
  8534. /*.main_gpu =*/ 0,
  8535. /*.tensor_split =*/ nullptr,
  8536. /*.progress_callback =*/ nullptr,
  8537. /*.progress_callback_user_data =*/ nullptr,
  8538. /*.kv_overrides =*/ nullptr,
  8539. /*.vocab_only =*/ false,
  8540. /*.use_mmap =*/ true,
  8541. /*.use_mlock =*/ false,
  8542. };
  8543. #ifdef GGML_USE_METAL
  8544. // note: we usually have plenty of VRAM, so by default offload all layers to the GPU
  8545. result.n_gpu_layers = 999;
  8546. #endif
  8547. return result;
  8548. }
  8549. struct llama_context_params llama_context_default_params() {
  8550. struct llama_context_params result = {
  8551. /*.seed =*/ LLAMA_DEFAULT_SEED,
  8552. /*.n_ctx =*/ 512,
  8553. /*.n_batch =*/ 512,
  8554. /*.n_threads =*/ GGML_DEFAULT_N_THREADS, // TODO: better default
  8555. /*.n_threads_batch =*/ GGML_DEFAULT_N_THREADS,
  8556. /*.rope_scaling_type =*/ LLAMA_ROPE_SCALING_UNSPECIFIED,
  8557. /*.rope_freq_base =*/ 0.0f,
  8558. /*.rope_freq_scale =*/ 0.0f,
  8559. /*.yarn_ext_factor =*/ -1.0f,
  8560. /*.yarn_attn_factor =*/ 1.0f,
  8561. /*.yarn_beta_fast =*/ 32.0f,
  8562. /*.yarn_beta_slow =*/ 1.0f,
  8563. /*.yarn_orig_ctx =*/ 0,
  8564. /*.cb_eval =*/ nullptr,
  8565. /*.cb_eval_user_data =*/ nullptr,
  8566. /*.type_k =*/ GGML_TYPE_F16,
  8567. /*.type_v =*/ GGML_TYPE_F16,
  8568. /*.mul_mat_q =*/ true,
  8569. /*.logits_all =*/ false,
  8570. /*.embedding =*/ false,
  8571. /*.offload_kqv =*/ true,
  8572. };
  8573. return result;
  8574. }
  8575. struct llama_model_quantize_params llama_model_quantize_default_params() {
  8576. struct llama_model_quantize_params result = {
  8577. /*.nthread =*/ 0,
  8578. /*.ftype =*/ LLAMA_FTYPE_MOSTLY_Q5_1,
  8579. /*.allow_requantize =*/ false,
  8580. /*.quantize_output_tensor =*/ true,
  8581. /*.only_copy =*/ false,
  8582. /*.pure =*/ false,
  8583. /*.imatrix =*/ nullptr,
  8584. };
  8585. return result;
  8586. }
  8587. size_t llama_max_devices(void) {
  8588. #if defined(GGML_USE_METAL)
  8589. return 1;
  8590. #elif defined(GGML_USE_CUBLAS)
  8591. return GGML_CUDA_MAX_DEVICES;
  8592. #elif defined(GGML_USE_SYCL)
  8593. return GGML_SYCL_MAX_DEVICES;
  8594. #else
  8595. return 1;
  8596. #endif
  8597. }
  8598. bool llama_supports_mmap(void) {
  8599. return llama_mmap::SUPPORTED;
  8600. }
  8601. bool llama_supports_mlock(void) {
  8602. return llama_mlock::SUPPORTED;
  8603. }
  8604. bool llama_supports_gpu_offload(void) {
  8605. #if defined(GGML_USE_CUBLAS) || defined(GGML_USE_CLBLAST) || defined(GGML_USE_METAL) || defined(GGML_USE_VULKAN) || \
  8606. defined(GGML_USE_SYCL) || defined(GGML_USE_KOMPUTE)
  8607. // Defined when llama.cpp is compiled with support for offloading model layers to GPU.
  8608. return true;
  8609. #else
  8610. return false;
  8611. #endif
  8612. }
  8613. // deprecated:
  8614. bool llama_mmap_supported(void) {
  8615. return llama_supports_mmap();
  8616. }
  8617. bool llama_mlock_supported(void) {
  8618. return llama_supports_mlock();
  8619. }
  8620. void llama_backend_init(bool numa) {
  8621. ggml_time_init();
  8622. // needed to initialize f16 tables
  8623. {
  8624. struct ggml_init_params params = { 0, NULL, false };
  8625. struct ggml_context * ctx = ggml_init(params);
  8626. ggml_free(ctx);
  8627. }
  8628. if (numa) {
  8629. ggml_numa_init();
  8630. }
  8631. #ifdef GGML_USE_MPI
  8632. ggml_mpi_backend_init();
  8633. #endif
  8634. }
  8635. void llama_backend_free(void) {
  8636. #ifdef GGML_USE_MPI
  8637. ggml_mpi_backend_free();
  8638. #endif
  8639. ggml_quantize_free();
  8640. }
  8641. int64_t llama_time_us(void) {
  8642. return ggml_time_us();
  8643. }
  8644. struct llama_model * llama_load_model_from_file(
  8645. const char * path_model,
  8646. struct llama_model_params params) {
  8647. ggml_time_init();
  8648. llama_model * model = new llama_model;
  8649. unsigned cur_percentage = 0;
  8650. if (params.progress_callback == NULL) {
  8651. params.progress_callback_user_data = &cur_percentage;
  8652. params.progress_callback = [](float progress, void * ctx) {
  8653. unsigned * cur_percentage_p = (unsigned *) ctx;
  8654. unsigned percentage = (unsigned) (100 * progress);
  8655. while (percentage > *cur_percentage_p) {
  8656. *cur_percentage_p = percentage;
  8657. LLAMA_LOG_INFO(".");
  8658. if (percentage >= 100) {
  8659. LLAMA_LOG_INFO("\n");
  8660. }
  8661. }
  8662. return true;
  8663. };
  8664. }
  8665. int status = llama_model_load(path_model, *model, params);
  8666. GGML_ASSERT(status <= 0);
  8667. if (status < 0) {
  8668. if (status == -1) {
  8669. LLAMA_LOG_ERROR("%s: failed to load model\n", __func__);
  8670. } else if (status == -2) {
  8671. LLAMA_LOG_INFO("%s: cancelled model load\n", __func__);
  8672. }
  8673. delete model;
  8674. return nullptr;
  8675. }
  8676. return model;
  8677. }
  8678. void llama_free_model(struct llama_model * model) {
  8679. delete model;
  8680. }
  8681. struct llama_context * llama_new_context_with_model(
  8682. struct llama_model * model,
  8683. struct llama_context_params params) {
  8684. if (!model) {
  8685. return nullptr;
  8686. }
  8687. llama_context * ctx = new llama_context(*model);
  8688. const auto & hparams = model->hparams;
  8689. auto & cparams = ctx->cparams;
  8690. cparams.n_batch = params.n_batch;
  8691. cparams.n_threads = params.n_threads;
  8692. cparams.n_threads_batch = params.n_threads_batch;
  8693. cparams.yarn_ext_factor = params.yarn_ext_factor;
  8694. cparams.yarn_attn_factor = params.yarn_attn_factor;
  8695. cparams.yarn_beta_fast = params.yarn_beta_fast;
  8696. cparams.yarn_beta_slow = params.yarn_beta_slow;
  8697. cparams.mul_mat_q = params.mul_mat_q;
  8698. cparams.offload_kqv = params.offload_kqv;
  8699. cparams.n_ctx = params.n_ctx == 0 ? hparams.n_ctx_train : params.n_ctx;
  8700. cparams.rope_freq_base = params.rope_freq_base == 0.0f ? hparams.rope_freq_base_train : params.rope_freq_base;
  8701. cparams.rope_freq_scale = params.rope_freq_scale == 0.0f ? hparams.rope_freq_scale_train : params.rope_freq_scale;
  8702. cparams.n_yarn_orig_ctx = params.yarn_orig_ctx != 0 ? params.yarn_orig_ctx :
  8703. hparams.n_yarn_orig_ctx != 0 ? hparams.n_yarn_orig_ctx :
  8704. hparams.n_ctx_train;
  8705. cparams.cb_eval = params.cb_eval;
  8706. cparams.cb_eval_user_data = params.cb_eval_user_data;
  8707. auto rope_scaling_type = params.rope_scaling_type;
  8708. if (rope_scaling_type == LLAMA_ROPE_SCALING_UNSPECIFIED) {
  8709. rope_scaling_type = hparams.rope_scaling_type_train;
  8710. }
  8711. if (rope_scaling_type == LLAMA_ROPE_SCALING_NONE) {
  8712. cparams.rope_freq_scale = 1.0f; // never scale if scaling type is none
  8713. }
  8714. if (cparams.yarn_ext_factor < 0.0f) { // negative indicates 'not set'
  8715. cparams.yarn_ext_factor = rope_scaling_type == LLAMA_ROPE_SCALING_YARN ? 1.0f : 0.0f;
  8716. }
  8717. if (params.seed == LLAMA_DEFAULT_SEED) {
  8718. params.seed = time(NULL);
  8719. }
  8720. LLAMA_LOG_INFO("%s: n_ctx = %u\n", __func__, cparams.n_ctx);
  8721. LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, cparams.rope_freq_base);
  8722. LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, cparams.rope_freq_scale);
  8723. ctx->rng = std::mt19937(params.seed);
  8724. ctx->logits_all = params.logits_all;
  8725. const ggml_type type_k = params.type_k;
  8726. const ggml_type type_v = params.type_v;
  8727. GGML_ASSERT(hparams.n_embd_head_k % ggml_blck_size(type_k) == 0);
  8728. GGML_ASSERT(hparams.n_embd_head_v % ggml_blck_size(type_v) == 0);
  8729. if (!hparams.vocab_only) {
  8730. // initialize backends
  8731. #ifdef GGML_USE_METAL
  8732. if (model->n_gpu_layers > 0) {
  8733. ctx->backend_metal = ggml_backend_metal_init();
  8734. if (ctx->backend_metal == nullptr) {
  8735. LLAMA_LOG_ERROR("%s: failed to initialize Metal backend\n", __func__);
  8736. llama_free(ctx);
  8737. return nullptr;
  8738. }
  8739. ctx->backends.push_back(ctx->backend_metal);
  8740. }
  8741. #elif defined(GGML_USE_CUBLAS)
  8742. if (model->n_gpu_layers > 0) {
  8743. // with split_mode LLAMA_SPLIT_NONE or LLAMA_SPLIT_ROW, only the main GPU backend is used
  8744. if (model->split_mode == LLAMA_SPLIT_NONE || model->split_mode == LLAMA_SPLIT_ROW) {
  8745. ggml_backend_t backend = ggml_backend_cuda_init(model->main_gpu);
  8746. if (backend == nullptr) {
  8747. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, model->main_gpu);
  8748. llama_free(ctx);
  8749. return nullptr;
  8750. }
  8751. ctx->backends.push_back(backend);
  8752. } else {
  8753. // LLAMA_SPLIT_LAYER requires a backend for each GPU
  8754. for (int device = 0; device < ggml_backend_cuda_get_device_count(); ++device) {
  8755. ggml_backend_t backend = ggml_backend_cuda_init(device);
  8756. if (backend == nullptr) {
  8757. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, device);
  8758. llama_free(ctx);
  8759. return nullptr;
  8760. }
  8761. ctx->backends.push_back(backend);
  8762. }
  8763. }
  8764. }
  8765. #elif defined(GGML_USE_VULKAN)
  8766. if (model->n_gpu_layers > 0) {
  8767. ggml_backend_t backend = ggml_backend_vk_init();
  8768. if (backend == nullptr) {
  8769. LLAMA_LOG_ERROR("%s: failed to initialize Vulkan backend\n", __func__);
  8770. llama_free(ctx);
  8771. return nullptr;
  8772. }
  8773. ctx->backends.push_back(backend);
  8774. }
  8775. #elif defined(GGML_USE_SYCL)
  8776. if (model->n_gpu_layers > 0) {
  8777. ggml_backend_t backend = ggml_backend_sycl_init(model->main_gpu);
  8778. if (backend == nullptr) {
  8779. LLAMA_LOG_ERROR("%s: failed to initialize SYCL%d backend\n", __func__, model->main_gpu);
  8780. llama_free(ctx);
  8781. return nullptr;
  8782. }
  8783. ctx->backends.push_back(backend);
  8784. }
  8785. #elif defined(GGML_USE_KOMPUTE)
  8786. if (model->n_gpu_layers > 0) {
  8787. auto * backend = ggml_backend_kompute_init(model->main_gpu);
  8788. if (backend == nullptr) {
  8789. LLAMA_LOG_ERROR("%s: failed to initialize Kompute backend\n", __func__);
  8790. llama_free(ctx);
  8791. return nullptr;
  8792. }
  8793. ctx->backends.push_back(backend);
  8794. }
  8795. #endif
  8796. ctx->backend_cpu = ggml_backend_cpu_init();
  8797. if (ctx->backend_cpu == nullptr) {
  8798. LLAMA_LOG_ERROR("%s: failed to initialize CPU backend\n", __func__);
  8799. llama_free(ctx);
  8800. return nullptr;
  8801. }
  8802. ctx->backends.push_back(ctx->backend_cpu);
  8803. if (!llama_kv_cache_init(ctx->kv_self, ctx->model, type_k, type_v,
  8804. cparams.n_ctx, cparams.offload_kqv)) {
  8805. LLAMA_LOG_ERROR("%s: llama_kv_cache_init() failed for self-attention cache\n", __func__);
  8806. llama_free(ctx);
  8807. return nullptr;
  8808. }
  8809. {
  8810. size_t memory_size_k = 0;
  8811. size_t memory_size_v = 0;
  8812. for (auto & k : ctx->kv_self.k_l) {
  8813. memory_size_k += ggml_nbytes(k);
  8814. }
  8815. for (auto & v : ctx->kv_self.v_l) {
  8816. memory_size_v += ggml_nbytes(v);
  8817. }
  8818. LLAMA_LOG_INFO("%s: KV self size = %7.2f MiB, K (%s): %7.2f MiB, V (%s): %7.2f MiB\n", __func__,
  8819. (float)(memory_size_k + memory_size_v) / (1024.0f * 1024.0f),
  8820. ggml_type_name(type_k), (float)memory_size_k / (1024.0f * 1024.0f),
  8821. ggml_type_name(type_v), (float)memory_size_v / (1024.0f * 1024.0f));
  8822. }
  8823. // resized during inference, reserve maximum
  8824. ctx->logits.reserve(hparams.n_vocab*cparams.n_batch);
  8825. if (params.embedding){
  8826. ctx->embedding.resize(hparams.n_embd);
  8827. }
  8828. // graph inputs
  8829. {
  8830. ggml_init_params init_params = {
  8831. /* .mem_size */ ggml_tensor_overhead()*5,
  8832. /* .mem_buffer */ nullptr,
  8833. /* .no_alloc */ true,
  8834. };
  8835. ctx->ctx_input = ggml_init(init_params);
  8836. ctx->inp_tokens = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_I32, cparams.n_batch);
  8837. ctx->inp_embd = ggml_new_tensor_2d(ctx->ctx_input, GGML_TYPE_F32, hparams.n_embd, cparams.n_batch);
  8838. ctx->inp_pos = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_I32, cparams.n_batch);
  8839. ctx->inp_KQ_mask = ggml_new_tensor_2d(ctx->ctx_input, GGML_TYPE_F32, cparams.n_ctx, cparams.n_batch);
  8840. ctx->inp_K_shift = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_I32, cparams.n_ctx);
  8841. ggml_set_name(ctx->inp_tokens, "inp_tokens");
  8842. ggml_set_name(ctx->inp_embd, "inp_embd");
  8843. ggml_set_name(ctx->inp_pos, "inp_pos");
  8844. ggml_set_name(ctx->inp_KQ_mask, "inp_KQ_mask");
  8845. ggml_set_name(ctx->inp_K_shift, "inp_K_shift");
  8846. ctx->buf_input = ggml_backend_alloc_ctx_tensors_from_buft(ctx->ctx_input, llama_default_buffer_type_cpu(true));
  8847. LLAMA_LOG_INFO("%s: %10s input buffer size = %8.2f MiB\n", __func__,
  8848. ggml_backend_buffer_name(ctx->buf_input),
  8849. ggml_backend_buffer_get_size(ctx->buf_input) / 1024.0 / 1024.0);
  8850. }
  8851. // scheduler and compute buffers
  8852. {
  8853. // buffer types used for the compute buffer of each backend
  8854. std::vector<ggml_backend_buffer_type_t> backend_buft;
  8855. for (auto * backend : ctx->backends) {
  8856. if (ggml_backend_is_cpu(backend)) {
  8857. // use host buffers for the CPU backend compute buffer
  8858. backend_buft.push_back(llama_default_buffer_type_cpu(true));
  8859. } else {
  8860. backend_buft.push_back(ggml_backend_get_default_buffer_type(backend));
  8861. }
  8862. }
  8863. // buffer used to store the computation graph and the tensor meta data
  8864. ctx->buf_compute_meta.resize(ggml_tensor_overhead()*LLAMA_MAX_NODES + ggml_graph_overhead());
  8865. ctx->sched = ggml_backend_sched_new(ctx->backends.data(), backend_buft.data(), ctx->backends.size(), LLAMA_MAX_NODES);
  8866. ctx->alloc = ggml_backend_sched_get_tallocr(ctx->sched, ctx->backend_cpu);
  8867. // build worst-case graph
  8868. int n_tokens = (int)std::min(cparams.n_ctx, cparams.n_batch);
  8869. int n_past = cparams.n_ctx - n_tokens;
  8870. 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
  8871. ggml_cgraph * gf = llama_build_graph(*ctx, llama_batch_get_one(&token, n_tokens, n_past, 0));
  8872. // initialize scheduler with the worst-case graph
  8873. ggml_backend_sched_init_measure(ctx->sched, gf);
  8874. ctx->alloc = ggml_backend_sched_get_tallocr(ctx->sched, ctx->backend_cpu);
  8875. for (ggml_backend_t backend : ctx->backends) {
  8876. ggml_backend_buffer_t buf = ggml_backend_sched_get_buffer(ctx->sched, backend);
  8877. LLAMA_LOG_INFO("%s: %10s compute buffer size = %8.2f MiB\n", __func__,
  8878. ggml_backend_buffer_name(buf),
  8879. ggml_backend_buffer_get_size(buf) / 1024.0 / 1024.0);
  8880. }
  8881. // note: the number of splits during measure is higher than during inference due to the kv shift
  8882. int n_splits = ggml_backend_sched_get_n_splits(ctx->sched);
  8883. LLAMA_LOG_INFO("%s: graph splits (measure): %d\n", __func__, n_splits);
  8884. }
  8885. }
  8886. #ifdef GGML_USE_MPI
  8887. ctx->ctx_mpi = ggml_mpi_init();
  8888. if (ggml_mpi_rank(ctx->ctx_mpi) > 0) {
  8889. // Enter a blocking eval loop with dummy input, letting rank=0 drive the process
  8890. // TODO: needs fix after #3228
  8891. GGML_ASSERT(false && "not implemented");
  8892. //const std::vector<llama_token> tmp(ctx->model.hparams.n_ctx, llama_token_bos(ctx));
  8893. //while (!llama_eval(ctx, tmp.data(), tmp.size(), 0, 0)) {};
  8894. llama_backend_free();
  8895. exit(1);
  8896. }
  8897. #endif
  8898. return ctx;
  8899. }
  8900. void llama_free(struct llama_context * ctx) {
  8901. delete ctx;
  8902. }
  8903. const llama_model * llama_get_model(const struct llama_context * ctx) {
  8904. return &ctx->model;
  8905. }
  8906. uint32_t llama_n_ctx(const struct llama_context * ctx) {
  8907. return ctx->cparams.n_ctx;
  8908. }
  8909. uint32_t llama_n_batch(const struct llama_context * ctx) {
  8910. return ctx->cparams.n_batch;
  8911. }
  8912. enum llama_vocab_type llama_vocab_type(const struct llama_model * model) {
  8913. return model->vocab.type;
  8914. }
  8915. int32_t llama_n_vocab(const struct llama_model * model) {
  8916. return model->vocab.id_to_token.size();
  8917. }
  8918. int32_t llama_n_ctx_train(const struct llama_model * model) {
  8919. return model->hparams.n_ctx_train;
  8920. }
  8921. int32_t llama_n_embd(const struct llama_model * model) {
  8922. return model->hparams.n_embd;
  8923. }
  8924. float llama_rope_freq_scale_train(const struct llama_model * model) {
  8925. return model->hparams.rope_freq_scale_train;
  8926. }
  8927. int32_t llama_model_meta_val_str(const struct llama_model * model, const char * key, char * buf, size_t buf_size) {
  8928. const auto & it = model->gguf_kv.find(key);
  8929. if (it == model->gguf_kv.end()) {
  8930. if (buf_size > 0) {
  8931. buf[0] = '\0';
  8932. }
  8933. return -1;
  8934. }
  8935. return snprintf(buf, buf_size, "%s", it->second.c_str());
  8936. }
  8937. int32_t llama_model_meta_count(const struct llama_model * model) {
  8938. return (int)model->gguf_kv.size();
  8939. }
  8940. int32_t llama_model_meta_key_by_index(const struct llama_model * model, int i, char * buf, size_t buf_size) {
  8941. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  8942. if (buf_size > 0) {
  8943. buf[0] = '\0';
  8944. }
  8945. return -1;
  8946. }
  8947. auto it = model->gguf_kv.begin();
  8948. std::advance(it, i);
  8949. return snprintf(buf, buf_size, "%s", it->first.c_str());
  8950. }
  8951. int32_t llama_model_meta_val_str_by_index(const struct llama_model * model, int32_t i, char * buf, size_t buf_size) {
  8952. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  8953. if (buf_size > 0) {
  8954. buf[0] = '\0';
  8955. }
  8956. return -1;
  8957. }
  8958. auto it = model->gguf_kv.begin();
  8959. std::advance(it, i);
  8960. return snprintf(buf, buf_size, "%s", it->second.c_str());
  8961. }
  8962. int32_t llama_model_desc(const struct llama_model * model, char * buf, size_t buf_size) {
  8963. return snprintf(buf, buf_size, "%s %s %s",
  8964. llama_model_arch_name(model->arch),
  8965. llama_model_type_name(model->type),
  8966. llama_model_ftype_name(model->ftype).c_str());
  8967. }
  8968. uint64_t llama_model_size(const struct llama_model * model) {
  8969. uint64_t size = 0;
  8970. for (const auto & it : model->tensors_by_name) {
  8971. size += ggml_nbytes(it.second);
  8972. }
  8973. return size;
  8974. }
  8975. uint64_t llama_model_n_params(const struct llama_model * model) {
  8976. uint64_t nparams = 0;
  8977. for (const auto & it : model->tensors_by_name) {
  8978. nparams += ggml_nelements(it.second);
  8979. }
  8980. return nparams;
  8981. }
  8982. struct ggml_tensor * llama_get_model_tensor(struct llama_model * model, const char * name) {
  8983. auto it = std::find_if(model->tensors_by_name.begin(), model->tensors_by_name.end(),
  8984. [name](const std::pair<std::string, struct ggml_tensor *> & it) {
  8985. return it.first == name;
  8986. });
  8987. if (it == model->tensors_by_name.end()) {
  8988. return nullptr;
  8989. }
  8990. return it->second;
  8991. }
  8992. uint32_t llama_model_quantize(
  8993. const char * fname_inp,
  8994. const char * fname_out,
  8995. const llama_model_quantize_params * params) {
  8996. try {
  8997. llama_model_quantize_internal(fname_inp, fname_out, params);
  8998. return 0;
  8999. } catch (const std::exception & err) {
  9000. LLAMA_LOG_ERROR("%s: failed to quantize: %s\n", __func__, err.what());
  9001. return 1;
  9002. }
  9003. }
  9004. int32_t llama_apply_lora_from_file(struct llama_context * ctx, const char * path_lora, float scale, const char * path_base_model, int32_t n_threads) {
  9005. try {
  9006. return llama_apply_lora_from_file_internal(ctx->model, path_lora, scale, path_base_model, n_threads);
  9007. } catch (const std::exception & err) {
  9008. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  9009. return 1;
  9010. }
  9011. }
  9012. 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) {
  9013. try {
  9014. return llama_apply_lora_from_file_internal(*model, path_lora, scale, path_base_model, n_threads);
  9015. } catch (const std::exception & err) {
  9016. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  9017. return 1;
  9018. }
  9019. }
  9020. struct llama_kv_cache_view llama_kv_cache_view_init(const struct llama_context * ctx, int32_t n_max_seq) {
  9021. struct llama_kv_cache_view result = {
  9022. /*.n_cells = */ 0,
  9023. /*.n_max_seq = */ n_max_seq,
  9024. /*.token_count = */ 0,
  9025. /*.used_cells = */ llama_get_kv_cache_used_cells(ctx),
  9026. /*.max_contiguous = */ 0,
  9027. /*.max_contiguous_idx = */ -1,
  9028. /*.cells = */ nullptr,
  9029. /*.cells_sequences = */ nullptr,
  9030. };
  9031. return result;
  9032. }
  9033. void llama_kv_cache_view_free(struct llama_kv_cache_view * view) {
  9034. if (view->cells != nullptr) {
  9035. free(view->cells);
  9036. view->cells = nullptr;
  9037. }
  9038. if (view->cells_sequences != nullptr) {
  9039. free(view->cells_sequences);
  9040. view->cells_sequences = nullptr;
  9041. }
  9042. }
  9043. void llama_kv_cache_view_update(const struct llama_context * ctx, struct llama_kv_cache_view * view) {
  9044. if (uint32_t(view->n_cells) < ctx->kv_self.size || view->cells == nullptr) {
  9045. view->n_cells = int32_t(ctx->kv_self.size);
  9046. void * p = realloc(view->cells, sizeof(struct llama_kv_cache_view_cell) * view->n_cells);
  9047. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells");
  9048. view->cells = (struct llama_kv_cache_view_cell *)p;
  9049. p = realloc(view->cells_sequences, sizeof(llama_seq_id) * view->n_max_seq * view->n_cells);
  9050. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells sequences");
  9051. view->cells_sequences = (llama_seq_id *)p;
  9052. }
  9053. const std::vector<llama_kv_cell> & kv_cells = ctx->kv_self.cells;
  9054. llama_kv_cache_view_cell * c_curr = view->cells;
  9055. llama_seq_id * cs_curr = view->cells_sequences;
  9056. int32_t used_cells = 0;
  9057. int32_t token_count = 0;
  9058. int32_t curr_contig_idx = -1;
  9059. uint32_t max_contig = 0;
  9060. int32_t max_contig_idx = -1;
  9061. for (int32_t i = 0; i < int32_t(ctx->kv_self.size); i++, c_curr++, cs_curr += view->n_max_seq) {
  9062. const size_t curr_size = kv_cells[i].seq_id.size();
  9063. token_count += curr_size;
  9064. c_curr->pos = kv_cells[i].pos + kv_cells[i].delta;
  9065. if (curr_size > 0) {
  9066. if (curr_contig_idx >= 0 && uint32_t(i - curr_contig_idx) > max_contig) {
  9067. max_contig = i - curr_contig_idx;
  9068. max_contig_idx = curr_contig_idx;
  9069. }
  9070. curr_contig_idx = -1;
  9071. } else if (curr_contig_idx < 0) {
  9072. curr_contig_idx = i;
  9073. }
  9074. int seq_idx = 0;
  9075. for (const llama_seq_id it : kv_cells[i].seq_id) {
  9076. if (seq_idx >= view->n_max_seq) {
  9077. break;
  9078. }
  9079. cs_curr[seq_idx] = it;
  9080. seq_idx++;
  9081. }
  9082. if (seq_idx != 0) {
  9083. used_cells++;
  9084. }
  9085. for (; seq_idx < view->n_max_seq; seq_idx++) {
  9086. cs_curr[seq_idx] = -1;
  9087. }
  9088. }
  9089. if (curr_contig_idx >= 0 && kv_cells.size() - curr_contig_idx > max_contig) {
  9090. max_contig_idx = curr_contig_idx;
  9091. max_contig = kv_cells.size() - curr_contig_idx;
  9092. }
  9093. view->max_contiguous = max_contig;
  9094. view->max_contiguous_idx = max_contig_idx;
  9095. view->token_count = token_count;
  9096. view->used_cells = used_cells;
  9097. if (uint32_t(used_cells) != ctx->kv_self.used) {
  9098. LLAMA_LOG_ERROR("%s: used cells mismatch. kv_cache says %d but we calculated %d\n",
  9099. __func__, ctx->kv_self.used, used_cells);
  9100. }
  9101. }
  9102. int32_t llama_get_kv_cache_token_count(const struct llama_context * ctx) {
  9103. int result = 0;
  9104. for (uint32_t i = 0; i < ctx->kv_self.size; i++) {
  9105. result += ctx->kv_self.cells[i].seq_id.size();
  9106. }
  9107. return result;
  9108. }
  9109. int32_t llama_get_kv_cache_used_cells(const struct llama_context * ctx) {
  9110. return ctx->kv_self.used;
  9111. }
  9112. void llama_kv_cache_clear(struct llama_context * ctx) {
  9113. llama_kv_cache_clear(ctx->kv_self);
  9114. }
  9115. void llama_kv_cache_seq_rm(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
  9116. llama_kv_cache_seq_rm(ctx->kv_self, seq_id, p0, p1);
  9117. }
  9118. 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) {
  9119. if (seq_id_src == seq_id_dst) {
  9120. return;
  9121. }
  9122. llama_kv_cache_seq_cp(ctx->kv_self, seq_id_src, seq_id_dst, p0, p1);
  9123. }
  9124. void llama_kv_cache_seq_keep(struct llama_context * ctx, llama_seq_id seq_id) {
  9125. llama_kv_cache_seq_keep(ctx->kv_self, seq_id);
  9126. }
  9127. void llama_kv_cache_seq_shift(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos delta) {
  9128. if (delta == 0) {
  9129. return;
  9130. }
  9131. llama_kv_cache_seq_shift(ctx->kv_self, seq_id, p0, p1, delta);
  9132. }
  9133. void llama_kv_cache_seq_div(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) {
  9134. if (d == 1) {
  9135. return;
  9136. }
  9137. llama_kv_cache_seq_div(ctx->kv_self, seq_id, p0, p1, d);
  9138. }
  9139. // Returns the *maximum* size of the state
  9140. size_t llama_get_state_size(const struct llama_context * ctx) {
  9141. // we don't know size of rng until we actually serialize it. so reserve more than enough memory for its serialized state.
  9142. // for reference, std::mt19937(1337) serializes to 6701 bytes.
  9143. const size_t s_rng_size = sizeof(size_t);
  9144. const size_t s_rng = LLAMA_MAX_RNG_STATE;
  9145. const size_t s_logits_size = sizeof(size_t);
  9146. // assume worst case for logits although only currently set ones are serialized
  9147. const size_t s_logits = ctx->logits.capacity() * sizeof(float);
  9148. const size_t s_embedding_size = sizeof(size_t);
  9149. const size_t s_embedding = ctx->embedding.size() * sizeof(float);
  9150. const size_t s_kv_size = sizeof(size_t);
  9151. const size_t s_kv_ntok = sizeof(int);
  9152. const size_t s_kv = ctx->kv_self.total_size();
  9153. const size_t s_total = (
  9154. + s_rng_size
  9155. + s_rng
  9156. + s_logits_size
  9157. + s_logits
  9158. + s_embedding_size
  9159. + s_embedding
  9160. + s_kv_size
  9161. + s_kv_ntok
  9162. + s_kv
  9163. );
  9164. return s_total;
  9165. }
  9166. // llama_context_data
  9167. struct llama_data_context {
  9168. virtual void write(const void * src, size_t size) = 0;
  9169. virtual size_t get_size_written() = 0;
  9170. virtual ~llama_data_context() = default;
  9171. };
  9172. struct llama_data_buffer_context : llama_data_context {
  9173. uint8_t * ptr;
  9174. size_t size_written = 0;
  9175. llama_data_buffer_context(uint8_t * p) : ptr(p) {}
  9176. void write(const void * src, size_t size) override {
  9177. memcpy(ptr, src, size);
  9178. ptr += size;
  9179. size_written += size;
  9180. }
  9181. size_t get_size_written() override {
  9182. return size_written;
  9183. }
  9184. };
  9185. struct llama_data_file_context : llama_data_context {
  9186. llama_file * file;
  9187. size_t size_written = 0;
  9188. llama_data_file_context(llama_file * f) : file(f) {}
  9189. void write(const void * src, size_t size) override {
  9190. file->write_raw(src, size);
  9191. size_written += size;
  9192. }
  9193. size_t get_size_written() override {
  9194. return size_written;
  9195. }
  9196. };
  9197. /** copy state data into either a buffer or file depending on the passed in context
  9198. *
  9199. * file context:
  9200. * llama_file file("/path", "wb");
  9201. * llama_data_file_context data_ctx(&file);
  9202. * llama_copy_state_data(ctx, &data_ctx);
  9203. *
  9204. * buffer context:
  9205. * std::vector<uint8_t> buf(max_size, 0);
  9206. * llama_data_buffer_context data_ctx(&buf.data());
  9207. * llama_copy_state_data(ctx, &data_ctx);
  9208. *
  9209. */
  9210. static void llama_copy_state_data_internal(struct llama_context * ctx, llama_data_context * data_ctx) {
  9211. // copy rng
  9212. {
  9213. std::ostringstream rng_ss;
  9214. rng_ss << ctx->rng;
  9215. const std::string & rng_str = rng_ss.str();
  9216. const size_t rng_size = rng_str.size();
  9217. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  9218. data_ctx->write(&rng_size, sizeof(rng_size));
  9219. data_ctx->write(rng_str.data(), rng_size);
  9220. }
  9221. // copy logits
  9222. {
  9223. const size_t logits_size = ctx->logits.size();
  9224. data_ctx->write(&logits_size, sizeof(logits_size));
  9225. if (logits_size) {
  9226. data_ctx->write(ctx->logits.data(), logits_size * sizeof(float));
  9227. }
  9228. }
  9229. // copy embeddings
  9230. {
  9231. const size_t embedding_size = ctx->embedding.size();
  9232. data_ctx->write(&embedding_size, sizeof(embedding_size));
  9233. if (embedding_size) {
  9234. data_ctx->write(ctx->embedding.data(), embedding_size * sizeof(float));
  9235. }
  9236. }
  9237. // copy kv cache
  9238. {
  9239. const auto & kv_self = ctx->kv_self;
  9240. const auto & hparams = ctx->model.hparams;
  9241. const auto & cparams = ctx->cparams;
  9242. const auto n_layer = hparams.n_layer;
  9243. const auto n_embd_k_gqa = hparams.n_embd_k_gqa();
  9244. const auto n_embd_v_gqa = hparams.n_embd_v_gqa();
  9245. const auto n_ctx = cparams.n_ctx;
  9246. const size_t kv_buf_size = kv_self.total_size();
  9247. const uint32_t kv_head = kv_self.head;
  9248. const uint32_t kv_size = kv_self.size;
  9249. const uint32_t kv_used = kv_self.used;
  9250. data_ctx->write(&kv_buf_size, sizeof(kv_buf_size));
  9251. data_ctx->write(&kv_head, sizeof(kv_head));
  9252. data_ctx->write(&kv_size, sizeof(kv_size));
  9253. data_ctx->write(&kv_used, sizeof(kv_used));
  9254. if (kv_buf_size) {
  9255. const size_t elt_size = ggml_element_size(kv_self.k_l[0]);
  9256. std::vector<uint8_t> tmp_buf;
  9257. for (int il = 0; il < (int) n_layer; ++il) {
  9258. tmp_buf.resize(elt_size*n_embd_k_gqa*kv_head);
  9259. ggml_backend_tensor_get(kv_self.k_l[il], tmp_buf.data(), 0, tmp_buf.size());
  9260. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  9261. // v is not contiguous, copy row by row
  9262. tmp_buf.resize(elt_size*kv_head);
  9263. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  9264. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), ir*elt_size*n_ctx, tmp_buf.size());
  9265. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  9266. }
  9267. }
  9268. }
  9269. for (uint32_t i = 0; i < kv_size; ++i) {
  9270. const auto & cell = kv_self.cells[i];
  9271. const llama_pos pos = cell.pos;
  9272. const size_t seq_id_size = cell.seq_id.size();
  9273. data_ctx->write(&pos, sizeof(pos));
  9274. data_ctx->write(&seq_id_size, sizeof(seq_id_size));
  9275. for (auto seq_id : cell.seq_id) {
  9276. data_ctx->write(&seq_id, sizeof(seq_id));
  9277. }
  9278. }
  9279. }
  9280. }
  9281. size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dst) {
  9282. llama_data_buffer_context data_ctx(dst);
  9283. llama_copy_state_data_internal(ctx, &data_ctx);
  9284. return data_ctx.get_size_written();
  9285. }
  9286. // Sets the state reading from the specified source address
  9287. size_t llama_set_state_data(struct llama_context * ctx, uint8_t * src) {
  9288. uint8_t * inp = src;
  9289. // set rng
  9290. {
  9291. size_t rng_size;
  9292. memcpy(&rng_size, inp, sizeof(rng_size)); inp += sizeof(rng_size);
  9293. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  9294. std::string rng_str((char *)inp, rng_size); inp += rng_size;
  9295. std::istringstream rng_ss(rng_str);
  9296. rng_ss >> ctx->rng;
  9297. GGML_ASSERT(!rng_ss.fail());
  9298. }
  9299. // set logits
  9300. {
  9301. size_t logits_size;
  9302. memcpy(&logits_size, inp, sizeof(logits_size)); inp += sizeof(logits_size);
  9303. GGML_ASSERT(ctx->logits.capacity() >= logits_size);
  9304. if (logits_size) {
  9305. ctx->logits.resize(logits_size);
  9306. memcpy(ctx->logits.data(), inp, logits_size * sizeof(float));
  9307. inp += logits_size * sizeof(float);
  9308. }
  9309. }
  9310. // set embeddings
  9311. {
  9312. size_t embedding_size;
  9313. memcpy(&embedding_size, inp, sizeof(embedding_size)); inp += sizeof(embedding_size);
  9314. GGML_ASSERT(ctx->embedding.capacity() == embedding_size);
  9315. if (embedding_size) {
  9316. memcpy(ctx->embedding.data(), inp, embedding_size * sizeof(float));
  9317. inp += embedding_size * sizeof(float);
  9318. }
  9319. }
  9320. // set kv cache
  9321. {
  9322. const auto & kv_self = ctx->kv_self;
  9323. const auto & hparams = ctx->model.hparams;
  9324. const auto & cparams = ctx->cparams;
  9325. const int n_layer = hparams.n_layer;
  9326. const int n_embd_k_gqa = hparams.n_embd_k_gqa();
  9327. const int n_embd_v_gqa = hparams.n_embd_v_gqa();
  9328. const int n_ctx = cparams.n_ctx;
  9329. size_t kv_buf_size;
  9330. uint32_t kv_head;
  9331. uint32_t kv_size;
  9332. uint32_t kv_used;
  9333. memcpy(&kv_buf_size, inp, sizeof(kv_buf_size)); inp += sizeof(kv_buf_size);
  9334. memcpy(&kv_head, inp, sizeof(kv_head)); inp += sizeof(kv_head);
  9335. memcpy(&kv_size, inp, sizeof(kv_size)); inp += sizeof(kv_size);
  9336. memcpy(&kv_used, inp, sizeof(kv_used)); inp += sizeof(kv_used);
  9337. if (kv_buf_size) {
  9338. GGML_ASSERT(kv_self.total_size() == kv_buf_size);
  9339. const size_t elt_size = ggml_element_size(kv_self.k_l[0]);
  9340. for (int il = 0; il < (int) n_layer; ++il) {
  9341. size_t k_size = elt_size*n_embd_k_gqa*kv_head;
  9342. ggml_backend_tensor_set(kv_self.k_l[il], inp, 0, k_size);
  9343. inp += k_size;
  9344. // v is not contiguous, copy row by row
  9345. size_t v_row_size = elt_size*kv_head;
  9346. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  9347. ggml_backend_tensor_set(kv_self.v_l[il], inp, ir*elt_size*n_ctx, v_row_size);
  9348. inp += v_row_size;
  9349. }
  9350. }
  9351. }
  9352. ctx->kv_self.head = kv_head;
  9353. ctx->kv_self.size = kv_size;
  9354. ctx->kv_self.used = kv_used;
  9355. ctx->kv_self.cells.resize(kv_size);
  9356. for (uint32_t i = 0; i < kv_size; ++i) {
  9357. llama_pos pos;
  9358. size_t seq_id_size;
  9359. memcpy(&pos, inp, sizeof(pos)); inp += sizeof(pos);
  9360. memcpy(&seq_id_size, inp, sizeof(seq_id_size)); inp += sizeof(seq_id_size);
  9361. ctx->kv_self.cells[i].pos = pos;
  9362. llama_seq_id seq_id;
  9363. for (size_t j = 0; j < seq_id_size; ++j) {
  9364. memcpy(&seq_id, inp, sizeof(seq_id)); inp += sizeof(seq_id);
  9365. ctx->kv_self.cells[i].seq_id.insert(seq_id);
  9366. }
  9367. }
  9368. }
  9369. const size_t nread = inp - src;
  9370. const size_t max_size = llama_get_state_size(ctx);
  9371. GGML_ASSERT(nread <= max_size);
  9372. return nread;
  9373. }
  9374. 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) {
  9375. llama_file file(path_session, "rb");
  9376. // sanity checks
  9377. {
  9378. const uint32_t magic = file.read_u32();
  9379. const uint32_t version = file.read_u32();
  9380. if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
  9381. LLAMA_LOG_ERROR("%s : unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
  9382. return false;
  9383. }
  9384. llama_hparams session_hparams;
  9385. file.read_raw(&session_hparams, sizeof(llama_hparams));
  9386. if (session_hparams != ctx->model.hparams) {
  9387. LLAMA_LOG_INFO("%s : model hparams didn't match from session file!\n", __func__);
  9388. return false;
  9389. }
  9390. }
  9391. // load the prompt
  9392. {
  9393. const uint32_t n_token_count = file.read_u32();
  9394. if (n_token_count > n_token_capacity) {
  9395. LLAMA_LOG_ERROR("%s : token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  9396. return false;
  9397. }
  9398. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  9399. *n_token_count_out = n_token_count;
  9400. }
  9401. // restore the context state
  9402. {
  9403. const size_t n_state_size_cur = file.size - file.tell();
  9404. const size_t n_state_size_max = llama_get_state_size(ctx);
  9405. if (n_state_size_cur > n_state_size_max) {
  9406. 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);
  9407. return false;
  9408. }
  9409. std::vector<uint8_t> state_data(n_state_size_max);
  9410. file.read_raw(state_data.data(), n_state_size_cur);
  9411. llama_set_state_data(ctx, state_data.data());
  9412. }
  9413. return true;
  9414. }
  9415. 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) {
  9416. try {
  9417. return llama_load_session_file_internal(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  9418. } catch (const std::exception & err) {
  9419. LLAMA_LOG_ERROR("error loading session file: %s\n", err.what());
  9420. return false;
  9421. }
  9422. }
  9423. bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  9424. llama_file file(path_session, "wb");
  9425. file.write_u32(LLAMA_SESSION_MAGIC);
  9426. file.write_u32(LLAMA_SESSION_VERSION);
  9427. file.write_raw(&ctx->model.hparams, sizeof(llama_hparams));
  9428. // save the prompt
  9429. file.write_u32((uint32_t) n_token_count);
  9430. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  9431. // save the context state using stream saving
  9432. llama_data_file_context data_ctx(&file);
  9433. llama_copy_state_data_internal(ctx, &data_ctx);
  9434. return true;
  9435. }
  9436. int llama_eval(
  9437. struct llama_context * ctx,
  9438. llama_token * tokens,
  9439. int32_t n_tokens,
  9440. int32_t n_past) {
  9441. llama_kv_cache_seq_rm(ctx->kv_self, -1, n_past, -1);
  9442. const int ret = llama_decode_internal(*ctx, llama_batch_get_one(tokens, n_tokens, n_past, 0));
  9443. if (ret < 0) {
  9444. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  9445. }
  9446. return ret;
  9447. }
  9448. int llama_eval_embd(
  9449. struct llama_context * ctx,
  9450. float * embd,
  9451. int32_t n_tokens,
  9452. int32_t n_past) {
  9453. llama_kv_cache_seq_rm(ctx->kv_self, -1, n_past, -1);
  9454. llama_batch batch = { n_tokens, nullptr, embd, nullptr, nullptr, nullptr, nullptr, n_past, 1, 0, };
  9455. const int ret = llama_decode_internal(*ctx, batch);
  9456. if (ret < 0) {
  9457. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  9458. }
  9459. return ret;
  9460. }
  9461. void llama_set_n_threads(struct llama_context * ctx, uint32_t n_threads, uint32_t n_threads_batch) {
  9462. ctx->cparams.n_threads = n_threads;
  9463. ctx->cparams.n_threads_batch = n_threads_batch;
  9464. }
  9465. struct llama_batch llama_batch_get_one(
  9466. llama_token * tokens,
  9467. int32_t n_tokens,
  9468. llama_pos pos_0,
  9469. llama_seq_id seq_id) {
  9470. return {
  9471. /*n_tokens =*/ n_tokens,
  9472. /*tokens =*/ tokens,
  9473. /*embd =*/ nullptr,
  9474. /*pos =*/ nullptr,
  9475. /*n_seq_id =*/ nullptr,
  9476. /*seq_id =*/ nullptr,
  9477. /*logits =*/ nullptr,
  9478. /*all_pos_0 =*/ pos_0,
  9479. /*all_pos_1 =*/ 1,
  9480. /*all_seq_id =*/ seq_id,
  9481. };
  9482. }
  9483. struct llama_batch llama_batch_init(int32_t n_tokens_alloc, int32_t embd, int32_t n_seq_max) {
  9484. llama_batch batch = { 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, 0, 0, 0, };
  9485. if (embd) {
  9486. batch.embd = (float *) malloc(sizeof(float) * n_tokens_alloc * embd);
  9487. } else {
  9488. batch.token = (llama_token *) malloc(sizeof(llama_token) * n_tokens_alloc);
  9489. }
  9490. batch.pos = (llama_pos *) malloc(sizeof(llama_pos) * n_tokens_alloc);
  9491. batch.n_seq_id = (int32_t *) malloc(sizeof(int32_t) * n_tokens_alloc);
  9492. batch.seq_id = (llama_seq_id **) malloc(sizeof(llama_seq_id *) * (n_tokens_alloc + 1));
  9493. for (int i = 0; i < n_tokens_alloc; ++i) {
  9494. batch.seq_id[i] = (llama_seq_id *) malloc(sizeof(llama_seq_id) * n_seq_max);
  9495. }
  9496. batch.seq_id[n_tokens_alloc] = nullptr;
  9497. batch.logits = (int8_t *) malloc(sizeof(int8_t) * n_tokens_alloc);
  9498. return batch;
  9499. }
  9500. void llama_batch_free(struct llama_batch batch) {
  9501. if (batch.token) free(batch.token);
  9502. if (batch.embd) free(batch.embd);
  9503. if (batch.pos) free(batch.pos);
  9504. if (batch.n_seq_id) free(batch.n_seq_id);
  9505. if (batch.seq_id) {
  9506. for (int i = 0; batch.seq_id[i] != nullptr; ++i) {
  9507. free(batch.seq_id[i]);
  9508. }
  9509. free(batch.seq_id);
  9510. }
  9511. if (batch.logits) free(batch.logits);
  9512. }
  9513. int32_t llama_decode(
  9514. struct llama_context * ctx,
  9515. struct llama_batch batch) {
  9516. const int ret = llama_decode_internal(*ctx, batch);
  9517. if (ret < 0) {
  9518. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  9519. }
  9520. return ret;
  9521. }
  9522. float * llama_get_logits(struct llama_context * ctx) {
  9523. return ctx->logits.data();
  9524. }
  9525. float * llama_get_logits_ith(struct llama_context * ctx, int32_t i) {
  9526. assert(ctx->logits_valid.at(i));
  9527. return ctx->logits.data() + i*ctx->model.hparams.n_vocab;
  9528. }
  9529. float * llama_get_embeddings(struct llama_context * ctx) {
  9530. return ctx->embedding.data();
  9531. }
  9532. const char * llama_token_get_text(const struct llama_model * model, llama_token token) {
  9533. return model->vocab.id_to_token[token].text.c_str();
  9534. }
  9535. float llama_token_get_score(const struct llama_model * model, llama_token token) {
  9536. return model->vocab.id_to_token[token].score;
  9537. }
  9538. llama_token_type llama_token_get_type(const struct llama_model * model, llama_token token) {
  9539. return model->vocab.id_to_token[token].type;
  9540. }
  9541. llama_token llama_token_bos(const struct llama_model * model) {
  9542. return model->vocab.special_bos_id;
  9543. }
  9544. llama_token llama_token_eos(const struct llama_model * model) {
  9545. return model->vocab.special_eos_id;
  9546. }
  9547. llama_token llama_token_nl(const struct llama_model * model) {
  9548. return model->vocab.linefeed_id;
  9549. }
  9550. int32_t llama_add_bos_token(const struct llama_model * model) {
  9551. return model->vocab.special_add_bos;
  9552. }
  9553. int32_t llama_add_eos_token(const struct llama_model * model) {
  9554. return model->vocab.special_add_eos;
  9555. }
  9556. llama_token llama_token_prefix(const struct llama_model * model) {
  9557. return model->vocab.special_prefix_id;
  9558. }
  9559. llama_token llama_token_middle(const struct llama_model * model) {
  9560. return model->vocab.special_middle_id;
  9561. }
  9562. llama_token llama_token_suffix(const struct llama_model * model) {
  9563. return model->vocab.special_suffix_id;
  9564. }
  9565. llama_token llama_token_eot(const struct llama_model * model) {
  9566. return model->vocab.special_eot_id;
  9567. }
  9568. int32_t llama_tokenize(
  9569. const struct llama_model * model,
  9570. const char * text,
  9571. int32_t text_len,
  9572. llama_token * tokens,
  9573. int32_t n_max_tokens,
  9574. bool add_bos,
  9575. bool special) {
  9576. auto res = llama_tokenize_internal(model->vocab, std::string(text, text_len), add_bos, special);
  9577. if (n_max_tokens < (int) res.size()) {
  9578. // LLAMA_LOG_ERROR("%s: too many tokens\n", __func__);
  9579. return -((int) res.size());
  9580. }
  9581. for (size_t i = 0; i < res.size(); i++) {
  9582. tokens[i] = res[i];
  9583. }
  9584. return res.size();
  9585. }
  9586. static std::string llama_decode_text(const std::string & text) {
  9587. std::string decoded_text;
  9588. auto unicode_sequences = codepoints_from_utf8(text);
  9589. for (auto& unicode_sequence : unicode_sequences) {
  9590. decoded_text += unicode_to_bytes_bpe(codepoint_to_utf8(unicode_sequence));
  9591. }
  9592. return decoded_text;
  9593. }
  9594. // does not write null-terminator to buf
  9595. int32_t llama_token_to_piece(const struct llama_model * model, llama_token token, char * buf, int32_t length) {
  9596. if (0 <= token && token < llama_n_vocab(model)) {
  9597. switch (llama_vocab_get_type(model->vocab)) {
  9598. case LLAMA_VOCAB_TYPE_SPM: {
  9599. // NOTE: we accept all unsupported token types,
  9600. // suppressing them like CONTROL tokens.
  9601. if (llama_is_normal_token(model->vocab, token)) {
  9602. std::string result = model->vocab.id_to_token[token].text;
  9603. llama_unescape_whitespace(result);
  9604. if (length < (int) result.length()) {
  9605. return -(int) result.length();
  9606. }
  9607. memcpy(buf, result.c_str(), result.length());
  9608. return result.length();
  9609. } else if (llama_is_user_defined_token(model->vocab, token)) {
  9610. std::string result = model->vocab.id_to_token[token].text;
  9611. if (length < (int) result.length()) {
  9612. return -result.length();
  9613. }
  9614. memcpy(buf, result.c_str(), result.length());
  9615. return result.length();
  9616. } else if (llama_is_unknown_token(model->vocab, token)) { // NOLINT
  9617. if (length < 3) {
  9618. return -3;
  9619. }
  9620. memcpy(buf, "\xe2\x96\x85", 3);
  9621. return 3;
  9622. } else if (llama_is_control_token(model->vocab, token)) {
  9623. ;
  9624. } else if (llama_is_byte_token(model->vocab, token)) {
  9625. if (length < 1) {
  9626. return -1;
  9627. }
  9628. buf[0] = llama_token_to_byte(model->vocab, token);
  9629. return 1;
  9630. }
  9631. break;
  9632. }
  9633. case LLAMA_VOCAB_TYPE_BPE: {
  9634. // NOTE: we accept all unsupported token types,
  9635. // suppressing them like CONTROL tokens.
  9636. if (llama_is_normal_token(model->vocab, token)) {
  9637. std::string result = model->vocab.id_to_token[token].text;
  9638. result = llama_decode_text(result);
  9639. if (length < (int) result.length()) {
  9640. return -(int) result.length();
  9641. }
  9642. memcpy(buf, result.c_str(), result.length());
  9643. return result.length();
  9644. } else if (llama_is_user_defined_token(model->vocab, token)) {
  9645. std::string result = model->vocab.id_to_token[token].text;
  9646. if (length < (int) result.length()) {
  9647. return -result.length();
  9648. }
  9649. memcpy(buf, result.c_str(), result.length());
  9650. return result.length();
  9651. } else if (llama_is_control_token(model->vocab, token)) {
  9652. ;
  9653. }
  9654. break;
  9655. }
  9656. default:
  9657. GGML_ASSERT(false);
  9658. }
  9659. }
  9660. return 0;
  9661. }
  9662. struct llama_timings llama_get_timings(struct llama_context * ctx) {
  9663. struct llama_timings result = {
  9664. /*.t_start_ms =*/ 1e-3 * ctx->t_start_us,
  9665. /*.t_end_ms =*/ 1.00 * ggml_time_ms(),
  9666. /*.t_load_ms =*/ 1e-3 * ctx->t_load_us,
  9667. /*.t_sample_ms =*/ 1e-3 * ctx->t_sample_us,
  9668. /*.t_p_eval_ms =*/ 1e-3 * ctx->t_p_eval_us,
  9669. /*.t_eval_ms =*/ 1e-3 * ctx->t_eval_us,
  9670. /*.n_sample =*/ std::max(1, ctx->n_sample),
  9671. /*.n_p_eval =*/ std::max(1, ctx->n_p_eval),
  9672. /*.n_eval =*/ std::max(1, ctx->n_eval),
  9673. };
  9674. return result;
  9675. }
  9676. void llama_print_timings(struct llama_context * ctx) {
  9677. const llama_timings timings = llama_get_timings(ctx);
  9678. LLAMA_LOG_INFO("\n");
  9679. LLAMA_LOG_INFO("%s: load time = %10.2f ms\n", __func__, timings.t_load_ms);
  9680. LLAMA_LOG_INFO("%s: sample time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  9681. __func__, timings.t_sample_ms, timings.n_sample, timings.t_sample_ms / timings.n_sample, 1e3 / timings.t_sample_ms * timings.n_sample);
  9682. LLAMA_LOG_INFO("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  9683. __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);
  9684. LLAMA_LOG_INFO("%s: eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  9685. __func__, timings.t_eval_ms, timings.n_eval, timings.t_eval_ms / timings.n_eval, 1e3 / timings.t_eval_ms * timings.n_eval);
  9686. 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));
  9687. }
  9688. void llama_reset_timings(struct llama_context * ctx) {
  9689. ctx->t_start_us = ggml_time_us();
  9690. ctx->t_sample_us = ctx->n_sample = 0;
  9691. ctx->t_eval_us = ctx->n_eval = 0;
  9692. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  9693. }
  9694. const char * llama_print_system_info(void) {
  9695. static std::string s;
  9696. s = "";
  9697. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  9698. s += "AVX_VNNI = " + std::to_string(ggml_cpu_has_avx_vnni()) + " | ";
  9699. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  9700. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  9701. s += "AVX512_VBMI = " + std::to_string(ggml_cpu_has_avx512_vbmi()) + " | ";
  9702. s += "AVX512_VNNI = " + std::to_string(ggml_cpu_has_avx512_vnni()) + " | ";
  9703. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  9704. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  9705. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  9706. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  9707. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  9708. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  9709. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  9710. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  9711. s += "SSSE3 = " + std::to_string(ggml_cpu_has_ssse3()) + " | ";
  9712. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  9713. return s.c_str();
  9714. }
  9715. void llama_dump_timing_info_yaml(FILE * stream, const llama_context * ctx) {
  9716. fprintf(stream, "\n");
  9717. fprintf(stream, "###########\n");
  9718. fprintf(stream, "# Timings #\n");
  9719. fprintf(stream, "###########\n");
  9720. fprintf(stream, "\n");
  9721. fprintf(stream, "mst_eval: %.2f # ms / token during generation\n",
  9722. 1.0e-3 * ctx->t_eval_us / ctx->n_eval);
  9723. fprintf(stream, "mst_p_eval: %.2f # ms / token during prompt processing\n",
  9724. 1.0e-3 * ctx->t_p_eval_us / ctx->n_p_eval);
  9725. fprintf(stream, "mst_sample: %.2f # ms / token during sampling\n",
  9726. 1.0e-3 * ctx->t_sample_us / ctx->n_sample);
  9727. fprintf(stream, "n_eval: %d # number of tokens generated (excluding the first one)\n", ctx->n_eval);
  9728. fprintf(stream, "n_p_eval: %d # number of tokens processed in batches at the beginning\n", ctx->n_p_eval);
  9729. fprintf(stream, "n_sample: %d # number of sampled tokens\n", ctx->n_sample);
  9730. fprintf(stream, "t_eval_us: %" PRId64 " # total microseconds spent generating tokens\n", ctx->t_eval_us);
  9731. fprintf(stream, "t_load_us: %" PRId64 " # total microseconds spent loading the model\n", ctx->t_load_us);
  9732. fprintf(stream, "t_p_eval_us: %" PRId64 " # total microseconds spent prompt processing\n", ctx->t_p_eval_us);
  9733. fprintf(stream, "t_sample_us: %" PRId64 " # total microseconds spent sampling\n", ctx->t_sample_us);
  9734. fprintf(stream, "ts_eval: %.2f # tokens / second during generation\n",
  9735. 1.0e6 * ctx->n_eval / ctx->t_eval_us);
  9736. fprintf(stream, "ts_p_eval: %.2f # tokens / second during prompt processing\n",
  9737. 1.0e6 * ctx->n_p_eval / ctx->t_p_eval_us);
  9738. fprintf(stream, "ts_sample: %.2f # tokens / second during sampling\n",
  9739. 1.0e6 * ctx->n_sample / ctx->t_sample_us);
  9740. }
  9741. // For internal test use
  9742. const std::vector<std::pair<std::string, struct ggml_tensor *>> & llama_internal_get_tensor_map(
  9743. struct llama_context * ctx
  9744. ) {
  9745. return ctx->model.tensors_by_name;
  9746. }
  9747. void llama_log_set(ggml_log_callback log_callback, void * user_data) {
  9748. g_state.log_callback = log_callback ? log_callback : llama_log_callback_default;
  9749. g_state.log_callback_user_data = user_data;
  9750. #ifdef GGML_USE_METAL
  9751. ggml_backend_metal_log_set_callback(g_state.log_callback, g_state.log_callback_user_data);
  9752. #endif
  9753. }
  9754. static void llama_log_internal_v(ggml_log_level level, const char * format, va_list args) {
  9755. va_list args_copy;
  9756. va_copy(args_copy, args);
  9757. char buffer[128];
  9758. int len = vsnprintf(buffer, 128, format, args);
  9759. if (len < 128) {
  9760. g_state.log_callback(level, buffer, g_state.log_callback_user_data);
  9761. } else {
  9762. char* buffer2 = new char[len+1];
  9763. vsnprintf(buffer2, len+1, format, args_copy);
  9764. buffer2[len] = 0;
  9765. g_state.log_callback(level, buffer2, g_state.log_callback_user_data);
  9766. delete[] buffer2;
  9767. }
  9768. va_end(args_copy);
  9769. }
  9770. static void llama_log_internal(ggml_log_level level, const char * format, ...) {
  9771. va_list args;
  9772. va_start(args, format);
  9773. llama_log_internal_v(level, format, args);
  9774. va_end(args);
  9775. }
  9776. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data) {
  9777. (void) level;
  9778. (void) user_data;
  9779. fputs(text, stderr);
  9780. fflush(stderr);
  9781. }