llama.cpp 516 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358
  1. #define LLAMA_API_INTERNAL
  2. #include "llama.h"
  3. #include "unicode.h"
  4. #include "ggml.h"
  5. #include "ggml-alloc.h"
  6. #include "ggml-backend.h"
  7. #ifdef GGML_USE_CUBLAS
  8. # include "ggml-cuda.h"
  9. #elif defined(GGML_USE_CLBLAST)
  10. # include "ggml-opencl.h"
  11. #elif defined(GGML_USE_VULKAN)
  12. # include "ggml-vulkan.h"
  13. #elif defined(GGML_USE_SYCL)
  14. # include "ggml-sycl.h"
  15. #elif defined(GGML_USE_KOMPUTE)
  16. # include "ggml-kompute.h"
  17. #endif
  18. #ifdef GGML_USE_METAL
  19. # include "ggml-metal.h"
  20. #endif
  21. #ifdef GGML_USE_MPI
  22. # include "ggml-mpi.h"
  23. #endif
  24. #ifndef QK_K
  25. # ifdef GGML_QKK_64
  26. # define QK_K 64
  27. # else
  28. # define QK_K 256
  29. # endif
  30. #endif
  31. #ifdef __has_include
  32. #if __has_include(<unistd.h>)
  33. #include <unistd.h>
  34. #if defined(_POSIX_MAPPED_FILES)
  35. #include <sys/mman.h>
  36. #include <fcntl.h>
  37. #endif
  38. #if defined(_POSIX_MEMLOCK_RANGE)
  39. #include <sys/resource.h>
  40. #endif
  41. #endif
  42. #endif
  43. #if defined(_WIN32)
  44. #define WIN32_LEAN_AND_MEAN
  45. #ifndef NOMINMAX
  46. #define NOMINMAX
  47. #endif
  48. #include <windows.h>
  49. #include <io.h>
  50. #endif
  51. #include <algorithm>
  52. #include <array>
  53. #include <cassert>
  54. #include <cfloat>
  55. #include <cinttypes>
  56. #include <climits>
  57. #include <cmath>
  58. #include <cstdarg>
  59. #include <cstddef>
  60. #include <cstdint>
  61. #include <cstdio>
  62. #include <cstring>
  63. #include <ctime>
  64. #include <cwctype>
  65. #include <forward_list>
  66. #include <fstream>
  67. #include <functional>
  68. #include <initializer_list>
  69. #include <locale>
  70. #include <map>
  71. #include <memory>
  72. #include <mutex>
  73. #include <numeric>
  74. #include <queue>
  75. #include <random>
  76. #include <regex>
  77. #include <set>
  78. #include <sstream>
  79. #include <thread>
  80. #include <type_traits>
  81. #include <unordered_map>
  82. #if defined(_MSC_VER)
  83. #pragma warning(disable: 4244 4267) // possible loss of data
  84. #endif
  85. #ifdef __GNUC__
  86. #ifdef __MINGW32__
  87. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(gnu_printf, __VA_ARGS__)))
  88. #else
  89. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(printf, __VA_ARGS__)))
  90. #endif
  91. #else
  92. #define LLAMA_ATTRIBUTE_FORMAT(...)
  93. #endif
  94. #define LLAMA_MAX_NODES 8192
  95. #define LLAMA_MAX_EXPERTS 8
  96. //
  97. // logging
  98. //
  99. LLAMA_ATTRIBUTE_FORMAT(2, 3)
  100. static void llama_log_internal (ggml_log_level level, const char* format, ...);
  101. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data);
  102. #define LLAMA_LOG_INFO(...) llama_log_internal(GGML_LOG_LEVEL_INFO , __VA_ARGS__)
  103. #define LLAMA_LOG_WARN(...) llama_log_internal(GGML_LOG_LEVEL_WARN , __VA_ARGS__)
  104. #define LLAMA_LOG_ERROR(...) llama_log_internal(GGML_LOG_LEVEL_ERROR, __VA_ARGS__)
  105. //
  106. // helpers
  107. //
  108. static size_t utf8_len(char src) {
  109. const size_t lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4 };
  110. uint8_t highbits = static_cast<uint8_t>(src) >> 4;
  111. return lookup[highbits];
  112. }
  113. static void replace_all(std::string & s, const std::string & search, const std::string & replace) {
  114. std::string result;
  115. for (size_t pos = 0; ; pos += search.length()) {
  116. auto new_pos = s.find(search, pos);
  117. if (new_pos == std::string::npos) {
  118. result += s.substr(pos, s.size() - pos);
  119. break;
  120. }
  121. result += s.substr(pos, new_pos - pos) + replace;
  122. pos = new_pos;
  123. }
  124. s = std::move(result);
  125. }
  126. static bool is_float_close(float a, float b, float abs_tol) {
  127. // Check for non-negative tolerance
  128. if (abs_tol < 0.0) {
  129. throw std::invalid_argument("Tolerance must be non-negative");
  130. }
  131. // Exact equality check
  132. if (a == b) {
  133. return true;
  134. }
  135. // Check for infinities
  136. if (std::isinf(a) || std::isinf(b)) {
  137. return false;
  138. }
  139. // Regular comparison using the provided absolute tolerance
  140. return std::fabs(b - a) <= abs_tol;
  141. }
  142. static void zeros(std::ofstream & file, size_t n) {
  143. char zero = 0;
  144. for (size_t i = 0; i < n; ++i) {
  145. file.write(&zero, 1);
  146. }
  147. }
  148. LLAMA_ATTRIBUTE_FORMAT(1, 2)
  149. static std::string format(const char * fmt, ...) {
  150. va_list ap;
  151. va_list ap2;
  152. va_start(ap, fmt);
  153. va_copy(ap2, ap);
  154. int size = vsnprintf(NULL, 0, fmt, ap);
  155. GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
  156. std::vector<char> buf(size + 1);
  157. int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
  158. GGML_ASSERT(size2 == size);
  159. va_end(ap2);
  160. va_end(ap);
  161. return std::string(buf.data(), size);
  162. }
  163. //
  164. // gguf constants (sync with gguf.py)
  165. //
  166. enum llm_arch {
  167. LLM_ARCH_LLAMA,
  168. LLM_ARCH_FALCON,
  169. LLM_ARCH_BAICHUAN,
  170. LLM_ARCH_GPT2,
  171. LLM_ARCH_GPTJ,
  172. LLM_ARCH_GPTNEOX,
  173. LLM_ARCH_MPT,
  174. LLM_ARCH_STARCODER,
  175. LLM_ARCH_PERSIMMON,
  176. LLM_ARCH_REFACT,
  177. LLM_ARCH_BERT,
  178. LLM_ARCH_NOMIC_BERT,
  179. LLM_ARCH_BLOOM,
  180. LLM_ARCH_STABLELM,
  181. LLM_ARCH_QWEN,
  182. LLM_ARCH_QWEN2,
  183. LLM_ARCH_PHI2,
  184. LLM_ARCH_PLAMO,
  185. LLM_ARCH_CODESHELL,
  186. LLM_ARCH_ORION,
  187. LLM_ARCH_INTERNLM2,
  188. LLM_ARCH_MINICPM,
  189. LLM_ARCH_GEMMA,
  190. LLM_ARCH_UNKNOWN,
  191. };
  192. static std::map<llm_arch, const char *> LLM_ARCH_NAMES = {
  193. { LLM_ARCH_LLAMA, "llama" },
  194. { LLM_ARCH_FALCON, "falcon" },
  195. { LLM_ARCH_GPT2, "gpt2" },
  196. { LLM_ARCH_GPTJ, "gptj" },
  197. { LLM_ARCH_GPTNEOX, "gptneox" },
  198. { LLM_ARCH_MPT, "mpt" },
  199. { LLM_ARCH_BAICHUAN, "baichuan" },
  200. { LLM_ARCH_STARCODER, "starcoder" },
  201. { LLM_ARCH_PERSIMMON, "persimmon" },
  202. { LLM_ARCH_REFACT, "refact" },
  203. { LLM_ARCH_BERT, "bert" },
  204. { LLM_ARCH_NOMIC_BERT, "nomic-bert" },
  205. { LLM_ARCH_BLOOM, "bloom" },
  206. { LLM_ARCH_STABLELM, "stablelm" },
  207. { LLM_ARCH_QWEN, "qwen" },
  208. { LLM_ARCH_QWEN2, "qwen2" },
  209. { LLM_ARCH_PHI2, "phi2" },
  210. { LLM_ARCH_PLAMO, "plamo" },
  211. { LLM_ARCH_CODESHELL, "codeshell" },
  212. { LLM_ARCH_ORION, "orion" },
  213. { LLM_ARCH_INTERNLM2, "internlm2" },
  214. { LLM_ARCH_MINICPM, "minicpm" },
  215. { LLM_ARCH_GEMMA, "gemma" },
  216. };
  217. enum llm_kv {
  218. LLM_KV_GENERAL_ARCHITECTURE,
  219. LLM_KV_GENERAL_QUANTIZATION_VERSION,
  220. LLM_KV_GENERAL_ALIGNMENT,
  221. LLM_KV_GENERAL_NAME,
  222. LLM_KV_GENERAL_AUTHOR,
  223. LLM_KV_GENERAL_URL,
  224. LLM_KV_GENERAL_DESCRIPTION,
  225. LLM_KV_GENERAL_LICENSE,
  226. LLM_KV_GENERAL_SOURCE_URL,
  227. LLM_KV_GENERAL_SOURCE_HF_REPO,
  228. LLM_KV_CONTEXT_LENGTH,
  229. LLM_KV_EMBEDDING_LENGTH,
  230. LLM_KV_BLOCK_COUNT,
  231. LLM_KV_FEED_FORWARD_LENGTH,
  232. LLM_KV_USE_PARALLEL_RESIDUAL,
  233. LLM_KV_TENSOR_DATA_LAYOUT,
  234. LLM_KV_EXPERT_COUNT,
  235. LLM_KV_EXPERT_USED_COUNT,
  236. LLM_KV_POOLING_TYPE,
  237. LLM_KV_ATTENTION_HEAD_COUNT,
  238. LLM_KV_ATTENTION_HEAD_COUNT_KV,
  239. LLM_KV_ATTENTION_MAX_ALIBI_BIAS,
  240. LLM_KV_ATTENTION_CLAMP_KQV,
  241. LLM_KV_ATTENTION_KEY_LENGTH,
  242. LLM_KV_ATTENTION_VALUE_LENGTH,
  243. LLM_KV_ATTENTION_LAYERNORM_EPS,
  244. LLM_KV_ATTENTION_LAYERNORM_RMS_EPS,
  245. LLM_KV_ATTENTION_CAUSAL,
  246. LLM_KV_ROPE_DIMENSION_COUNT,
  247. LLM_KV_ROPE_FREQ_BASE,
  248. LLM_KV_ROPE_SCALE_LINEAR,
  249. LLM_KV_ROPE_SCALING_TYPE,
  250. LLM_KV_ROPE_SCALING_FACTOR,
  251. LLM_KV_ROPE_SCALING_ORIG_CTX_LEN,
  252. LLM_KV_ROPE_SCALING_FINETUNED,
  253. LLM_KV_TOKENIZER_MODEL,
  254. LLM_KV_TOKENIZER_LIST,
  255. LLM_KV_TOKENIZER_TOKEN_TYPE,
  256. LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT,
  257. LLM_KV_TOKENIZER_SCORES,
  258. LLM_KV_TOKENIZER_MERGES,
  259. LLM_KV_TOKENIZER_BOS_ID,
  260. LLM_KV_TOKENIZER_EOS_ID,
  261. LLM_KV_TOKENIZER_UNK_ID,
  262. LLM_KV_TOKENIZER_SEP_ID,
  263. LLM_KV_TOKENIZER_PAD_ID,
  264. LLM_KV_TOKENIZER_ADD_BOS,
  265. LLM_KV_TOKENIZER_ADD_EOS,
  266. LLM_KV_TOKENIZER_ADD_PREFIX,
  267. LLM_KV_TOKENIZER_HF_JSON,
  268. LLM_KV_TOKENIZER_RWKV,
  269. };
  270. static std::map<llm_kv, const char *> LLM_KV_NAMES = {
  271. { LLM_KV_GENERAL_ARCHITECTURE, "general.architecture" },
  272. { LLM_KV_GENERAL_QUANTIZATION_VERSION, "general.quantization_version" },
  273. { LLM_KV_GENERAL_ALIGNMENT, "general.alignment" },
  274. { LLM_KV_GENERAL_NAME, "general.name" },
  275. { LLM_KV_GENERAL_AUTHOR, "general.author" },
  276. { LLM_KV_GENERAL_URL, "general.url" },
  277. { LLM_KV_GENERAL_DESCRIPTION, "general.description" },
  278. { LLM_KV_GENERAL_LICENSE, "general.license" },
  279. { LLM_KV_GENERAL_SOURCE_URL, "general.source.url" },
  280. { LLM_KV_GENERAL_SOURCE_HF_REPO, "general.source.huggingface.repository" },
  281. { LLM_KV_CONTEXT_LENGTH, "%s.context_length" },
  282. { LLM_KV_EMBEDDING_LENGTH, "%s.embedding_length" },
  283. { LLM_KV_BLOCK_COUNT, "%s.block_count" },
  284. { LLM_KV_FEED_FORWARD_LENGTH, "%s.feed_forward_length" },
  285. { LLM_KV_USE_PARALLEL_RESIDUAL, "%s.use_parallel_residual" },
  286. { LLM_KV_TENSOR_DATA_LAYOUT, "%s.tensor_data_layout" },
  287. { LLM_KV_EXPERT_COUNT, "%s.expert_count" },
  288. { LLM_KV_EXPERT_USED_COUNT, "%s.expert_used_count" },
  289. { LLM_KV_POOLING_TYPE , "%s.pooling_type" },
  290. { LLM_KV_ATTENTION_HEAD_COUNT, "%s.attention.head_count" },
  291. { LLM_KV_ATTENTION_HEAD_COUNT_KV, "%s.attention.head_count_kv" },
  292. { LLM_KV_ATTENTION_MAX_ALIBI_BIAS, "%s.attention.max_alibi_bias" },
  293. { LLM_KV_ATTENTION_CLAMP_KQV, "%s.attention.clamp_kqv" },
  294. { LLM_KV_ATTENTION_KEY_LENGTH, "%s.attention.key_length" },
  295. { LLM_KV_ATTENTION_VALUE_LENGTH, "%s.attention.value_length" },
  296. { LLM_KV_ATTENTION_LAYERNORM_EPS, "%s.attention.layer_norm_epsilon" },
  297. { LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, "%s.attention.layer_norm_rms_epsilon" },
  298. { LLM_KV_ATTENTION_CAUSAL, "%s.attention.causal" },
  299. { LLM_KV_ROPE_DIMENSION_COUNT, "%s.rope.dimension_count" },
  300. { LLM_KV_ROPE_FREQ_BASE, "%s.rope.freq_base" },
  301. { LLM_KV_ROPE_SCALE_LINEAR, "%s.rope.scale_linear" },
  302. { LLM_KV_ROPE_SCALING_TYPE, "%s.rope.scaling.type" },
  303. { LLM_KV_ROPE_SCALING_FACTOR, "%s.rope.scaling.factor" },
  304. { LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, "%s.rope.scaling.original_context_length" },
  305. { LLM_KV_ROPE_SCALING_FINETUNED, "%s.rope.scaling.finetuned" },
  306. { LLM_KV_TOKENIZER_MODEL, "tokenizer.ggml.model" },
  307. { LLM_KV_TOKENIZER_LIST, "tokenizer.ggml.tokens" },
  308. { LLM_KV_TOKENIZER_TOKEN_TYPE, "tokenizer.ggml.token_type" },
  309. { LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, "tokenizer.ggml.token_type_count" },
  310. { LLM_KV_TOKENIZER_SCORES, "tokenizer.ggml.scores" },
  311. { LLM_KV_TOKENIZER_MERGES, "tokenizer.ggml.merges" },
  312. { LLM_KV_TOKENIZER_BOS_ID, "tokenizer.ggml.bos_token_id" },
  313. { LLM_KV_TOKENIZER_EOS_ID, "tokenizer.ggml.eos_token_id" },
  314. { LLM_KV_TOKENIZER_UNK_ID, "tokenizer.ggml.unknown_token_id" },
  315. { LLM_KV_TOKENIZER_SEP_ID, "tokenizer.ggml.seperator_token_id" },
  316. { LLM_KV_TOKENIZER_PAD_ID, "tokenizer.ggml.padding_token_id" },
  317. { LLM_KV_TOKENIZER_ADD_BOS, "tokenizer.ggml.add_bos_token" },
  318. { LLM_KV_TOKENIZER_ADD_EOS, "tokenizer.ggml.add_eos_token" },
  319. { LLM_KV_TOKENIZER_ADD_PREFIX, "tokenizer.ggml.add_space_prefix" },
  320. { LLM_KV_TOKENIZER_HF_JSON, "tokenizer.huggingface.json" },
  321. { LLM_KV_TOKENIZER_RWKV, "tokenizer.rwkv.world" },
  322. };
  323. struct LLM_KV {
  324. LLM_KV(llm_arch arch) : arch(arch) {}
  325. llm_arch arch;
  326. std::string operator()(llm_kv kv) const {
  327. return ::format(LLM_KV_NAMES[kv], LLM_ARCH_NAMES[arch]);
  328. }
  329. };
  330. enum llm_tensor {
  331. LLM_TENSOR_TOKEN_EMBD,
  332. LLM_TENSOR_TOKEN_EMBD_NORM,
  333. LLM_TENSOR_TOKEN_TYPES,
  334. LLM_TENSOR_POS_EMBD,
  335. LLM_TENSOR_OUTPUT,
  336. LLM_TENSOR_OUTPUT_NORM,
  337. LLM_TENSOR_ROPE_FREQS,
  338. LLM_TENSOR_ATTN_Q,
  339. LLM_TENSOR_ATTN_K,
  340. LLM_TENSOR_ATTN_V,
  341. LLM_TENSOR_ATTN_QKV,
  342. LLM_TENSOR_ATTN_OUT,
  343. LLM_TENSOR_ATTN_NORM,
  344. LLM_TENSOR_ATTN_NORM_2,
  345. LLM_TENSOR_ATTN_OUT_NORM,
  346. LLM_TENSOR_ATTN_ROT_EMBD,
  347. LLM_TENSOR_FFN_GATE_INP,
  348. LLM_TENSOR_FFN_NORM,
  349. LLM_TENSOR_FFN_GATE,
  350. LLM_TENSOR_FFN_DOWN,
  351. LLM_TENSOR_FFN_UP,
  352. LLM_TENSOR_FFN_ACT,
  353. LLM_TENSOR_FFN_DOWN_EXP,
  354. LLM_TENSOR_FFN_GATE_EXP,
  355. LLM_TENSOR_FFN_UP_EXP,
  356. LLM_TENSOR_ATTN_Q_NORM,
  357. LLM_TENSOR_ATTN_K_NORM,
  358. LLM_TENSOR_LAYER_OUT_NORM,
  359. };
  360. static std::map<llm_arch, std::map<llm_tensor, std::string>> LLM_TENSOR_NAMES = {
  361. {
  362. LLM_ARCH_LLAMA,
  363. {
  364. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  365. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  366. { LLM_TENSOR_OUTPUT, "output" },
  367. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  368. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  369. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  370. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  371. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  372. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  373. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  374. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  375. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  376. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  377. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  378. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  379. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  380. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  381. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  382. },
  383. },
  384. {
  385. LLM_ARCH_BAICHUAN,
  386. {
  387. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  388. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  389. { LLM_TENSOR_OUTPUT, "output" },
  390. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  391. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  392. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  393. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  394. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  395. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  396. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  397. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  398. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  399. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  400. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  401. },
  402. },
  403. {
  404. LLM_ARCH_FALCON,
  405. {
  406. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  407. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  408. { LLM_TENSOR_OUTPUT, "output" },
  409. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  410. { LLM_TENSOR_ATTN_NORM_2, "blk.%d.attn_norm_2" },
  411. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  412. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  413. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  414. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  415. },
  416. },
  417. {
  418. LLM_ARCH_GPT2,
  419. {
  420. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  421. { LLM_TENSOR_POS_EMBD, "position_embd" },
  422. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  423. { LLM_TENSOR_OUTPUT, "output" },
  424. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  425. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  426. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  427. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  428. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  429. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  430. },
  431. },
  432. {
  433. LLM_ARCH_GPTJ,
  434. {
  435. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  436. },
  437. },
  438. {
  439. LLM_ARCH_GPTNEOX,
  440. {
  441. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  442. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  443. { LLM_TENSOR_OUTPUT, "output" },
  444. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  445. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  446. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  447. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  448. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  449. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  450. },
  451. },
  452. {
  453. LLM_ARCH_PERSIMMON,
  454. {
  455. { LLM_TENSOR_TOKEN_EMBD, "token_embd"},
  456. { LLM_TENSOR_OUTPUT_NORM, "output_norm"},
  457. { LLM_TENSOR_OUTPUT, "output"},
  458. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm"},
  459. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv"},
  460. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output"},
  461. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm"},
  462. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm"},
  463. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm"},
  464. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down"},
  465. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up"},
  466. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd"},
  467. },
  468. },
  469. {
  470. LLM_ARCH_MPT,
  471. {
  472. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  473. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  474. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  475. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  476. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  477. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  478. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  479. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  480. { LLM_TENSOR_FFN_ACT, "blk.%d.ffn.act" },
  481. },
  482. },
  483. {
  484. LLM_ARCH_STARCODER,
  485. {
  486. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  487. { LLM_TENSOR_POS_EMBD, "position_embd" },
  488. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  489. { LLM_TENSOR_OUTPUT, "output" },
  490. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  491. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  492. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  493. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  494. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  495. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  496. },
  497. },
  498. {
  499. LLM_ARCH_REFACT,
  500. {
  501. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  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_Q, "blk.%d.attn_q" },
  506. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  507. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  508. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  509. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  510. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  511. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  512. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  513. },
  514. },
  515. {
  516. LLM_ARCH_BERT,
  517. {
  518. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  519. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  520. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  521. { LLM_TENSOR_POS_EMBD, "position_embd" },
  522. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  523. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  524. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  525. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  526. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  527. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  528. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  529. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  530. },
  531. },
  532. {
  533. LLM_ARCH_NOMIC_BERT,
  534. {
  535. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  536. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  537. { LLM_TENSOR_TOKEN_TYPES, "token_types" },
  538. { LLM_TENSOR_ATTN_OUT_NORM, "blk.%d.attn_output_norm" },
  539. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  540. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  541. { LLM_TENSOR_LAYER_OUT_NORM, "blk.%d.layer_output_norm" },
  542. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  543. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  544. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  545. },
  546. },
  547. {
  548. LLM_ARCH_BLOOM,
  549. {
  550. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  551. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  552. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  553. { LLM_TENSOR_OUTPUT, "output" },
  554. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  555. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  556. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  557. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  558. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  559. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  560. },
  561. },
  562. {
  563. LLM_ARCH_STABLELM,
  564. {
  565. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  566. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  567. { LLM_TENSOR_OUTPUT, "output" },
  568. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  569. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  570. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  571. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  572. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  573. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  574. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  575. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  576. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  577. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  578. },
  579. },
  580. {
  581. LLM_ARCH_QWEN,
  582. {
  583. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  584. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  585. { LLM_TENSOR_OUTPUT, "output" },
  586. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  587. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  588. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  589. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  590. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  591. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  592. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  593. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  594. },
  595. },
  596. {
  597. LLM_ARCH_QWEN2,
  598. {
  599. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  600. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  601. { LLM_TENSOR_OUTPUT, "output" },
  602. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  603. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  604. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  605. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  606. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  607. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  608. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  609. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  610. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  611. },
  612. },
  613. {
  614. LLM_ARCH_PHI2,
  615. {
  616. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  617. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  618. { LLM_TENSOR_OUTPUT, "output" },
  619. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  620. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  621. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  622. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  623. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  624. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  625. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  626. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  627. },
  628. },
  629. {
  630. LLM_ARCH_PLAMO,
  631. {
  632. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  633. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  634. { LLM_TENSOR_OUTPUT, "output" },
  635. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  636. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  637. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  638. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  639. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  640. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  641. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  642. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  643. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  644. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  645. },
  646. },
  647. {
  648. LLM_ARCH_CODESHELL,
  649. {
  650. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  651. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  652. { LLM_TENSOR_OUTPUT, "output" },
  653. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  654. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  655. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  656. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  657. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  658. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  659. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  660. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  661. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  662. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  663. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  664. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  665. },
  666. },
  667. {
  668. LLM_ARCH_ORION,
  669. {
  670. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  671. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  672. { LLM_TENSOR_OUTPUT, "output" },
  673. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  674. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  675. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  676. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  677. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  678. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  679. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  680. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  681. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  682. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  683. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  684. },
  685. },
  686. {
  687. LLM_ARCH_INTERNLM2,
  688. {
  689. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  690. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  691. { LLM_TENSOR_OUTPUT, "output" },
  692. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  693. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  694. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  695. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  696. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  697. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  698. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  699. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  700. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  701. },
  702. },
  703. {
  704. LLM_ARCH_MINICPM,
  705. {
  706. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  707. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  708. { LLM_TENSOR_OUTPUT, "output" },
  709. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  710. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  711. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  712. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  713. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  714. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  715. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  716. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  717. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  718. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  719. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  720. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  721. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  722. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  723. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  724. },
  725. },
  726. {
  727. LLM_ARCH_GEMMA,
  728. {
  729. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  730. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  731. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  732. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  733. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  734. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  735. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  736. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  737. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  738. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  739. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  740. },
  741. },
  742. {
  743. LLM_ARCH_UNKNOWN,
  744. {
  745. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  746. },
  747. },
  748. };
  749. static llm_arch llm_arch_from_string(const std::string & name) {
  750. for (const auto & kv : LLM_ARCH_NAMES) { // NOLINT
  751. if (kv.second == name) {
  752. return kv.first;
  753. }
  754. }
  755. return LLM_ARCH_UNKNOWN;
  756. }
  757. // helper to handle gguf constants
  758. // usage:
  759. //
  760. // const auto tn = LLM_TN(LLM_ARCH_LLAMA);
  761. //
  762. // std::string name = tn(LLM_TENSOR_OUTPUT); -> "output"
  763. // std::string name = tn(LLM_TENSOR_TOKEN_EMBD, "bias"); -> "token_embd.bias"
  764. // std::string name = tn(LLM_TENSOR_ATTN_NORM, "weight", 3); -> "blk.3.attn_norm.weight"
  765. //
  766. struct LLM_TN {
  767. LLM_TN(llm_arch arch) : arch(arch) {}
  768. llm_arch arch;
  769. std::string operator()(llm_tensor tensor) const {
  770. if (LLM_TENSOR_NAMES[arch].find(tensor) == LLM_TENSOR_NAMES[arch].end()) {
  771. return "__missing__";
  772. }
  773. return LLM_TENSOR_NAMES[arch].at(tensor);
  774. }
  775. std::string operator()(llm_tensor tensor, const std::string & suffix) const {
  776. if (LLM_TENSOR_NAMES[arch].find(tensor) == LLM_TENSOR_NAMES[arch].end()) {
  777. return "__missing__";
  778. }
  779. return LLM_TENSOR_NAMES[arch].at(tensor) + "." + suffix;
  780. }
  781. std::string operator()(llm_tensor tensor, int bid) const {
  782. if (LLM_TENSOR_NAMES[arch].find(tensor) == LLM_TENSOR_NAMES[arch].end()) {
  783. return "__missing__";
  784. }
  785. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid);
  786. }
  787. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid) const {
  788. if (LLM_TENSOR_NAMES[arch].find(tensor) == LLM_TENSOR_NAMES[arch].end()) {
  789. return "__missing__";
  790. }
  791. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid) + "." + suffix;
  792. }
  793. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid, int xid) const {
  794. if (LLM_TENSOR_NAMES[arch].find(tensor) == LLM_TENSOR_NAMES[arch].end()) {
  795. return "__missing__";
  796. }
  797. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid, xid) + "." + suffix;
  798. }
  799. };
  800. //
  801. // gguf helpers
  802. //
  803. static std::map<int32_t, const char *> LLAMA_ROPE_SCALING_TYPES = {
  804. { LLAMA_ROPE_SCALING_TYPE_NONE, "none" },
  805. { LLAMA_ROPE_SCALING_TYPE_LINEAR, "linear" },
  806. { LLAMA_ROPE_SCALING_TYPE_YARN, "yarn" },
  807. };
  808. static int32_t llama_rope_scaling_type_from_string(const std::string & name) {
  809. for (const auto & kv : LLAMA_ROPE_SCALING_TYPES) {
  810. if (kv.second == name) {
  811. return kv.first;
  812. }
  813. }
  814. return LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED;
  815. }
  816. static std::string gguf_data_to_str(enum gguf_type type, const void * data, int i) {
  817. switch (type) {
  818. case GGUF_TYPE_UINT8: return std::to_string(((const uint8_t *)data)[i]);
  819. case GGUF_TYPE_INT8: return std::to_string(((const int8_t *)data)[i]);
  820. case GGUF_TYPE_UINT16: return std::to_string(((const uint16_t *)data)[i]);
  821. case GGUF_TYPE_INT16: return std::to_string(((const int16_t *)data)[i]);
  822. case GGUF_TYPE_UINT32: return std::to_string(((const uint32_t *)data)[i]);
  823. case GGUF_TYPE_INT32: return std::to_string(((const int32_t *)data)[i]);
  824. case GGUF_TYPE_UINT64: return std::to_string(((const uint64_t *)data)[i]);
  825. case GGUF_TYPE_INT64: return std::to_string(((const int64_t *)data)[i]);
  826. case GGUF_TYPE_FLOAT32: return std::to_string(((const float *)data)[i]);
  827. case GGUF_TYPE_FLOAT64: return std::to_string(((const double *)data)[i]);
  828. case GGUF_TYPE_BOOL: return ((const bool *)data)[i] ? "true" : "false";
  829. default: return format("unknown type %d", type);
  830. }
  831. }
  832. static std::string gguf_kv_to_str(const struct gguf_context * ctx_gguf, int i) {
  833. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  834. switch (type) {
  835. case GGUF_TYPE_STRING:
  836. return gguf_get_val_str(ctx_gguf, i);
  837. case GGUF_TYPE_ARRAY:
  838. {
  839. const enum gguf_type arr_type = gguf_get_arr_type(ctx_gguf, i);
  840. int arr_n = gguf_get_arr_n(ctx_gguf, i);
  841. const void * data = gguf_get_arr_data(ctx_gguf, i);
  842. std::stringstream ss;
  843. ss << "[";
  844. for (int j = 0; j < arr_n; j++) {
  845. if (arr_type == GGUF_TYPE_STRING) {
  846. std::string val = gguf_get_arr_str(ctx_gguf, i, j);
  847. // escape quotes
  848. replace_all(val, "\\", "\\\\");
  849. replace_all(val, "\"", "\\\"");
  850. ss << '"' << val << '"';
  851. } else if (arr_type == GGUF_TYPE_ARRAY) {
  852. ss << "???";
  853. } else {
  854. ss << gguf_data_to_str(arr_type, data, j);
  855. }
  856. if (j < arr_n - 1) {
  857. ss << ", ";
  858. }
  859. }
  860. ss << "]";
  861. return ss.str();
  862. }
  863. default:
  864. return gguf_data_to_str(type, gguf_get_val_data(ctx_gguf, i), 0);
  865. }
  866. }
  867. //
  868. // ggml helpers
  869. //
  870. static void ggml_graph_compute_helper(std::vector<uint8_t> & buf, ggml_cgraph * graph, int n_threads) {
  871. struct ggml_cplan plan = ggml_graph_plan(graph, n_threads);
  872. if (plan.work_size > 0) {
  873. buf.resize(plan.work_size);
  874. plan.work_data = buf.data();
  875. }
  876. ggml_graph_compute(graph, &plan);
  877. }
  878. //
  879. // llama helpers
  880. //
  881. #if defined(_WIN32)
  882. static std::string llama_format_win_err(DWORD err) {
  883. LPSTR buf;
  884. size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  885. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, NULL);
  886. if (!size) {
  887. return "FormatMessageA failed";
  888. }
  889. std::string ret(buf, size);
  890. LocalFree(buf);
  891. return ret;
  892. }
  893. #endif
  894. template <typename T>
  895. struct no_init {
  896. T value;
  897. no_init() { /* do nothing */ }
  898. };
  899. struct llama_file {
  900. // use FILE * so we don't have to re-open the file to mmap
  901. FILE * fp;
  902. size_t size;
  903. llama_file(const char * fname, const char * mode) {
  904. fp = std::fopen(fname, mode);
  905. if (fp == NULL) {
  906. throw std::runtime_error(format("failed to open %s: %s", fname, strerror(errno)));
  907. }
  908. seek(0, SEEK_END);
  909. size = tell();
  910. seek(0, SEEK_SET);
  911. }
  912. size_t tell() const {
  913. #ifdef _WIN32
  914. __int64 ret = _ftelli64(fp);
  915. #else
  916. long ret = std::ftell(fp);
  917. #endif
  918. GGML_ASSERT(ret != -1); // this really shouldn't fail
  919. return (size_t) ret;
  920. }
  921. void seek(size_t offset, int whence) const {
  922. #ifdef _WIN32
  923. int ret = _fseeki64(fp, (__int64) offset, whence);
  924. #else
  925. int ret = std::fseek(fp, (long) offset, whence);
  926. #endif
  927. GGML_ASSERT(ret == 0); // same
  928. }
  929. void read_raw(void * ptr, size_t len) const {
  930. if (len == 0) {
  931. return;
  932. }
  933. errno = 0;
  934. std::size_t ret = std::fread(ptr, len, 1, fp);
  935. if (ferror(fp)) {
  936. throw std::runtime_error(format("read error: %s", strerror(errno)));
  937. }
  938. if (ret != 1) {
  939. throw std::runtime_error("unexpectedly reached end of file");
  940. }
  941. }
  942. uint32_t read_u32() const {
  943. uint32_t ret;
  944. read_raw(&ret, sizeof(ret));
  945. return ret;
  946. }
  947. void write_raw(const void * ptr, size_t len) const {
  948. if (len == 0) {
  949. return;
  950. }
  951. errno = 0;
  952. size_t ret = std::fwrite(ptr, len, 1, fp);
  953. if (ret != 1) {
  954. throw std::runtime_error(format("write error: %s", strerror(errno)));
  955. }
  956. }
  957. void write_u32(std::uint32_t val) const {
  958. write_raw(&val, sizeof(val));
  959. }
  960. ~llama_file() {
  961. if (fp) {
  962. std::fclose(fp);
  963. }
  964. }
  965. };
  966. struct llama_mmap {
  967. void * addr;
  968. size_t size;
  969. llama_mmap(const llama_mmap &) = delete;
  970. #ifdef _POSIX_MAPPED_FILES
  971. static constexpr bool SUPPORTED = true;
  972. // list of mapped fragments (first_offset, last_offset)
  973. std::vector<std::pair<size_t, size_t>> mapped_fragments;
  974. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1 /* -1 = max value */, bool numa = false) {
  975. size = file->size;
  976. int fd = fileno(file->fp);
  977. int flags = MAP_SHARED;
  978. // prefetch/readahead impairs performance on NUMA systems
  979. if (numa) { prefetch = 0; }
  980. #ifdef __linux__
  981. // advise the kernel to read the file sequentially (increases readahead)
  982. if (posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL)) {
  983. LLAMA_LOG_WARN("warning: posix_fadvise(.., POSIX_FADV_SEQUENTIAL) failed: %s\n",
  984. strerror(errno));
  985. }
  986. if (prefetch) { flags |= MAP_POPULATE; }
  987. #endif
  988. addr = mmap(NULL, file->size, PROT_READ, flags, fd, 0);
  989. if (addr == MAP_FAILED) { // NOLINT
  990. throw std::runtime_error(format("mmap failed: %s", strerror(errno)));
  991. }
  992. if (prefetch > 0) {
  993. // advise the kernel to preload the mapped memory
  994. if (posix_madvise(addr, std::min(file->size, prefetch), POSIX_MADV_WILLNEED)) {
  995. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_WILLNEED) failed: %s\n",
  996. strerror(errno));
  997. }
  998. }
  999. if (numa) {
  1000. // advise the kernel not to use readahead
  1001. // (because the next page might not belong on the same node)
  1002. if (posix_madvise(addr, file->size, POSIX_MADV_RANDOM)) {
  1003. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_RANDOM) failed: %s\n",
  1004. strerror(errno));
  1005. }
  1006. }
  1007. // initialize list of mapped_fragments
  1008. mapped_fragments.emplace_back(0, file->size);
  1009. }
  1010. static void align_range(size_t * first, size_t * last, size_t page_size) {
  1011. // align first to the next page
  1012. size_t offset_in_page = *first & (page_size - 1);
  1013. size_t offset_to_page = offset_in_page == 0 ? 0 : page_size - offset_in_page;
  1014. *first += offset_to_page;
  1015. // align last to the previous page
  1016. *last = *last & ~(page_size - 1);
  1017. if (*last <= *first) {
  1018. *last = *first;
  1019. }
  1020. }
  1021. // partially unmap the file in the range [first, last)
  1022. void unmap_fragment(size_t first, size_t last) {
  1023. // note: this function must not be called multiple times with overlapping ranges
  1024. // otherwise, there is a risk of invalidating addresses that have been repurposed for other mappings
  1025. int page_size = sysconf(_SC_PAGESIZE);
  1026. align_range(&first, &last, page_size);
  1027. size_t len = last - first;
  1028. if (len == 0) {
  1029. return;
  1030. }
  1031. GGML_ASSERT(first % page_size == 0);
  1032. GGML_ASSERT(last % page_size == 0);
  1033. GGML_ASSERT(last > first);
  1034. void * next_page_start = (uint8_t *) addr + first;
  1035. // unmap the range
  1036. if (munmap(next_page_start, len)) {
  1037. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  1038. }
  1039. // update the list of mapped fragments to avoid unmapping the same range again in the destructor
  1040. std::vector<std::pair<size_t, size_t>> new_mapped_fragments;
  1041. for (const auto & frag : mapped_fragments) {
  1042. if (frag.first < first && frag.second > last) {
  1043. // the range is in the middle of the fragment, split it
  1044. new_mapped_fragments.emplace_back(frag.first, first);
  1045. new_mapped_fragments.emplace_back(last, frag.second);
  1046. } else if (frag.first < first && frag.second > first) {
  1047. // the range starts in the middle of the fragment
  1048. new_mapped_fragments.emplace_back(frag.first, first);
  1049. } else if (frag.first < last && frag.second > last) {
  1050. // the range ends in the middle of the fragment
  1051. new_mapped_fragments.emplace_back(last, frag.second);
  1052. } else if (frag.first >= first && frag.second <= last) {
  1053. // the range covers the entire fragment
  1054. } else {
  1055. // the range is outside the fragment
  1056. new_mapped_fragments.push_back(frag);
  1057. }
  1058. }
  1059. mapped_fragments = std::move(new_mapped_fragments);
  1060. }
  1061. ~llama_mmap() {
  1062. for (const auto & frag : mapped_fragments) {
  1063. if (munmap((char *) addr + frag.first, frag.second - frag.first)) {
  1064. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  1065. }
  1066. }
  1067. }
  1068. #elif defined(_WIN32)
  1069. static constexpr bool SUPPORTED = true;
  1070. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1, bool numa = false) {
  1071. GGML_UNUSED(numa);
  1072. size = file->size;
  1073. HANDLE hFile = (HANDLE) _get_osfhandle(_fileno(file->fp));
  1074. HANDLE hMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
  1075. if (hMapping == NULL) {
  1076. DWORD error = GetLastError();
  1077. throw std::runtime_error(format("CreateFileMappingA failed: %s", llama_format_win_err(error).c_str()));
  1078. }
  1079. addr = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
  1080. DWORD error = GetLastError();
  1081. CloseHandle(hMapping);
  1082. if (addr == NULL) {
  1083. throw std::runtime_error(format("MapViewOfFile failed: %s", llama_format_win_err(error).c_str()));
  1084. }
  1085. if (prefetch > 0) {
  1086. #if _WIN32_WINNT >= 0x602
  1087. // PrefetchVirtualMemory is only present on Windows 8 and above, so we dynamically load it
  1088. BOOL (WINAPI *pPrefetchVirtualMemory) (HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG);
  1089. HMODULE hKernel32 = GetModuleHandleW(L"kernel32.dll");
  1090. // may fail on pre-Windows 8 systems
  1091. pPrefetchVirtualMemory = reinterpret_cast<decltype(pPrefetchVirtualMemory)> (GetProcAddress(hKernel32, "PrefetchVirtualMemory"));
  1092. if (pPrefetchVirtualMemory) {
  1093. // advise the kernel to preload the mapped memory
  1094. WIN32_MEMORY_RANGE_ENTRY range;
  1095. range.VirtualAddress = addr;
  1096. range.NumberOfBytes = (SIZE_T) std::min(size, prefetch);
  1097. if (!pPrefetchVirtualMemory(GetCurrentProcess(), 1, &range, 0)) {
  1098. LLAMA_LOG_WARN("warning: PrefetchVirtualMemory failed: %s\n",
  1099. llama_format_win_err(GetLastError()).c_str());
  1100. }
  1101. }
  1102. #else
  1103. throw std::runtime_error("PrefetchVirtualMemory unavailable");
  1104. #endif
  1105. }
  1106. }
  1107. void unmap_fragment(size_t first, size_t last) {
  1108. // not supported
  1109. GGML_UNUSED(first);
  1110. GGML_UNUSED(last);
  1111. }
  1112. ~llama_mmap() {
  1113. if (!UnmapViewOfFile(addr)) {
  1114. LLAMA_LOG_WARN("warning: UnmapViewOfFile failed: %s\n",
  1115. llama_format_win_err(GetLastError()).c_str());
  1116. }
  1117. }
  1118. #else
  1119. static constexpr bool SUPPORTED = false;
  1120. llama_mmap(struct llama_file * file, size_t prefetch = -1, bool numa = false) {
  1121. GGML_UNUSED(file);
  1122. GGML_UNUSED(prefetch);
  1123. GGML_UNUSED(numa);
  1124. throw std::runtime_error("mmap not supported");
  1125. }
  1126. void unmap_fragment(size_t first, size_t last) {
  1127. GGML_UNUSED(first);
  1128. GGML_UNUSED(last);
  1129. throw std::runtime_error("mmap not supported");
  1130. }
  1131. #endif
  1132. };
  1133. // Represents some region of memory being locked using mlock or VirtualLock;
  1134. // will automatically unlock on destruction.
  1135. struct llama_mlock {
  1136. void * addr = NULL;
  1137. size_t size = 0;
  1138. bool failed_already = false;
  1139. llama_mlock() {}
  1140. llama_mlock(const llama_mlock &) = delete;
  1141. ~llama_mlock() {
  1142. if (size) {
  1143. raw_unlock(addr, size);
  1144. }
  1145. }
  1146. void init(void * ptr) {
  1147. GGML_ASSERT(addr == NULL && size == 0); // NOLINT
  1148. addr = ptr;
  1149. }
  1150. void grow_to(size_t target_size) {
  1151. GGML_ASSERT(addr);
  1152. if (failed_already) {
  1153. return;
  1154. }
  1155. size_t granularity = lock_granularity();
  1156. target_size = (target_size + granularity - 1) & ~(granularity - 1);
  1157. if (target_size > size) {
  1158. if (raw_lock((uint8_t *) addr + size, target_size - size)) {
  1159. size = target_size;
  1160. } else {
  1161. failed_already = true;
  1162. }
  1163. }
  1164. }
  1165. #ifdef _POSIX_MEMLOCK_RANGE
  1166. static constexpr bool SUPPORTED = true;
  1167. static size_t lock_granularity() {
  1168. return (size_t) sysconf(_SC_PAGESIZE);
  1169. }
  1170. #ifdef __APPLE__
  1171. #define MLOCK_SUGGESTION \
  1172. "Try increasing the sysctl values 'vm.user_wire_limit' and 'vm.global_user_wire_limit' and/or " \
  1173. "decreasing 'vm.global_no_user_wire_amount'. Also try increasing RLIMIT_MEMLOCK (ulimit -l).\n"
  1174. #else
  1175. #define MLOCK_SUGGESTION \
  1176. "Try increasing RLIMIT_MEMLOCK ('ulimit -l' as root).\n"
  1177. #endif
  1178. bool raw_lock(const void * addr, size_t size) const {
  1179. if (!mlock(addr, size)) {
  1180. return true;
  1181. }
  1182. char* errmsg = std::strerror(errno);
  1183. bool suggest = (errno == ENOMEM);
  1184. // Check if the resource limit is fine after all
  1185. struct rlimit lock_limit;
  1186. if (suggest && getrlimit(RLIMIT_MEMLOCK, &lock_limit)) {
  1187. suggest = false;
  1188. }
  1189. if (suggest && (lock_limit.rlim_max > lock_limit.rlim_cur + size)) {
  1190. suggest = false;
  1191. }
  1192. LLAMA_LOG_WARN("warning: failed to mlock %zu-byte buffer (after previously locking %zu bytes): %s\n%s",
  1193. size, this->size, errmsg, suggest ? MLOCK_SUGGESTION : "");
  1194. return false;
  1195. }
  1196. #undef MLOCK_SUGGESTION
  1197. static void raw_unlock(void * addr, size_t size) {
  1198. if (munlock(addr, size)) {
  1199. LLAMA_LOG_WARN("warning: failed to munlock buffer: %s\n", std::strerror(errno));
  1200. }
  1201. }
  1202. #elif defined(_WIN32)
  1203. static constexpr bool SUPPORTED = true;
  1204. static size_t lock_granularity() {
  1205. SYSTEM_INFO si;
  1206. GetSystemInfo(&si);
  1207. return (size_t) si.dwPageSize;
  1208. }
  1209. bool raw_lock(void * ptr, size_t len) const {
  1210. for (int tries = 1; ; tries++) {
  1211. if (VirtualLock(ptr, len)) {
  1212. return true;
  1213. }
  1214. if (tries == 2) {
  1215. LLAMA_LOG_WARN("warning: failed to VirtualLock %zu-byte buffer (after previously locking %zu bytes): %s\n",
  1216. len, size, llama_format_win_err(GetLastError()).c_str());
  1217. return false;
  1218. }
  1219. // It failed but this was only the first try; increase the working
  1220. // set size and try again.
  1221. SIZE_T min_ws_size, max_ws_size;
  1222. if (!GetProcessWorkingSetSize(GetCurrentProcess(), &min_ws_size, &max_ws_size)) {
  1223. LLAMA_LOG_WARN("warning: GetProcessWorkingSetSize failed: %s\n",
  1224. llama_format_win_err(GetLastError()).c_str());
  1225. return false;
  1226. }
  1227. // Per MSDN: "The maximum number of pages that a process can lock
  1228. // is equal to the number of pages in its minimum working set minus
  1229. // a small overhead."
  1230. // Hopefully a megabyte is enough overhead:
  1231. size_t increment = len + 1048576;
  1232. // The minimum must be <= the maximum, so we need to increase both:
  1233. min_ws_size += increment;
  1234. max_ws_size += increment;
  1235. if (!SetProcessWorkingSetSize(GetCurrentProcess(), min_ws_size, max_ws_size)) {
  1236. LLAMA_LOG_WARN("warning: SetProcessWorkingSetSize failed: %s\n",
  1237. llama_format_win_err(GetLastError()).c_str());
  1238. return false;
  1239. }
  1240. }
  1241. }
  1242. static void raw_unlock(void * ptr, size_t len) {
  1243. if (!VirtualUnlock(ptr, len)) {
  1244. LLAMA_LOG_WARN("warning: failed to VirtualUnlock buffer: %s\n",
  1245. llama_format_win_err(GetLastError()).c_str());
  1246. }
  1247. }
  1248. #else
  1249. static constexpr bool SUPPORTED = false;
  1250. static size_t lock_granularity() {
  1251. return (size_t) 65536;
  1252. }
  1253. bool raw_lock(const void * addr, size_t len) const {
  1254. LLAMA_LOG_WARN("warning: mlock not supported on this system\n");
  1255. return false;
  1256. }
  1257. static void raw_unlock(const void * addr, size_t len) {}
  1258. #endif
  1259. };
  1260. static std::string llama_token_to_piece(const struct llama_context * ctx, llama_token token) {
  1261. std::vector<char> result(8, 0);
  1262. const int n_tokens = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1263. if (n_tokens < 0) {
  1264. result.resize(-n_tokens);
  1265. int check = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1266. GGML_ASSERT(check == -n_tokens);
  1267. }
  1268. else {
  1269. result.resize(n_tokens);
  1270. }
  1271. return std::string(result.data(), result.size());
  1272. }
  1273. static ggml_backend_buffer_type_t llama_default_buffer_type_cpu(bool host_buffer) {
  1274. ggml_backend_buffer_type_t buft = nullptr;
  1275. #if defined(GGML_USE_CUBLAS)
  1276. // host buffers should only be used when data is expected to be copied to/from the GPU
  1277. if (host_buffer) {
  1278. buft = ggml_backend_cuda_host_buffer_type();
  1279. }
  1280. #elif defined(GGML_USE_SYCL)
  1281. buft = ggml_backend_sycl_host_buffer_type();
  1282. #elif defined(GGML_USE_CPU_HBM)
  1283. buft = ggml_backend_cpu_hbm_buffer_type();
  1284. #elif defined(GGML_USE_VULKAN)
  1285. if (host_buffer) {
  1286. buft = ggml_backend_vk_host_buffer_type();
  1287. }
  1288. #endif
  1289. if (buft == nullptr) {
  1290. buft = ggml_backend_cpu_buffer_type();
  1291. }
  1292. return buft;
  1293. GGML_UNUSED(host_buffer);
  1294. }
  1295. static ggml_backend_buffer_type_t llama_default_buffer_type_offload(int gpu) {
  1296. ggml_backend_buffer_type_t buft = nullptr;
  1297. #ifdef GGML_USE_METAL
  1298. buft = ggml_backend_metal_buffer_type();
  1299. #elif defined(GGML_USE_CUBLAS)
  1300. buft = ggml_backend_cuda_buffer_type(gpu);
  1301. #elif defined(GGML_USE_VULKAN)
  1302. buft = ggml_backend_vk_buffer_type(gpu);
  1303. #elif defined(GGML_USE_SYCL)
  1304. buft = ggml_backend_sycl_buffer_type(gpu);
  1305. #elif defined(GGML_USE_CLBLAST)
  1306. buft = ggml_backend_opencl_buffer_type();
  1307. #elif defined(GGML_USE_KOMPUTE)
  1308. buft = ggml_backend_kompute_buffer_type(gpu);
  1309. if (buft == nullptr) {
  1310. LLAMA_LOG_WARN("%s: cannot use GPU %d, check `vulkaninfo --summary`\n", __func__, gpu);
  1311. }
  1312. #endif
  1313. if (buft == nullptr) {
  1314. buft = llama_default_buffer_type_cpu(true);
  1315. }
  1316. return buft;
  1317. GGML_UNUSED(gpu);
  1318. }
  1319. static ggml_backend_buffer_type_t llama_default_buffer_type_split(int fallback_gpu, const float * tensor_split) {
  1320. ggml_backend_buffer_type_t buft = nullptr;
  1321. #ifdef GGML_USE_CUBLAS
  1322. if (ggml_backend_cuda_get_device_count() > 1) {
  1323. buft = ggml_backend_cuda_split_buffer_type(tensor_split);
  1324. }
  1325. #endif
  1326. if (buft == nullptr) {
  1327. buft = llama_default_buffer_type_offload(fallback_gpu);
  1328. }
  1329. return buft;
  1330. GGML_UNUSED(tensor_split);
  1331. }
  1332. static size_t llama_get_device_count() {
  1333. #if defined(GGML_USE_CUBLAS)
  1334. return ggml_backend_cuda_get_device_count();
  1335. #elif defined(GGML_USE_VULKAN)
  1336. return ggml_backend_vk_get_device_count();
  1337. #else
  1338. return 1;
  1339. #endif
  1340. }
  1341. static size_t llama_get_device_memory(int device) {
  1342. #if defined(GGML_USE_CUBLAS)
  1343. size_t total;
  1344. size_t free;
  1345. ggml_backend_cuda_get_device_memory(device, &total, &free);
  1346. return free;
  1347. #elif defined(GGML_USE_VULKAN)
  1348. size_t total;
  1349. size_t free;
  1350. ggml_backend_vk_get_device_memory(device, &total, &free);
  1351. return free;
  1352. #else
  1353. return 1;
  1354. GGML_UNUSED(device);
  1355. #endif
  1356. }
  1357. //
  1358. // globals
  1359. //
  1360. struct llama_state {
  1361. llama_state() {
  1362. #ifdef GGML_USE_METAL
  1363. ggml_backend_metal_log_set_callback(log_callback, log_callback_user_data);
  1364. #endif
  1365. }
  1366. // We save the log callback globally
  1367. ggml_log_callback log_callback = llama_log_callback_default;
  1368. void * log_callback_user_data = nullptr;
  1369. };
  1370. static llama_state g_state;
  1371. // available llama models
  1372. enum e_model {
  1373. MODEL_UNKNOWN,
  1374. MODEL_17M,
  1375. MODEL_22M,
  1376. MODEL_33M,
  1377. MODEL_109M,
  1378. MODEL_137M,
  1379. MODEL_335M,
  1380. MODEL_0_5B,
  1381. MODEL_1B,
  1382. MODEL_2B,
  1383. MODEL_3B,
  1384. MODEL_4B,
  1385. MODEL_7B,
  1386. MODEL_8B,
  1387. MODEL_13B,
  1388. MODEL_14B,
  1389. MODEL_15B,
  1390. MODEL_20B,
  1391. MODEL_30B,
  1392. MODEL_34B,
  1393. MODEL_40B,
  1394. MODEL_65B,
  1395. MODEL_70B,
  1396. MODEL_SMALL,
  1397. MODEL_MEDIUM,
  1398. MODEL_LARGE,
  1399. MODEL_XL,
  1400. };
  1401. static const size_t kiB = 1024;
  1402. static const size_t MiB = 1024*kiB;
  1403. static const size_t GiB = 1024*MiB;
  1404. struct llama_hparams {
  1405. bool vocab_only;
  1406. bool rope_finetuned;
  1407. uint32_t n_vocab;
  1408. uint32_t n_ctx_train; // context size the model was trained on
  1409. uint32_t n_embd;
  1410. uint32_t n_head;
  1411. uint32_t n_head_kv;
  1412. uint32_t n_layer;
  1413. uint32_t n_rot;
  1414. 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
  1415. uint32_t n_embd_head_v; // dimension of values (d_v) aka n_embd_head
  1416. uint32_t n_ff;
  1417. uint32_t n_expert = 0;
  1418. uint32_t n_expert_used = 0;
  1419. uint32_t n_vocab_type = 0; // for BERT-style token types
  1420. float f_norm_eps;
  1421. float f_norm_rms_eps;
  1422. float rope_freq_base_train;
  1423. float rope_freq_scale_train;
  1424. uint32_t n_yarn_orig_ctx;
  1425. int32_t rope_scaling_type_train;
  1426. float f_clamp_kqv = 0.0f;
  1427. float f_max_alibi_bias = 0.0f;
  1428. bool causal_attn = true;
  1429. bool need_kq_pos = false;
  1430. enum llama_pooling_type pooling_type = LLAMA_POOLING_TYPE_NONE;
  1431. enum llama_rope_type rope_type = LLAMA_ROPE_TYPE_NONE;
  1432. bool operator!=(const llama_hparams & other) const {
  1433. if (this->vocab_only != other.vocab_only) return true;
  1434. if (this->n_vocab != other.n_vocab) return true;
  1435. if (this->n_ctx_train != other.n_ctx_train) return true;
  1436. if (this->n_embd != other.n_embd) return true;
  1437. if (this->n_head != other.n_head) return true;
  1438. if (this->n_head_kv != other.n_head_kv) return true;
  1439. if (this->n_layer != other.n_layer) return true;
  1440. if (this->n_rot != other.n_rot) return true;
  1441. if (this->n_embd_head_k != other.n_embd_head_k) return true;
  1442. if (this->n_embd_head_v != other.n_embd_head_v) return true;
  1443. if (this->n_ff != other.n_ff) return true;
  1444. if (this->n_expert != other.n_expert) return true;
  1445. if (this->n_expert_used != other.n_expert_used) return true;
  1446. if (this->rope_finetuned != other.rope_finetuned) return true;
  1447. if (this->n_yarn_orig_ctx != other.n_yarn_orig_ctx) return true;
  1448. const float EPSILON = 1e-9f;
  1449. if (!is_float_close(this->f_norm_eps, other.f_norm_eps, EPSILON)) return true;
  1450. if (!is_float_close(this->f_norm_rms_eps, other.f_norm_rms_eps, EPSILON)) return true;
  1451. if (!is_float_close(this->rope_freq_base_train, other.rope_freq_base_train, EPSILON)) return true;
  1452. if (!is_float_close(this->rope_freq_scale_train, other.rope_freq_scale_train, EPSILON)) return true;
  1453. return false;
  1454. }
  1455. uint32_t n_gqa() const {
  1456. return n_head/n_head_kv;
  1457. }
  1458. uint32_t n_embd_k_gqa() const { // dimension of key embeddings across all k-v heads
  1459. return n_embd_head_k * n_head_kv;
  1460. }
  1461. uint32_t n_embd_v_gqa() const { // dimension of value embeddings across all k-v heads
  1462. return n_embd_head_v * n_head_kv;
  1463. }
  1464. };
  1465. struct llama_cparams {
  1466. uint32_t n_ctx; // context size used during inference
  1467. uint32_t n_batch;
  1468. uint32_t n_threads; // number of threads to use for generation
  1469. uint32_t n_threads_batch; // number of threads to use for batch processing
  1470. float rope_freq_base;
  1471. float rope_freq_scale;
  1472. uint32_t n_yarn_orig_ctx;
  1473. // These hyperparameters are not exposed in GGUF, because all
  1474. // existing YaRN models use the same values for them.
  1475. float yarn_ext_factor;
  1476. float yarn_attn_factor;
  1477. float yarn_beta_fast;
  1478. float yarn_beta_slow;
  1479. float defrag_thold;
  1480. bool mul_mat_q;
  1481. bool offload_kqv;
  1482. bool do_pooling;
  1483. ggml_backend_sched_eval_callback cb_eval;
  1484. void * cb_eval_user_data;
  1485. };
  1486. struct llama_layer {
  1487. // normalization
  1488. struct ggml_tensor * attn_norm;
  1489. struct ggml_tensor * attn_norm_b;
  1490. struct ggml_tensor * attn_norm_2;
  1491. struct ggml_tensor * attn_norm_2_b;
  1492. struct ggml_tensor * attn_q_norm;
  1493. struct ggml_tensor * attn_q_norm_b;
  1494. struct ggml_tensor * attn_k_norm;
  1495. struct ggml_tensor * attn_k_norm_b;
  1496. struct ggml_tensor * attn_out_norm;
  1497. struct ggml_tensor * attn_out_norm_b;
  1498. // attention
  1499. struct ggml_tensor * wq;
  1500. struct ggml_tensor * wk;
  1501. struct ggml_tensor * wv;
  1502. struct ggml_tensor * wo;
  1503. struct ggml_tensor * wqkv;
  1504. // attention bias
  1505. struct ggml_tensor * bq;
  1506. struct ggml_tensor * bk;
  1507. struct ggml_tensor * bv;
  1508. struct ggml_tensor * bo;
  1509. struct ggml_tensor * bqkv;
  1510. // normalization
  1511. struct ggml_tensor * ffn_norm;
  1512. struct ggml_tensor * ffn_norm_b;
  1513. struct ggml_tensor * layer_out_norm;
  1514. struct ggml_tensor * layer_out_norm_b;
  1515. // ff
  1516. struct ggml_tensor * ffn_gate; // w1
  1517. struct ggml_tensor * ffn_down; // w2
  1518. struct ggml_tensor * ffn_up; // w3
  1519. // ff MoE
  1520. struct ggml_tensor * ffn_gate_inp;
  1521. struct ggml_tensor * ffn_gate_exp[LLAMA_MAX_EXPERTS];
  1522. struct ggml_tensor * ffn_down_exp[LLAMA_MAX_EXPERTS];
  1523. struct ggml_tensor * ffn_up_exp [LLAMA_MAX_EXPERTS];
  1524. // ff bias
  1525. struct ggml_tensor * ffn_down_b; // b2
  1526. struct ggml_tensor * ffn_up_b; // b3
  1527. struct ggml_tensor * ffn_act;
  1528. };
  1529. struct llama_kv_cell {
  1530. llama_pos pos = -1;
  1531. llama_pos delta = 0;
  1532. std::set<llama_seq_id> seq_id;
  1533. bool has_seq_id(const llama_seq_id & id) const {
  1534. return seq_id.find(id) != seq_id.end();
  1535. }
  1536. bool is_empty() const {
  1537. return seq_id.empty();
  1538. }
  1539. bool is_same_seq(const llama_kv_cell & other) const {
  1540. return seq_id == other.seq_id;
  1541. }
  1542. };
  1543. // ring-buffer of cached KV data
  1544. struct llama_kv_cache {
  1545. bool has_shift = false;
  1546. bool do_defrag = false;
  1547. // Note: The value of head isn't only used to optimize searching
  1548. // for a free KV slot. llama_decode_internal also uses it, so it
  1549. // cannot be freely changed after a slot has been allocated.
  1550. uint32_t head = 0;
  1551. uint32_t size = 0;
  1552. uint32_t used = 0; // used cells (i.e. at least one seq_id)
  1553. // computed before each graph build
  1554. uint32_t n = 0;
  1555. ggml_type type_k = GGML_TYPE_F16;
  1556. ggml_type type_v = GGML_TYPE_F16;
  1557. std::vector<llama_kv_cell> cells;
  1558. std::vector<struct ggml_tensor *> k_l; // per layer
  1559. std::vector<struct ggml_tensor *> v_l;
  1560. std::vector<struct ggml_context *> ctxs;
  1561. std::vector<ggml_backend_buffer_t> bufs;
  1562. size_t total_size() const {
  1563. size_t size = 0;
  1564. for (ggml_backend_buffer_t buf : bufs) {
  1565. size += ggml_backend_buffer_get_size(buf);
  1566. }
  1567. return size;
  1568. }
  1569. ~llama_kv_cache() {
  1570. for (struct ggml_context * ctx : ctxs) {
  1571. ggml_free(ctx);
  1572. }
  1573. for (ggml_backend_buffer_t buf : bufs) {
  1574. ggml_backend_buffer_free(buf);
  1575. }
  1576. }
  1577. };
  1578. struct llama_vocab {
  1579. using id = int32_t;
  1580. using token = std::string;
  1581. using ttype = llama_token_type;
  1582. struct token_data {
  1583. token text;
  1584. float score;
  1585. ttype type;
  1586. };
  1587. enum llama_vocab_type type = LLAMA_VOCAB_TYPE_SPM;
  1588. std::unordered_map<token, id> token_to_id;
  1589. std::vector<token_data> id_to_token;
  1590. std::unordered_map<token, id> special_tokens_cache;
  1591. std::map<std::pair<std::string, std::string>, int> bpe_ranks;
  1592. // default LLaMA special tokens
  1593. id special_bos_id = 1;
  1594. id special_eos_id = 2;
  1595. id special_unk_id = 0;
  1596. id special_sep_id = -1;
  1597. id special_pad_id = -1;
  1598. int special_add_bos = -1; // -1 unknown, 1 add, 0 don't add.
  1599. int special_add_eos = -1; // -1 unknown, 1 add, 0 don't add.
  1600. id linefeed_id = 13;
  1601. id special_prefix_id = 32007;
  1602. id special_middle_id = 32009;
  1603. id special_suffix_id = 32008;
  1604. id special_eot_id = 32010;
  1605. bool add_space_prefix = true;
  1606. int find_bpe_rank(const std::string & token_left, const std::string & token_right) const {
  1607. GGML_ASSERT(token_left.find(' ') == std::string::npos);
  1608. GGML_ASSERT(token_left.find('\n') == std::string::npos);
  1609. GGML_ASSERT(token_right.find(' ') == std::string::npos);
  1610. GGML_ASSERT(token_right.find('\n') == std::string::npos);
  1611. auto it = bpe_ranks.find(std::make_pair(token_left, token_right));
  1612. if (it == bpe_ranks.end()) {
  1613. return -1;
  1614. }
  1615. return it->second;
  1616. }
  1617. };
  1618. struct llama_model {
  1619. e_model type = MODEL_UNKNOWN;
  1620. llm_arch arch = LLM_ARCH_UNKNOWN;
  1621. llama_ftype ftype = LLAMA_FTYPE_ALL_F32;
  1622. std::string name = "n/a";
  1623. llama_hparams hparams = {};
  1624. llama_vocab vocab;
  1625. struct ggml_tensor * tok_embd;
  1626. struct ggml_tensor * type_embd;
  1627. struct ggml_tensor * pos_embd;
  1628. struct ggml_tensor * tok_norm;
  1629. struct ggml_tensor * tok_norm_b;
  1630. struct ggml_tensor * output_norm;
  1631. struct ggml_tensor * output_norm_b;
  1632. struct ggml_tensor * output;
  1633. struct ggml_tensor * output_b;
  1634. std::vector<llama_layer> layers;
  1635. llama_split_mode split_mode;
  1636. int main_gpu;
  1637. int n_gpu_layers;
  1638. // gguf metadata
  1639. std::unordered_map<std::string, std::string> gguf_kv;
  1640. // layer -> buffer type mapping
  1641. struct layer_buft {
  1642. layer_buft() : buft_matrix(nullptr), buft(nullptr) {}
  1643. layer_buft(ggml_backend_buffer_type_t matrix) : buft_matrix(matrix), buft(matrix) {}
  1644. layer_buft(ggml_backend_buffer_type_t matrix, ggml_backend_buffer_type_t other) : buft_matrix(matrix), buft(other) {}
  1645. ggml_backend_buffer_type_t buft_matrix; // matrices only - used by split buffers and backends that support only matrix multiplication
  1646. ggml_backend_buffer_type_t buft; // everything else
  1647. };
  1648. layer_buft buft_input;
  1649. layer_buft buft_output;
  1650. std::vector<layer_buft> buft_layer;
  1651. // contexts where the model tensors metadata is stored
  1652. std::vector<struct ggml_context *> ctxs;
  1653. // the model memory buffers for the tensor data
  1654. std::vector<ggml_backend_buffer_t> bufs;
  1655. // model memory mapped file
  1656. std::unique_ptr<llama_mmap> mapping;
  1657. // objects representing data potentially being locked in memory
  1658. std::vector<std::unique_ptr<llama_mlock>> mlock_bufs;
  1659. llama_mlock mlock_mmap;
  1660. // for quantize-stats only
  1661. std::vector<std::pair<std::string, struct ggml_tensor *>> tensors_by_name;
  1662. int64_t t_load_us = 0;
  1663. int64_t t_start_us = 0;
  1664. ~llama_model() {
  1665. for (struct ggml_context * ctx : ctxs) {
  1666. ggml_free(ctx);
  1667. }
  1668. for (ggml_backend_buffer_t buf : bufs) {
  1669. ggml_backend_buffer_free(buf);
  1670. }
  1671. }
  1672. };
  1673. struct llama_context {
  1674. llama_context(const llama_model & model) : model(model), t_start_us(model.t_start_us), t_load_us(model.t_load_us) {}
  1675. ~llama_context() {
  1676. ggml_backend_sched_free(sched);
  1677. for (ggml_backend_t backend : backends) {
  1678. ggml_backend_free(backend);
  1679. }
  1680. #ifdef GGML_USE_VULKAN
  1681. ggml_vk_free_cpu_assist();
  1682. #endif
  1683. ggml_backend_buffer_free(buf_input);
  1684. ggml_free(ctx_input);
  1685. }
  1686. llama_cparams cparams;
  1687. std::vector<ggml_backend_t> backends;
  1688. #ifdef GGML_USE_METAL
  1689. ggml_backend_t backend_metal = nullptr;
  1690. #endif
  1691. ggml_backend_t backend_cpu = nullptr;
  1692. const llama_model & model;
  1693. // key + value cache for the self attention
  1694. struct llama_kv_cache kv_self;
  1695. std::mt19937 rng;
  1696. bool has_evaluated_once = false;
  1697. int64_t t_start_us;
  1698. int64_t t_load_us;
  1699. int64_t t_sample_us = 0;
  1700. int64_t t_p_eval_us = 0;
  1701. int64_t t_eval_us = 0;
  1702. int32_t n_sample = 0; // number of tokens sampled
  1703. int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1)
  1704. int32_t n_eval = 0; // number of eval calls
  1705. // decode output (2-dimensional array: [n_tokens][n_vocab])
  1706. std::vector<float> logits;
  1707. #ifndef NDEBUG
  1708. // guard against access to unset logits
  1709. std::vector<bool> logits_valid;
  1710. #endif
  1711. bool logits_all = false;
  1712. // input embedding (1-dimensional array: [n_embd])
  1713. std::vector<float> embedding;
  1714. // memory buffers used to evaluate the model
  1715. std::vector<uint8_t> buf_compute_meta;
  1716. ggml_backend_sched_t sched = nullptr;
  1717. // input tensors
  1718. ggml_backend_buffer_t buf_input = nullptr;
  1719. ggml_context * ctx_input = nullptr;
  1720. struct ggml_tensor * inp_tokens; // I32 [n_batch]
  1721. struct ggml_tensor * inp_embd; // F32 [n_embd, n_batch]
  1722. struct ggml_tensor * inp_pos; // I32 [n_batch]
  1723. struct ggml_tensor * inp_KQ_mask; // F32 [n_ctx, n_batch]
  1724. struct ggml_tensor * inp_KQ_pos; // F32 [n_ctx]
  1725. struct ggml_tensor * inp_K_shift; // I32 [n_ctx]
  1726. struct ggml_tensor * inp_mean; // F32 [n_batch, n_batch]
  1727. struct ggml_tensor * inp_cls; // I32 [n_batch]
  1728. #ifdef GGML_USE_MPI
  1729. ggml_mpi_context * ctx_mpi = NULL;
  1730. #endif
  1731. };
  1732. //
  1733. // kv cache helpers
  1734. //
  1735. static bool llama_kv_cache_init(
  1736. struct llama_kv_cache & cache,
  1737. const llama_model & model,
  1738. ggml_type type_k,
  1739. ggml_type type_v,
  1740. uint32_t n_ctx,
  1741. bool offload) {
  1742. const struct llama_hparams & hparams = model.hparams;
  1743. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  1744. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  1745. const int64_t n_layer = hparams.n_layer;
  1746. cache.has_shift = false;
  1747. cache.head = 0;
  1748. cache.size = n_ctx;
  1749. cache.used = 0;
  1750. cache.type_k = type_k;
  1751. cache.type_v = type_v;
  1752. cache.cells.clear();
  1753. cache.cells.resize(n_ctx);
  1754. #ifdef GGML_USE_CLBLAST
  1755. offload = false;
  1756. #endif
  1757. // count used buffer types
  1758. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  1759. if (offload) {
  1760. for (int64_t i = 0; i < n_layer; ++i) {
  1761. buft_layer_count[model.buft_layer[i].buft]++;
  1762. }
  1763. } else {
  1764. buft_layer_count[llama_default_buffer_type_cpu(true)] = n_layer;
  1765. }
  1766. // create a context for each buffer type
  1767. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  1768. for (auto & it : buft_layer_count) {
  1769. int n_layers = it.second;
  1770. struct ggml_init_params params = {
  1771. /*.mem_size =*/ 2u*n_layers*ggml_tensor_overhead(),
  1772. /*.mem_buffer =*/ NULL,
  1773. /*.no_alloc =*/ true,
  1774. };
  1775. ggml_context * ctx = ggml_init(params);
  1776. if (!ctx) {
  1777. LLAMA_LOG_ERROR("%s: failed to allocate context for kv cache\n", __func__);
  1778. return false;
  1779. }
  1780. ctx_map[it.first] = ctx;
  1781. cache.ctxs.push_back(ctx);
  1782. }
  1783. cache.k_l.reserve(n_layer);
  1784. cache.v_l.reserve(n_layer);
  1785. for (int i = 0; i < (int) n_layer; i++) {
  1786. struct ggml_context * ctx = offload ? ctx_map.at(model.buft_layer[i].buft) : cache.ctxs.front();
  1787. ggml_tensor * k = ggml_new_tensor_1d(ctx, type_k, n_embd_k_gqa*n_ctx);
  1788. ggml_tensor * v = ggml_new_tensor_1d(ctx, type_v, n_embd_v_gqa*n_ctx);
  1789. ggml_format_name(k, "cache_k_l%d", i);
  1790. ggml_format_name(v, "cache_v_l%d", i);
  1791. cache.k_l.push_back(k);
  1792. cache.v_l.push_back(v);
  1793. }
  1794. // allocate tensors and initialize the buffers to avoid NaNs in the padding
  1795. for (auto it : ctx_map) {
  1796. ggml_backend_buffer_type_t buft = it.first;
  1797. ggml_context * ctx = it.second;
  1798. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  1799. if (!buf) {
  1800. LLAMA_LOG_ERROR("%s: failed to allocate buffer for kv cache\n", __func__);
  1801. return false;
  1802. }
  1803. ggml_backend_buffer_clear(buf, 0);
  1804. 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);
  1805. cache.bufs.push_back(buf);
  1806. }
  1807. return true;
  1808. }
  1809. // find an empty slot of size "n_tokens" in the cache
  1810. // updates the cache head
  1811. // Note: On success, it's important that cache.head points
  1812. // to the first cell of the slot.
  1813. static bool llama_kv_cache_find_slot(
  1814. struct llama_kv_cache & cache,
  1815. const struct llama_batch & batch) {
  1816. const uint32_t n_ctx = cache.size;
  1817. const uint32_t n_tokens = batch.n_tokens;
  1818. if (n_tokens > n_ctx) {
  1819. LLAMA_LOG_ERROR("%s: n_tokens=%d > n_ctx=%d\n", __func__, n_tokens, n_ctx);
  1820. return false;
  1821. }
  1822. uint32_t n_tested = 0;
  1823. while (true) {
  1824. if (cache.head + n_tokens > n_ctx) {
  1825. n_tested += n_ctx - cache.head;
  1826. cache.head = 0;
  1827. continue;
  1828. }
  1829. bool found = true;
  1830. for (uint32_t i = 0; i < n_tokens; i++) {
  1831. if (cache.cells[cache.head + i].pos >= 0) {
  1832. found = false;
  1833. cache.head += i + 1;
  1834. n_tested += i + 1;
  1835. break;
  1836. }
  1837. }
  1838. if (found) {
  1839. break;
  1840. }
  1841. if (n_tested >= n_ctx) {
  1842. //LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens);
  1843. return false;
  1844. }
  1845. }
  1846. for (uint32_t i = 0; i < n_tokens; i++) {
  1847. cache.cells[cache.head + i].pos = batch.pos[i];
  1848. for (int32_t j = 0; j < batch.n_seq_id[i]; j++) {
  1849. cache.cells[cache.head + i].seq_id.insert(batch.seq_id[i][j]);
  1850. }
  1851. }
  1852. cache.used += n_tokens;
  1853. return true;
  1854. }
  1855. // find how many cells are currently in use
  1856. static int32_t llama_kv_cache_cell_max(const struct llama_kv_cache & cache) {
  1857. for (uint32_t i = cache.size - 1; i > 0; --i) {
  1858. if (cache.cells[i].pos >= 0 && !cache.cells[i].is_empty()) {
  1859. return i + 1;
  1860. }
  1861. }
  1862. return 0;
  1863. }
  1864. static void llama_kv_cache_clear(struct llama_kv_cache & cache) {
  1865. for (int32_t i = 0; i < (int32_t) cache.size; ++i) {
  1866. cache.cells[i].pos = -1;
  1867. cache.cells[i].seq_id.clear();
  1868. }
  1869. cache.head = 0;
  1870. cache.used = 0;
  1871. }
  1872. static void llama_kv_cache_seq_rm(
  1873. struct llama_kv_cache & cache,
  1874. llama_seq_id seq_id,
  1875. llama_pos p0,
  1876. llama_pos p1) {
  1877. uint32_t new_head = cache.size;
  1878. if (p0 < 0) p0 = 0;
  1879. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1880. for (uint32_t i = 0; i < cache.size; ++i) {
  1881. if (cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1882. if (seq_id < 0) {
  1883. cache.cells[i].seq_id.clear();
  1884. } else if (cache.cells[i].has_seq_id(seq_id)) {
  1885. cache.cells[i].seq_id.erase(seq_id);
  1886. } else {
  1887. continue;
  1888. }
  1889. if (cache.cells[i].is_empty()) {
  1890. // keep count of the number of used cells
  1891. if (cache.cells[i].pos >= 0) cache.used--;
  1892. cache.cells[i].pos = -1;
  1893. if (new_head == cache.size) new_head = i;
  1894. }
  1895. }
  1896. }
  1897. // If we freed up a slot, set head to it so searching can start there.
  1898. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  1899. }
  1900. static void llama_kv_cache_seq_cp(
  1901. struct llama_kv_cache & cache,
  1902. llama_seq_id seq_id_src,
  1903. llama_seq_id seq_id_dst,
  1904. llama_pos p0,
  1905. llama_pos p1) {
  1906. if (p0 < 0) p0 = 0;
  1907. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1908. cache.head = 0;
  1909. for (uint32_t i = 0; i < cache.size; ++i) {
  1910. if (cache.cells[i].has_seq_id(seq_id_src) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1911. cache.cells[i].seq_id.insert(seq_id_dst);
  1912. }
  1913. }
  1914. }
  1915. static void llama_kv_cache_seq_keep(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  1916. uint32_t new_head = cache.size;
  1917. for (uint32_t i = 0; i < cache.size; ++i) {
  1918. if (!cache.cells[i].has_seq_id(seq_id)) {
  1919. if (cache.cells[i].pos >= 0) cache.used--;
  1920. cache.cells[i].pos = -1;
  1921. cache.cells[i].seq_id.clear();
  1922. if (new_head == cache.size) new_head = i;
  1923. } else {
  1924. cache.cells[i].seq_id.clear();
  1925. cache.cells[i].seq_id.insert(seq_id);
  1926. }
  1927. }
  1928. // If we freed up a slot, set head to it so searching can start there.
  1929. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  1930. }
  1931. static void llama_kv_cache_seq_add(
  1932. struct llama_kv_cache & cache,
  1933. llama_seq_id seq_id,
  1934. llama_pos p0,
  1935. llama_pos p1,
  1936. llama_pos delta) {
  1937. uint32_t new_head = cache.size;
  1938. if (p0 < 0) p0 = 0;
  1939. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1940. for (uint32_t i = 0; i < cache.size; ++i) {
  1941. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1942. cache.has_shift = true;
  1943. cache.cells[i].pos += delta;
  1944. cache.cells[i].delta += delta;
  1945. if (cache.cells[i].pos < 0) {
  1946. if (!cache.cells[i].is_empty()) {
  1947. cache.used--;
  1948. }
  1949. cache.cells[i].pos = -1;
  1950. cache.cells[i].seq_id.clear();
  1951. if (new_head == cache.size) {
  1952. new_head = i;
  1953. }
  1954. }
  1955. }
  1956. }
  1957. // If we freed up a slot, set head to it so searching can start there.
  1958. // Otherwise we just start the next search from the beginning.
  1959. cache.head = new_head != cache.size ? new_head : 0;
  1960. }
  1961. static void llama_kv_cache_seq_div(
  1962. struct llama_kv_cache & cache,
  1963. llama_seq_id seq_id,
  1964. llama_pos p0,
  1965. llama_pos p1,
  1966. int d) {
  1967. if (p0 < 0) p0 = 0;
  1968. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1969. for (uint32_t i = 0; i < cache.size; ++i) {
  1970. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1971. cache.has_shift = true;
  1972. {
  1973. llama_pos p_old = cache.cells[i].pos;
  1974. cache.cells[i].pos /= d;
  1975. cache.cells[i].delta += cache.cells[i].pos - p_old;
  1976. }
  1977. }
  1978. }
  1979. }
  1980. static llama_pos llama_kv_cache_seq_pos_max(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  1981. llama_pos result = 0;
  1982. for (uint32_t i = 0; i < cache.size; ++i) {
  1983. if (cache.cells[i].has_seq_id(seq_id)) {
  1984. result = std::max(result, cache.cells[i].pos);
  1985. }
  1986. }
  1987. return result;
  1988. }
  1989. static void llama_kv_cache_defrag(struct llama_kv_cache & cache) {
  1990. cache.do_defrag = true;
  1991. }
  1992. //
  1993. // model loading and saving
  1994. //
  1995. enum llama_fver {
  1996. GGUF_FILE_VERSION_V1 = 1,
  1997. GGUF_FILE_VERSION_V2 = 2,
  1998. GGUF_FILE_VERSION_V3 = 3,
  1999. };
  2000. static const char * llama_file_version_name(llama_fver version) {
  2001. switch (version) {
  2002. case GGUF_FILE_VERSION_V1: return "GGUF V1 (support until nov 2023)";
  2003. case GGUF_FILE_VERSION_V2: return "GGUF V2";
  2004. case GGUF_FILE_VERSION_V3: return "GGUF V3 (latest)";
  2005. }
  2006. return "unknown";
  2007. }
  2008. static std::string llama_format_tensor_shape(const std::vector<int64_t> & ne) {
  2009. char buf[256];
  2010. snprintf(buf, sizeof(buf), "%5" PRId64, ne.at(0));
  2011. for (size_t i = 1; i < ne.size(); i++) {
  2012. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, ne.at(i));
  2013. }
  2014. return buf;
  2015. }
  2016. static std::string llama_format_tensor_shape(const struct ggml_tensor * t) {
  2017. char buf[256];
  2018. snprintf(buf, sizeof(buf), "%5" PRId64, t->ne[0]);
  2019. for (int i = 1; i < GGML_MAX_DIMS; i++) {
  2020. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, t->ne[i]);
  2021. }
  2022. return buf;
  2023. }
  2024. namespace GGUFMeta {
  2025. template <typename T, gguf_type gt_, T (*gfun)(const gguf_context *, const int)>
  2026. struct GKV_Base_Type {
  2027. static constexpr gguf_type gt = gt_;
  2028. static T getter(const gguf_context * ctx, const int kid) {
  2029. return gfun(ctx, kid);
  2030. }
  2031. };
  2032. template<typename T> struct GKV_Base;
  2033. template<> struct GKV_Base<bool >: GKV_Base_Type<bool, GGUF_TYPE_BOOL, gguf_get_val_bool> {};
  2034. template<> struct GKV_Base<uint8_t >: GKV_Base_Type<uint8_t, GGUF_TYPE_UINT8, gguf_get_val_u8 > {};
  2035. template<> struct GKV_Base<uint16_t >: GKV_Base_Type<uint16_t, GGUF_TYPE_UINT16, gguf_get_val_u16 > {};
  2036. template<> struct GKV_Base<uint32_t >: GKV_Base_Type<uint32_t, GGUF_TYPE_UINT32, gguf_get_val_u32 > {};
  2037. template<> struct GKV_Base<uint64_t >: GKV_Base_Type<uint64_t, GGUF_TYPE_UINT64, gguf_get_val_u64 > {};
  2038. template<> struct GKV_Base<int8_t >: GKV_Base_Type<int8_t, GGUF_TYPE_INT8, gguf_get_val_i8 > {};
  2039. template<> struct GKV_Base<int16_t >: GKV_Base_Type<int16_t, GGUF_TYPE_INT16, gguf_get_val_i16 > {};
  2040. template<> struct GKV_Base<int32_t >: GKV_Base_Type<int32_t, GGUF_TYPE_INT32, gguf_get_val_i32 > {};
  2041. template<> struct GKV_Base<int64_t >: GKV_Base_Type<int64_t, GGUF_TYPE_INT64, gguf_get_val_i64 > {};
  2042. template<> struct GKV_Base<float >: GKV_Base_Type<float, GGUF_TYPE_FLOAT32, gguf_get_val_f32 > {};
  2043. template<> struct GKV_Base<double >: GKV_Base_Type<double, GGUF_TYPE_FLOAT64, gguf_get_val_f64 > {};
  2044. template<> struct GKV_Base<const char *>: GKV_Base_Type<const char *, GGUF_TYPE_STRING, gguf_get_val_str > {};
  2045. template<> struct GKV_Base<std::string> {
  2046. static constexpr gguf_type gt = GGUF_TYPE_STRING;
  2047. static std::string getter(const gguf_context * ctx, const int kid) {
  2048. return gguf_get_val_str(ctx, kid);
  2049. }
  2050. };
  2051. struct ArrayInfo {
  2052. const gguf_type gt;
  2053. const size_t length;
  2054. const void * data;
  2055. };
  2056. template<> struct GKV_Base<ArrayInfo> {
  2057. public:
  2058. static constexpr gguf_type gt = GGUF_TYPE_ARRAY;
  2059. static ArrayInfo getter(const gguf_context *ctx, const int k) {
  2060. return ArrayInfo {
  2061. gguf_get_arr_type(ctx, k),
  2062. size_t(gguf_get_arr_n(ctx, k)),
  2063. gguf_get_arr_data(ctx, k),
  2064. };
  2065. }
  2066. };
  2067. template<typename T>
  2068. class GKV : public GKV_Base<T> {
  2069. GKV() = delete;
  2070. public:
  2071. static T get_kv(const gguf_context * ctx, const int k) {
  2072. const enum gguf_type kt = gguf_get_kv_type(ctx, k);
  2073. if (kt != GKV::gt) {
  2074. throw std::runtime_error(format("key %s has wrong type %s but expected type %s",
  2075. gguf_get_key(ctx, k), gguf_type_name(kt), gguf_type_name(GKV::gt)));
  2076. }
  2077. return GKV::getter(ctx, k);
  2078. }
  2079. static const char * override_type_to_str(const llama_model_kv_override_type ty) {
  2080. switch (ty) {
  2081. case LLAMA_KV_OVERRIDE_TYPE_BOOL: return "bool";
  2082. case LLAMA_KV_OVERRIDE_TYPE_INT: return "int";
  2083. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: return "float";
  2084. }
  2085. return "unknown";
  2086. }
  2087. static bool validate_override(const llama_model_kv_override_type expected_type, const struct llama_model_kv_override * ovrd) {
  2088. if (!ovrd) { return false; }
  2089. if (ovrd->tag == expected_type) {
  2090. LLAMA_LOG_INFO("%s: Using metadata override (%5s) '%s' = ",
  2091. __func__, override_type_to_str(ovrd->tag), ovrd->key);
  2092. switch (ovrd->tag) {
  2093. case LLAMA_KV_OVERRIDE_TYPE_BOOL: {
  2094. LLAMA_LOG_INFO("%s\n", ovrd->bool_value ? "true" : "false");
  2095. } break;
  2096. case LLAMA_KV_OVERRIDE_TYPE_INT: {
  2097. LLAMA_LOG_INFO("%" PRId64 "\n", ovrd->int_value);
  2098. } break;
  2099. case LLAMA_KV_OVERRIDE_TYPE_FLOAT: {
  2100. LLAMA_LOG_INFO("%.6f\n", ovrd->float_value);
  2101. } break;
  2102. default:
  2103. // Shouldn't be possible to end up here, but just in case...
  2104. throw std::runtime_error(
  2105. format("Unsupported attempt to override %s type for metadata key %s\n",
  2106. override_type_to_str(ovrd->tag), ovrd->key));
  2107. }
  2108. return true;
  2109. }
  2110. LLAMA_LOG_WARN("%s: Warning: Bad metadata override type for key '%s', expected %s but got %s\n",
  2111. __func__, ovrd->key, override_type_to_str(expected_type), override_type_to_str(ovrd->tag));
  2112. return false;
  2113. }
  2114. template<typename OT>
  2115. static typename std::enable_if<std::is_same<OT, bool>::value, bool>::type
  2116. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  2117. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_BOOL, ovrd)) {
  2118. target = ovrd->bool_value;
  2119. return true;
  2120. }
  2121. return false;
  2122. }
  2123. template<typename OT>
  2124. static typename std::enable_if<!std::is_same<OT, bool>::value && std::is_integral<OT>::value, bool>::type
  2125. try_override(OT & target, const struct llama_model_kv_override * ovrd) {
  2126. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_INT, ovrd)) {
  2127. target = ovrd->int_value;
  2128. return true;
  2129. }
  2130. return false;
  2131. }
  2132. template<typename OT>
  2133. static typename std::enable_if<std::is_floating_point<OT>::value, bool>::type
  2134. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  2135. if (validate_override(LLAMA_KV_OVERRIDE_TYPE_FLOAT, ovrd)) {
  2136. target = ovrd->float_value;
  2137. return true;
  2138. }
  2139. return false;
  2140. }
  2141. template<typename OT>
  2142. static typename std::enable_if<std::is_same<OT, std::string>::value, bool>::type
  2143. try_override(T & target, const struct llama_model_kv_override * ovrd) {
  2144. (void)target;
  2145. (void)ovrd;
  2146. if (!ovrd) { return false; }
  2147. // Currently, we should never end up here so it would be a bug if we do.
  2148. throw std::runtime_error(format("Unsupported attempt to override string type for metadata key %s\n",
  2149. ovrd ? ovrd->key : "NULL"));
  2150. }
  2151. static bool set(const gguf_context * ctx, const int k, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  2152. if (try_override<T>(target, ovrd)) {
  2153. return true;
  2154. }
  2155. if (k < 0) { return false; }
  2156. target = get_kv(ctx, k);
  2157. return true;
  2158. }
  2159. static bool set(const gguf_context * ctx, const char * key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  2160. return set(ctx, gguf_find_key(ctx, key), target, ovrd);
  2161. }
  2162. static bool set(const gguf_context * ctx, const std::string & key, T & target, const struct llama_model_kv_override * ovrd = nullptr) {
  2163. return set(ctx, key.c_str(), target, ovrd);
  2164. }
  2165. };
  2166. }
  2167. struct llama_model_loader {
  2168. int n_kv = 0;
  2169. int n_tensors = 0;
  2170. int n_created = 0;
  2171. int64_t n_elements = 0;
  2172. size_t n_bytes = 0;
  2173. bool use_mmap = false;
  2174. llama_file file;
  2175. llama_ftype ftype;
  2176. llama_fver fver;
  2177. std::unique_ptr<llama_mmap> mapping;
  2178. std::unordered_map<std::string, struct llama_model_kv_override> kv_overrides;
  2179. struct gguf_context * ctx_gguf = NULL;
  2180. struct ggml_context * ctx_meta = NULL;
  2181. std::string arch_name;
  2182. LLM_KV llm_kv = LLM_KV(LLM_ARCH_UNKNOWN);
  2183. llama_model_loader(const std::string & fname, bool use_mmap, const struct llama_model_kv_override * param_overrides_p) : file(fname.c_str(), "rb") {
  2184. int trace = 0;
  2185. if (getenv("LLAMA_TRACE")) {
  2186. trace = atoi(getenv("LLAMA_TRACE"));
  2187. }
  2188. struct gguf_init_params params = {
  2189. /*.no_alloc = */ true,
  2190. /*.ctx = */ &ctx_meta,
  2191. };
  2192. if (param_overrides_p != nullptr) {
  2193. for (const struct llama_model_kv_override *p = param_overrides_p; p->key[0] != 0; p++) {
  2194. kv_overrides.insert({std::string(p->key), *p});
  2195. }
  2196. }
  2197. ctx_gguf = gguf_init_from_file(fname.c_str(), params);
  2198. if (!ctx_gguf) {
  2199. throw std::runtime_error(format("%s: failed to load model from %s\n", __func__, fname.c_str()));
  2200. }
  2201. get_key(llm_kv(LLM_KV_GENERAL_ARCHITECTURE), arch_name, false);
  2202. llm_kv = LLM_KV(llm_arch_from_string(arch_name));
  2203. n_kv = gguf_get_n_kv(ctx_gguf);
  2204. n_tensors = gguf_get_n_tensors(ctx_gguf);
  2205. fver = (enum llama_fver ) gguf_get_version(ctx_gguf);
  2206. for (int i = 0; i < n_tensors; i++) {
  2207. const char * name = gguf_get_tensor_name(ctx_gguf, i);
  2208. struct ggml_tensor * t = ggml_get_tensor(ctx_meta, name);
  2209. n_elements += ggml_nelements(t);
  2210. n_bytes += ggml_nbytes(t);
  2211. }
  2212. LLAMA_LOG_INFO("%s: loaded meta data with %d key-value pairs and %d tensors from %s (version %s)\n",
  2213. __func__, n_kv, n_tensors, fname.c_str(), llama_file_version_name(fver));
  2214. // determine file type based on the number of tensors for each quantization and print meta data
  2215. // TODO: make optional
  2216. {
  2217. std::map<enum ggml_type, uint32_t> n_type;
  2218. uint32_t n_type_max = 0;
  2219. enum ggml_type type_max = GGML_TYPE_F32;
  2220. for (int i = 0; i < n_tensors; i++) {
  2221. enum ggml_type type = gguf_get_tensor_type(ctx_gguf, i);
  2222. n_type[type]++;
  2223. if (n_type_max < n_type[type]) {
  2224. n_type_max = n_type[type];
  2225. type_max = type;
  2226. }
  2227. if (trace > 0) {
  2228. struct ggml_tensor * meta = ggml_get_tensor(ctx_meta, gguf_get_tensor_name(ctx_gguf, i));
  2229. 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());
  2230. }
  2231. }
  2232. switch (type_max) {
  2233. case GGML_TYPE_F32: ftype = LLAMA_FTYPE_ALL_F32; break;
  2234. case GGML_TYPE_F16: ftype = LLAMA_FTYPE_MOSTLY_F16; break;
  2235. case GGML_TYPE_Q4_0: ftype = LLAMA_FTYPE_MOSTLY_Q4_0; break;
  2236. case GGML_TYPE_Q4_1: ftype = LLAMA_FTYPE_MOSTLY_Q4_1; break;
  2237. case GGML_TYPE_Q5_0: ftype = LLAMA_FTYPE_MOSTLY_Q5_0; break;
  2238. case GGML_TYPE_Q5_1: ftype = LLAMA_FTYPE_MOSTLY_Q5_1; break;
  2239. case GGML_TYPE_Q8_0: ftype = LLAMA_FTYPE_MOSTLY_Q8_0; break;
  2240. case GGML_TYPE_Q2_K: ftype = LLAMA_FTYPE_MOSTLY_Q2_K; break;
  2241. case GGML_TYPE_Q3_K: ftype = LLAMA_FTYPE_MOSTLY_Q3_K_M; break;
  2242. case GGML_TYPE_Q4_K: ftype = LLAMA_FTYPE_MOSTLY_Q4_K_M; break;
  2243. case GGML_TYPE_Q5_K: ftype = LLAMA_FTYPE_MOSTLY_Q5_K_M; break;
  2244. case GGML_TYPE_Q6_K: ftype = LLAMA_FTYPE_MOSTLY_Q6_K; break;
  2245. case GGML_TYPE_IQ2_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XXS; break;
  2246. case GGML_TYPE_IQ2_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XS; break;
  2247. case GGML_TYPE_IQ2_S: ftype = LLAMA_FTYPE_MOSTLY_IQ2_S; break;
  2248. case GGML_TYPE_IQ3_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ3_XXS; break;
  2249. case GGML_TYPE_IQ1_S: ftype = LLAMA_FTYPE_MOSTLY_IQ1_S; break;
  2250. case GGML_TYPE_IQ4_NL: ftype = LLAMA_FTYPE_MOSTLY_IQ4_NL; break;
  2251. case GGML_TYPE_IQ4_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ4_XS; break;
  2252. case GGML_TYPE_IQ3_S: ftype = LLAMA_FTYPE_MOSTLY_IQ3_S; break;
  2253. default:
  2254. {
  2255. LLAMA_LOG_WARN("%s: unknown type %s\n", __func__, ggml_type_name(type_max));
  2256. ftype = LLAMA_FTYPE_ALL_F32;
  2257. } break;
  2258. }
  2259. // this is a way to mark that we have "guessed" the file type
  2260. ftype = (llama_ftype) (ftype | LLAMA_FTYPE_GUESSED);
  2261. {
  2262. const int kid = gguf_find_key(ctx_gguf, "general.file_type");
  2263. if (kid >= 0) {
  2264. ftype = (llama_ftype) gguf_get_val_u32(ctx_gguf, kid);
  2265. }
  2266. }
  2267. LLAMA_LOG_INFO("%s: Dumping metadata keys/values. Note: KV overrides do not apply in this output.\n", __func__);
  2268. for (int i = 0; i < n_kv; i++) {
  2269. const char * name = gguf_get_key(ctx_gguf, i);
  2270. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  2271. const std::string type_name =
  2272. type == GGUF_TYPE_ARRAY
  2273. ? 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))
  2274. : gguf_type_name(type);
  2275. std::string value = gguf_kv_to_str(ctx_gguf, i);
  2276. const size_t MAX_VALUE_LEN = 40;
  2277. if (value.size() > MAX_VALUE_LEN) {
  2278. value = format("%s...", value.substr(0, MAX_VALUE_LEN - 3).c_str());
  2279. }
  2280. replace_all(value, "\n", "\\n");
  2281. LLAMA_LOG_INFO("%s: - kv %3d: %42s %-16s = %s\n", __func__, i, name, type_name.c_str(), value.c_str());
  2282. }
  2283. // print type counts
  2284. for (auto & kv : n_type) {
  2285. if (kv.second == 0) {
  2286. continue;
  2287. }
  2288. LLAMA_LOG_INFO("%s: - type %4s: %4d tensors\n", __func__, ggml_type_name(kv.first), kv.second);
  2289. }
  2290. }
  2291. if (!llama_mmap::SUPPORTED) {
  2292. LLAMA_LOG_WARN("%s: mmap is not supported on this platform\n", __func__);
  2293. use_mmap = false;
  2294. }
  2295. this->use_mmap = use_mmap;
  2296. }
  2297. ~llama_model_loader() {
  2298. if (ctx_gguf) {
  2299. gguf_free(ctx_gguf);
  2300. }
  2301. if (ctx_meta) {
  2302. ggml_free(ctx_meta);
  2303. }
  2304. }
  2305. template<typename T>
  2306. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2307. get_arr_n(const std::string & key, T & result, const bool required = true) {
  2308. const int kid = gguf_find_key(ctx_gguf, key.c_str());
  2309. if (kid < 0) {
  2310. if (required) {
  2311. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2312. }
  2313. return false;
  2314. }
  2315. struct GGUFMeta::ArrayInfo arr_info =
  2316. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(ctx_gguf, kid);
  2317. result = arr_info.length;
  2318. return true;
  2319. }
  2320. template<typename T>
  2321. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2322. get_arr_n(const enum llm_kv kid, T & result, const bool required = true) {
  2323. return get_arr_n(llm_kv(kid), result, required);
  2324. }
  2325. template<typename T>
  2326. bool get_key(const std::string & key, T & result, const bool required = true) {
  2327. auto it = kv_overrides.find(key);
  2328. const struct llama_model_kv_override * override =
  2329. it != kv_overrides.end() ? &it->second : nullptr;
  2330. const bool found = GGUFMeta::GKV<T>::set(ctx_gguf, key, result, override);
  2331. if (required && !found) {
  2332. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2333. }
  2334. return found;
  2335. }
  2336. template<typename T>
  2337. bool get_key(const enum llm_kv kid, T & result, const bool required = true) {
  2338. return get_key(llm_kv(kid), result, required);
  2339. }
  2340. std::string get_arch_name() const {
  2341. return arch_name;
  2342. }
  2343. enum llm_arch get_arch() const {
  2344. return llm_kv.arch;
  2345. }
  2346. const char * get_tensor_name(int i) const {
  2347. return gguf_get_tensor_name(ctx_gguf, i);
  2348. }
  2349. struct ggml_tensor * get_tensor_meta(const char * name) const {
  2350. return ggml_get_tensor(ctx_meta, name);
  2351. }
  2352. struct ggml_tensor * get_tensor_meta(int i) const {
  2353. return get_tensor_meta(get_tensor_name(i));
  2354. }
  2355. struct ggml_tensor * create_tensor_for(struct ggml_context * ctx, struct ggml_tensor * meta) {
  2356. struct ggml_tensor * tensor = ggml_dup_tensor(ctx, meta);
  2357. ggml_set_name(tensor, ggml_get_name(meta));
  2358. n_created++;
  2359. return tensor;
  2360. }
  2361. struct ggml_tensor * create_tensor(struct ggml_context * ctx, const std::string & name, const std::vector<int64_t> & ne, bool required = true) {
  2362. struct ggml_tensor * cur = ggml_get_tensor(ctx_meta, name.c_str());
  2363. if (cur == NULL) {
  2364. if (!required) {
  2365. return NULL;
  2366. }
  2367. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
  2368. }
  2369. {
  2370. bool is_ok = true;
  2371. for (size_t i = 0; i < ne.size(); ++i) {
  2372. if (ne[i] != cur->ne[i]) {
  2373. is_ok = false;
  2374. break;
  2375. }
  2376. }
  2377. if (!is_ok) {
  2378. throw std::runtime_error(
  2379. format("%s: tensor '%s' has wrong shape; expected %s, got %s",
  2380. __func__, name.c_str(),
  2381. llama_format_tensor_shape(ne).c_str(),
  2382. llama_format_tensor_shape(cur).c_str()));
  2383. }
  2384. }
  2385. return create_tensor_for(ctx, cur);
  2386. }
  2387. void done_getting_tensors() const {
  2388. if (n_created != n_tensors) {
  2389. throw std::runtime_error(format("%s: wrong number of tensors; expected %d, got %d", __func__, n_tensors, n_created));
  2390. }
  2391. }
  2392. size_t file_offset(const char * name) const {
  2393. const int idx = gguf_find_tensor(ctx_gguf, name);
  2394. if (idx < 0) {
  2395. throw std::runtime_error(format("%s: tensor '%s' not found in the file", __func__, name));
  2396. }
  2397. return gguf_get_data_offset(ctx_gguf) + gguf_get_tensor_offset(ctx_gguf, idx);
  2398. }
  2399. void init_mapping(bool prefetch = true, llama_mlock * lmlock = nullptr) {
  2400. // prefetch the whole file - all the data is needed anyway
  2401. if (use_mmap) {
  2402. mapping.reset(new llama_mmap(&file, prefetch ? -1 : 0, ggml_is_numa()));
  2403. }
  2404. // compute the total size of all tensors for progress reporting
  2405. for (int i = 0; i < gguf_get_n_tensors(ctx_gguf); i++) {
  2406. struct ggml_tensor * cur = ggml_get_tensor(ctx_meta, gguf_get_tensor_name(ctx_gguf, i));
  2407. size_data += ggml_nbytes(cur);
  2408. }
  2409. if (use_mmap && mapping) {
  2410. if (lmlock) {
  2411. lmlock->init(mapping->addr);
  2412. }
  2413. mmap_used_first = mapping->size;
  2414. }
  2415. }
  2416. void get_mapping_range(size_t * first, size_t * last, ggml_context * ctx) const {
  2417. GGML_ASSERT(mapping);
  2418. *first = mapping->size;
  2419. *last = 0;
  2420. for (ggml_tensor * tensor = ggml_get_first_tensor(ctx); tensor; tensor = ggml_get_next_tensor(ctx, tensor)) {
  2421. const size_t offs = file_offset(ggml_get_name(tensor));
  2422. *first = std::min(*first, offs);
  2423. *last = std::max(*last, offs + ggml_nbytes(tensor));
  2424. }
  2425. }
  2426. // for backwards compatibility, does not support ggml-backend
  2427. void load_data_for(struct ggml_tensor * cur) const {
  2428. const size_t offs = file_offset(ggml_get_name(cur));
  2429. if (use_mmap && mapping) {
  2430. if (cur->data == nullptr) {
  2431. cur->data = (uint8_t *)mapping->addr + offs;
  2432. } else {
  2433. memcpy(cur->data, (uint8_t *)mapping->addr + offs, ggml_nbytes(cur));
  2434. }
  2435. } else {
  2436. GGML_ASSERT(cur->data != nullptr);
  2437. file.seek(offs, SEEK_SET);
  2438. file.read_raw(cur->data, ggml_nbytes(cur));
  2439. }
  2440. }
  2441. size_t size_done = 0;
  2442. size_t size_data = 0;
  2443. size_t mmap_used_first = -1;
  2444. size_t mmap_used_last = 0;
  2445. // Returns false if cancelled by progress_callback
  2446. 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) {
  2447. GGML_ASSERT(size_data != 0 && "call init_mapping() first");
  2448. std::vector<no_init<uint8_t>> read_buf;
  2449. for (struct ggml_tensor * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  2450. if (progress_callback) {
  2451. if (!progress_callback((float) size_done / size_data, progress_callback_user_data)) {
  2452. return false;
  2453. }
  2454. }
  2455. const size_t offs = file_offset(ggml_get_name(cur));
  2456. if (use_mmap && mapping) {
  2457. if (buf_mmap && cur->data == nullptr) {
  2458. ggml_backend_tensor_alloc(buf_mmap, cur, (uint8_t *) mapping->addr + offs);
  2459. if (lmlock) {
  2460. lmlock->grow_to(offs + ggml_nbytes(cur));
  2461. }
  2462. mmap_used_first = std::min(mmap_used_first, offs);
  2463. mmap_used_last = std::max(mmap_used_last, offs + ggml_nbytes(cur));
  2464. } else {
  2465. ggml_backend_tensor_set(cur, (uint8_t *) mapping->addr + offs, 0, ggml_nbytes(cur));
  2466. }
  2467. } else {
  2468. if (ggml_backend_buffer_is_host(cur->buffer)) {
  2469. file.seek(offs, SEEK_SET);
  2470. file.read_raw(cur->data, ggml_nbytes(cur));
  2471. } else {
  2472. read_buf.resize(ggml_nbytes(cur));
  2473. file.seek(offs, SEEK_SET);
  2474. file.read_raw(read_buf.data(), ggml_nbytes(cur));
  2475. ggml_backend_tensor_set(cur, read_buf.data(), 0, ggml_nbytes(cur));
  2476. }
  2477. }
  2478. size_done += ggml_nbytes(cur);
  2479. }
  2480. // check if this is the last call and do final cleanup
  2481. if (size_done >= size_data) {
  2482. // unmap offloaded tensors and metadata
  2483. if (use_mmap && mapping) {
  2484. mapping->unmap_fragment(0, mmap_used_first);
  2485. if (mmap_used_last != 0) {
  2486. mapping->unmap_fragment(mmap_used_last, mapping->size);
  2487. }
  2488. }
  2489. if (progress_callback) {
  2490. // Even though the model is done loading, we still honor
  2491. // cancellation since we need to free allocations.
  2492. return progress_callback(1.0f, progress_callback_user_data);
  2493. }
  2494. }
  2495. return true;
  2496. }
  2497. };
  2498. template<>
  2499. bool llama_model_loader::get_key(const enum llm_kv kid, enum llama_pooling_type & result, const bool required) {
  2500. uint32_t tmp;
  2501. const bool found = get_key(kid, tmp, required);
  2502. result = (enum llama_pooling_type) tmp;
  2503. return found;
  2504. }
  2505. //
  2506. // load LLaMA models
  2507. //
  2508. static const char * llama_model_arch_name(llm_arch arch) {
  2509. auto it = LLM_ARCH_NAMES.find(arch);
  2510. if (it == LLM_ARCH_NAMES.end()) {
  2511. return "unknown";
  2512. }
  2513. return it->second;
  2514. }
  2515. static std::string llama_model_ftype_name(llama_ftype ftype) {
  2516. if (ftype & LLAMA_FTYPE_GUESSED) {
  2517. return llama_model_ftype_name((enum llama_ftype) (ftype & ~LLAMA_FTYPE_GUESSED)) + " (guessed)";
  2518. }
  2519. switch (ftype) {
  2520. case LLAMA_FTYPE_ALL_F32: return "all F32";
  2521. case LLAMA_FTYPE_MOSTLY_F16: return "F16";
  2522. case LLAMA_FTYPE_MOSTLY_Q4_0: return "Q4_0";
  2523. case LLAMA_FTYPE_MOSTLY_Q4_1: return "Q4_1";
  2524. case LLAMA_FTYPE_MOSTLY_Q4_1_SOME_F16:
  2525. return "Q4_1, some F16";
  2526. case LLAMA_FTYPE_MOSTLY_Q5_0: return "Q5_0";
  2527. case LLAMA_FTYPE_MOSTLY_Q5_1: return "Q5_1";
  2528. case LLAMA_FTYPE_MOSTLY_Q8_0: return "Q8_0";
  2529. // K-quants
  2530. case LLAMA_FTYPE_MOSTLY_Q2_K: return "Q2_K - Medium";
  2531. case LLAMA_FTYPE_MOSTLY_Q2_K_S: return "Q2_K - Small";
  2532. case LLAMA_FTYPE_MOSTLY_Q3_K_S: return "Q3_K - Small";
  2533. case LLAMA_FTYPE_MOSTLY_Q3_K_M: return "Q3_K - Medium";
  2534. case LLAMA_FTYPE_MOSTLY_Q3_K_L: return "Q3_K - Large";
  2535. case LLAMA_FTYPE_MOSTLY_Q4_K_S: return "Q4_K - Small";
  2536. case LLAMA_FTYPE_MOSTLY_Q4_K_M: return "Q4_K - Medium";
  2537. case LLAMA_FTYPE_MOSTLY_Q5_K_S: return "Q5_K - Small";
  2538. case LLAMA_FTYPE_MOSTLY_Q5_K_M: return "Q5_K - Medium";
  2539. case LLAMA_FTYPE_MOSTLY_Q6_K: return "Q6_K";
  2540. case LLAMA_FTYPE_MOSTLY_IQ2_XXS:return "IQ2_XXS - 2.0625 bpw";
  2541. case LLAMA_FTYPE_MOSTLY_IQ2_XS: return "IQ2_XS - 2.3125 bpw";
  2542. case LLAMA_FTYPE_MOSTLY_IQ2_S: return "IQ2_S - 2.5 bpw";
  2543. case LLAMA_FTYPE_MOSTLY_IQ2_M: return "IQ2_M - 2.7 bpw";
  2544. case LLAMA_FTYPE_MOSTLY_IQ3_XS: return "IQ3_XS - 3.3 bpw";
  2545. case LLAMA_FTYPE_MOSTLY_IQ3_XXS:return "IQ3_XXS - 3.0625 bpw";
  2546. case LLAMA_FTYPE_MOSTLY_IQ1_S :return "IQ1_S - 1.5625 bpw";
  2547. case LLAMA_FTYPE_MOSTLY_IQ4_NL: return "IQ4_NL - 4.5 bpw";
  2548. case LLAMA_FTYPE_MOSTLY_IQ4_XS: return "IQ4_XS - 4.25 bpw";
  2549. case LLAMA_FTYPE_MOSTLY_IQ3_S: return "IQ3_S - 3.4375 bpw";
  2550. case LLAMA_FTYPE_MOSTLY_IQ3_M: return "IQ3_S mix - 3.66 bpw";
  2551. default: return "unknown, may not work";
  2552. }
  2553. }
  2554. static const char * llama_model_type_name(e_model type) {
  2555. switch (type) {
  2556. case MODEL_22M: return "22M";
  2557. case MODEL_33M: return "33M";
  2558. case MODEL_109M: return "109M";
  2559. case MODEL_137M: return "137M";
  2560. case MODEL_0_5B: return "0.5B";
  2561. case MODEL_1B: return "1B";
  2562. case MODEL_2B: return "2B";
  2563. case MODEL_3B: return "3B";
  2564. case MODEL_7B: return "7B";
  2565. case MODEL_8B: return "8B";
  2566. case MODEL_13B: return "13B";
  2567. case MODEL_14B: return "14B";
  2568. case MODEL_15B: return "15B";
  2569. case MODEL_20B: return "20B";
  2570. case MODEL_30B: return "30B";
  2571. case MODEL_34B: return "34B";
  2572. case MODEL_40B: return "40B";
  2573. case MODEL_65B: return "65B";
  2574. case MODEL_70B: return "70B";
  2575. case MODEL_SMALL: return "0.1B";
  2576. case MODEL_MEDIUM: return "0.4B";
  2577. case MODEL_LARGE: return "0.8B";
  2578. case MODEL_XL: return "1.5B";
  2579. default: return "?B";
  2580. }
  2581. }
  2582. static const char * llama_model_vocab_type_name(enum llama_vocab_type type){
  2583. switch (type) {
  2584. case LLAMA_VOCAB_TYPE_SPM: return "SPM";
  2585. case LLAMA_VOCAB_TYPE_BPE: return "BPE";
  2586. case LLAMA_VOCAB_TYPE_WPM: return "WPM";
  2587. default: return "unknown";
  2588. }
  2589. }
  2590. static void llm_load_arch(llama_model_loader & ml, llama_model & model) {
  2591. model.arch = ml.get_arch();
  2592. if (model.arch == LLM_ARCH_UNKNOWN) {
  2593. throw std::runtime_error("unknown model architecture: '" + ml.get_arch_name() + "'");
  2594. }
  2595. }
  2596. static void llm_load_hparams(
  2597. llama_model_loader & ml,
  2598. llama_model & model) {
  2599. auto & hparams = model.hparams;
  2600. const gguf_context * ctx = ml.ctx_gguf;
  2601. // get metadata as string
  2602. for (int i = 0; i < gguf_get_n_kv(ctx); i++) {
  2603. enum gguf_type type = gguf_get_kv_type(ctx, i);
  2604. if (type == GGUF_TYPE_ARRAY) {
  2605. continue;
  2606. }
  2607. const char * name = gguf_get_key(ctx, i);
  2608. const std::string value = gguf_kv_to_str(ctx, i);
  2609. model.gguf_kv.emplace(name, value);
  2610. }
  2611. // get general kv
  2612. ml.get_key(LLM_KV_GENERAL_NAME, model.name, false);
  2613. // get hparams kv
  2614. ml.get_arr_n(LLM_KV_TOKENIZER_LIST, hparams.n_vocab);
  2615. ml.get_key (LLM_KV_CONTEXT_LENGTH, hparams.n_ctx_train);
  2616. ml.get_key (LLM_KV_EMBEDDING_LENGTH, hparams.n_embd);
  2617. ml.get_key (LLM_KV_FEED_FORWARD_LENGTH, hparams.n_ff);
  2618. ml.get_key (LLM_KV_ATTENTION_HEAD_COUNT, hparams.n_head);
  2619. ml.get_key (LLM_KV_BLOCK_COUNT, hparams.n_layer);
  2620. ml.get_key (LLM_KV_EXPERT_COUNT, hparams.n_expert, false);
  2621. ml.get_key (LLM_KV_EXPERT_USED_COUNT, hparams.n_expert_used, false);
  2622. GGML_ASSERT(hparams.n_expert <= LLAMA_MAX_EXPERTS);
  2623. GGML_ASSERT(hparams.n_expert_used <= hparams.n_expert);
  2624. if (hparams.n_expert > 0) {
  2625. GGML_ASSERT(hparams.n_expert_used > 0);
  2626. } else {
  2627. GGML_ASSERT(hparams.n_expert_used == 0);
  2628. }
  2629. // n_head_kv is optional, default to n_head
  2630. hparams.n_head_kv = hparams.n_head;
  2631. ml.get_key(LLM_KV_ATTENTION_HEAD_COUNT_KV, hparams.n_head_kv, false);
  2632. bool rope_finetuned = false;
  2633. ml.get_key(LLM_KV_ROPE_SCALING_FINETUNED, rope_finetuned, false);
  2634. hparams.rope_finetuned = rope_finetuned;
  2635. hparams.n_yarn_orig_ctx = hparams.n_ctx_train;
  2636. ml.get_key(LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, hparams.n_yarn_orig_ctx, false);
  2637. // rope_freq_base (optional)
  2638. hparams.rope_freq_base_train = 10000.0f;
  2639. ml.get_key(LLM_KV_ROPE_FREQ_BASE, hparams.rope_freq_base_train, false);
  2640. std::string rope_scaling("linear");
  2641. ml.get_key(LLM_KV_ROPE_SCALING_TYPE, rope_scaling, false);
  2642. hparams.rope_scaling_type_train = llama_rope_scaling_type_from_string(rope_scaling);
  2643. GGML_ASSERT(hparams.rope_scaling_type_train != LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED);
  2644. // rope_freq_scale (inverse of the kv) is optional
  2645. float ropescale = 0.0f;
  2646. if (!ml.get_key(LLM_KV_ROPE_SCALING_FACTOR, ropescale, false)) {
  2647. // try the old key name
  2648. ml.get_key(LLM_KV_ROPE_SCALE_LINEAR, ropescale, false);
  2649. }
  2650. hparams.rope_freq_scale_train = ropescale == 0.0f ? 1.0f : 1.0f/ropescale;
  2651. // sanity check for n_rot (optional)
  2652. {
  2653. hparams.n_rot = hparams.n_embd / hparams.n_head;
  2654. ml.get_key(LLM_KV_ROPE_DIMENSION_COUNT, hparams.n_rot, false);
  2655. if (model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON) {
  2656. if (hparams.n_rot != hparams.n_embd / hparams.n_head) {
  2657. throw std::runtime_error(format("invalid n_rot: %u, expected %u", hparams.n_rot, hparams.n_embd / hparams.n_head));
  2658. }
  2659. }
  2660. // gpt-neox n_rot = rotary_pct * (n_embd / n_head)
  2661. // gpt-j n_rot = rotary_dim
  2662. }
  2663. hparams.n_embd_head_k = hparams.n_embd / hparams.n_head;
  2664. ml.get_key(LLM_KV_ATTENTION_KEY_LENGTH, hparams.n_embd_head_k, false);
  2665. hparams.n_embd_head_v = hparams.n_embd / hparams.n_head;
  2666. ml.get_key(LLM_KV_ATTENTION_VALUE_LENGTH, hparams.n_embd_head_v, false);
  2667. // arch-specific KVs
  2668. switch (model.arch) {
  2669. case LLM_ARCH_LLAMA:
  2670. {
  2671. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2672. switch (hparams.n_layer) {
  2673. case 22: model.type = e_model::MODEL_1B; break;
  2674. case 26: model.type = e_model::MODEL_3B; break;
  2675. case 32: model.type = e_model::MODEL_7B; break;
  2676. case 40: model.type = e_model::MODEL_13B; break;
  2677. case 48: model.type = e_model::MODEL_34B; break;
  2678. case 60: model.type = e_model::MODEL_30B; break;
  2679. case 80: model.type = hparams.n_head == hparams.n_head_kv ? e_model::MODEL_65B : e_model::MODEL_70B; break;
  2680. default: model.type = e_model::MODEL_UNKNOWN;
  2681. }
  2682. } break;
  2683. case LLM_ARCH_MINICPM:
  2684. {
  2685. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2686. switch (hparams.n_layer) {
  2687. case 40: model.type = e_model::MODEL_2B; break;
  2688. default: model.type = e_model::MODEL_UNKNOWN;
  2689. }
  2690. } break;
  2691. case LLM_ARCH_FALCON:
  2692. {
  2693. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2694. switch (hparams.n_layer) {
  2695. case 32: model.type = e_model::MODEL_7B; break;
  2696. case 60: model.type = e_model::MODEL_40B; break;
  2697. default: model.type = e_model::MODEL_UNKNOWN;
  2698. }
  2699. } break;
  2700. case LLM_ARCH_BAICHUAN:
  2701. {
  2702. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2703. switch (hparams.n_layer) {
  2704. case 32: model.type = e_model::MODEL_7B; break;
  2705. case 40: model.type = e_model::MODEL_13B; break;
  2706. default: model.type = e_model::MODEL_UNKNOWN;
  2707. }
  2708. if (model.type == e_model::MODEL_13B) {
  2709. // TODO: become GGUF KV parameter
  2710. hparams.f_max_alibi_bias = 8.0f;
  2711. }
  2712. } break;
  2713. case LLM_ARCH_STARCODER:
  2714. {
  2715. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2716. switch (hparams.n_layer) {
  2717. case 24: model.type = e_model::MODEL_1B; break;
  2718. case 36: model.type = e_model::MODEL_3B; break;
  2719. case 42: model.type = e_model::MODEL_7B; break;
  2720. case 40: model.type = e_model::MODEL_15B; break;
  2721. default: model.type = e_model::MODEL_UNKNOWN;
  2722. }
  2723. } break;
  2724. case LLM_ARCH_PERSIMMON:
  2725. {
  2726. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2727. switch (hparams.n_layer) {
  2728. case 36: model.type = e_model::MODEL_8B; break;
  2729. default: model.type = e_model::MODEL_UNKNOWN;
  2730. }
  2731. } break;
  2732. case LLM_ARCH_REFACT:
  2733. {
  2734. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2735. switch (hparams.n_layer) {
  2736. case 32: model.type = e_model::MODEL_1B; break;
  2737. default: model.type = e_model::MODEL_UNKNOWN;
  2738. }
  2739. // TODO: become GGUF KV parameter
  2740. hparams.f_max_alibi_bias = 8.0f;
  2741. } break;
  2742. case LLM_ARCH_BERT:
  2743. {
  2744. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2745. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  2746. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  2747. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type);
  2748. switch (hparams.n_layer) {
  2749. case 3:
  2750. model.type = e_model::MODEL_17M; break; // bge-micro
  2751. case 6:
  2752. model.type = e_model::MODEL_22M; break; // MiniLM-L6
  2753. case 12:
  2754. switch (hparams.n_embd) {
  2755. case 384: model.type = e_model::MODEL_33M; break; // MiniLM-L12, bge-small
  2756. case 768: model.type = e_model::MODEL_109M; break; // bge-base
  2757. } break;
  2758. case 24:
  2759. model.type = e_model::MODEL_335M; break; // bge-large
  2760. }
  2761. } break;
  2762. case LLM_ARCH_NOMIC_BERT:
  2763. {
  2764. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2765. ml.get_key(LLM_KV_ATTENTION_CAUSAL, hparams.causal_attn);
  2766. ml.get_key(LLM_KV_TOKENIZER_TOKEN_TYPE_COUNT, hparams.n_vocab_type);
  2767. ml.get_key(LLM_KV_POOLING_TYPE, hparams.pooling_type);
  2768. if (hparams.n_layer == 12 && hparams.n_embd == 768) {
  2769. model.type = e_model::MODEL_137M;
  2770. }
  2771. } break;
  2772. case LLM_ARCH_BLOOM:
  2773. {
  2774. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2775. switch (hparams.n_layer) {
  2776. case 24: model.type = e_model::MODEL_1B; break;
  2777. case 30:
  2778. switch (hparams.n_embd) {
  2779. case 2560: model.type = e_model::MODEL_3B; break;
  2780. case 4096: model.type = e_model::MODEL_7B; break;
  2781. } break;
  2782. }
  2783. // TODO: become GGUF KV parameter
  2784. hparams.f_max_alibi_bias = 8.0f;
  2785. } break;
  2786. case LLM_ARCH_MPT:
  2787. {
  2788. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2789. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv, false);
  2790. ml.get_key(LLM_KV_ATTENTION_MAX_ALIBI_BIAS, hparams.f_max_alibi_bias);
  2791. switch (hparams.n_layer) {
  2792. case 32: model.type = e_model::MODEL_7B; break;
  2793. case 48: model.type = e_model::MODEL_30B; break;
  2794. default: model.type = e_model::MODEL_UNKNOWN;
  2795. }
  2796. } break;
  2797. case LLM_ARCH_STABLELM:
  2798. {
  2799. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2800. switch (hparams.n_layer) {
  2801. case 24: model.type = e_model::MODEL_1B; break;
  2802. case 32: model.type = e_model::MODEL_3B; break;
  2803. default: model.type = e_model::MODEL_UNKNOWN;
  2804. }
  2805. } break;
  2806. case LLM_ARCH_QWEN:
  2807. {
  2808. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2809. switch (hparams.n_layer) {
  2810. case 32: model.type = e_model::MODEL_7B; break;
  2811. case 40: model.type = e_model::MODEL_13B; break;
  2812. default: model.type = e_model::MODEL_UNKNOWN;
  2813. }
  2814. } break;
  2815. case LLM_ARCH_QWEN2:
  2816. {
  2817. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2818. switch (hparams.n_layer) {
  2819. case 24: model.type = hparams.n_embd == 1024 ? e_model::MODEL_0_5B : e_model::MODEL_1B; break;
  2820. case 32: model.type = e_model::MODEL_7B; break;
  2821. case 40: model.type = hparams.n_head == 20 ? e_model::MODEL_4B : e_model::MODEL_13B; break;
  2822. case 80: model.type = e_model::MODEL_70B; break;
  2823. default: model.type = e_model::MODEL_UNKNOWN;
  2824. }
  2825. } break;
  2826. case LLM_ARCH_PHI2:
  2827. {
  2828. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2829. switch (hparams.n_layer) {
  2830. case 24: model.type = e_model::MODEL_1B; break;
  2831. case 32: model.type = e_model::MODEL_3B; break;
  2832. default: model.type = e_model::MODEL_UNKNOWN;
  2833. }
  2834. } break;
  2835. case LLM_ARCH_PLAMO:
  2836. {
  2837. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2838. switch (hparams.n_layer) {
  2839. case 40: model.type = e_model::MODEL_13B; break;
  2840. default: model.type = e_model::MODEL_UNKNOWN;
  2841. }
  2842. } break;
  2843. case LLM_ARCH_GPT2:
  2844. {
  2845. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2846. switch (hparams.n_layer) {
  2847. case 12: model.type = e_model::MODEL_SMALL; break;
  2848. case 24: model.type = e_model::MODEL_MEDIUM; break;
  2849. case 36: model.type = e_model::MODEL_LARGE; break;
  2850. case 48: model.type = e_model::MODEL_XL; break;
  2851. default: model.type = e_model::MODEL_UNKNOWN;
  2852. }
  2853. } break;
  2854. case LLM_ARCH_CODESHELL:
  2855. {
  2856. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2857. switch (hparams.n_layer) {
  2858. case 42: model.type = e_model::MODEL_SMALL; break;
  2859. default: model.type = e_model::MODEL_UNKNOWN;
  2860. }
  2861. } break;
  2862. case LLM_ARCH_ORION:
  2863. {
  2864. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2865. switch (hparams.n_layer) {
  2866. case 40: model.type = e_model::MODEL_14B; break;
  2867. default: model.type = e_model::MODEL_UNKNOWN;
  2868. }
  2869. } break;
  2870. case LLM_ARCH_INTERNLM2:
  2871. {
  2872. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2873. switch (hparams.n_layer) {
  2874. case 32: model.type = e_model::MODEL_7B; break;
  2875. case 48: model.type = e_model::MODEL_20B; break;
  2876. default: model.type = e_model::MODEL_UNKNOWN;
  2877. }
  2878. } break;
  2879. case LLM_ARCH_GEMMA:
  2880. {
  2881. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2882. switch (hparams.n_layer) {
  2883. case 18: model.type = e_model::MODEL_2B; break;
  2884. case 28: model.type = e_model::MODEL_7B; break;
  2885. default: model.type = e_model::MODEL_UNKNOWN;
  2886. }
  2887. } break;
  2888. default: (void)0;
  2889. }
  2890. model.ftype = ml.ftype;
  2891. if (hparams.f_max_alibi_bias > 0.0f) {
  2892. hparams.need_kq_pos = true;
  2893. }
  2894. hparams.rope_type = llama_rope_type(&model);
  2895. }
  2896. // TODO: This should probably be in llama.h
  2897. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special = false);
  2898. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch);
  2899. static void llm_load_vocab(
  2900. llama_model_loader & ml,
  2901. llama_model & model) {
  2902. auto & vocab = model.vocab;
  2903. struct gguf_context * ctx = ml.ctx_gguf;
  2904. const auto kv = LLM_KV(model.arch);
  2905. const int token_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_LIST).c_str());
  2906. if (token_idx == -1) {
  2907. throw std::runtime_error("cannot find tokenizer vocab in model file\n");
  2908. }
  2909. const float * scores = nullptr;
  2910. const int score_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_SCORES).c_str());
  2911. if (score_idx != -1) {
  2912. scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
  2913. }
  2914. const int * toktypes = nullptr;
  2915. const int toktype_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE).c_str());
  2916. if (toktype_idx != -1) {
  2917. toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
  2918. }
  2919. // determine vocab type
  2920. {
  2921. std::string tokenizer_name;
  2922. ml.get_key(LLM_KV_TOKENIZER_MODEL, tokenizer_name);
  2923. if (tokenizer_name == "llama") {
  2924. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  2925. // default special tokens
  2926. vocab.special_bos_id = 1;
  2927. vocab.special_eos_id = 2;
  2928. vocab.special_unk_id = 0;
  2929. vocab.special_sep_id = -1;
  2930. vocab.special_pad_id = -1;
  2931. const int add_space_prefix_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_ADD_PREFIX).c_str());
  2932. if (add_space_prefix_keyidx != -1) {
  2933. vocab.add_space_prefix = gguf_get_val_bool(ctx, add_space_prefix_keyidx);
  2934. } // The default value of add_space_prefix is true.
  2935. } else if (tokenizer_name == "gpt2") {
  2936. vocab.type = LLAMA_VOCAB_TYPE_BPE;
  2937. // read bpe merges and populate bpe ranks
  2938. const int merges_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_MERGES).c_str());
  2939. if (merges_keyidx == -1) {
  2940. throw std::runtime_error("cannot find tokenizer merges in model file\n");
  2941. }
  2942. const int n_merges = gguf_get_arr_n(ctx, merges_keyidx);
  2943. for (int i = 0; i < n_merges; i++) {
  2944. const std::string word = gguf_get_arr_str(ctx, merges_keyidx, i);
  2945. GGML_ASSERT(codepoints_from_utf8(word).size() > 0);
  2946. std::string first;
  2947. std::string second;
  2948. const size_t pos = word.find(' ', 1);
  2949. if (pos != std::string::npos) {
  2950. first = word.substr(0, pos);
  2951. second = word.substr(pos + 1);
  2952. }
  2953. vocab.bpe_ranks.emplace(std::make_pair(first, second), i);
  2954. }
  2955. // default special tokens
  2956. vocab.special_bos_id = 11;
  2957. vocab.special_eos_id = 11;
  2958. vocab.special_unk_id = -1;
  2959. vocab.special_sep_id = -1;
  2960. vocab.special_pad_id = -1;
  2961. } else if (tokenizer_name == "bert") {
  2962. vocab.type = LLAMA_VOCAB_TYPE_WPM;
  2963. // default special tokens
  2964. vocab.special_bos_id = 101;
  2965. vocab.special_eos_id = 102;
  2966. vocab.special_unk_id = 100;
  2967. vocab.special_sep_id = -1;
  2968. vocab.special_pad_id = -1;
  2969. vocab.add_space_prefix = false;
  2970. } else {
  2971. LLAMA_LOG_WARN("%s: unknown tokenizer: '%s'", __func__, tokenizer_name.c_str());
  2972. LLAMA_LOG_WARN("%s: using default tokenizer: 'llama'", __func__);
  2973. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  2974. }
  2975. }
  2976. const uint32_t n_vocab = gguf_get_arr_n(ctx, token_idx);
  2977. vocab.id_to_token.resize(n_vocab);
  2978. for (uint32_t i = 0; i < n_vocab; i++) {
  2979. std::string word = gguf_get_arr_str(ctx, token_idx, i);
  2980. GGML_ASSERT(codepoints_from_utf8(word).size() > 0);
  2981. vocab.token_to_id[word] = i;
  2982. auto & token_data = vocab.id_to_token[i];
  2983. token_data.text = std::move(word);
  2984. token_data.score = scores ? scores[i] : 0.0f;
  2985. token_data.type = toktypes ? (llama_token_type) toktypes[i] : LLAMA_TOKEN_TYPE_NORMAL;
  2986. }
  2987. GGML_ASSERT(vocab.id_to_token.size() == vocab.token_to_id.size());
  2988. // determine the newline token: LLaMA "<0x0A>" == 10 == '\n', Falcon 193 == '\n'
  2989. if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  2990. try {
  2991. vocab.linefeed_id = llama_byte_to_token(vocab, '\n');
  2992. } catch (const std::exception & e) {
  2993. LLAMA_LOG_WARN("%s: SPM vocabulary, but newline token not found: %s! Using special_pad_id instead.", __func__, e.what());
  2994. vocab.linefeed_id = vocab.special_pad_id;
  2995. }
  2996. } else if (vocab.type == LLAMA_VOCAB_TYPE_WPM) {
  2997. vocab.linefeed_id = vocab.special_pad_id;
  2998. } else {
  2999. const std::vector<int> ids = llama_tokenize_internal(vocab, "\u010A", false);
  3000. GGML_ASSERT(!ids.empty() && "model vocab missing newline token");
  3001. vocab.linefeed_id = ids[0];
  3002. }
  3003. // special tokens
  3004. {
  3005. const std::vector<std::pair<enum llm_kv, int32_t &>> special_token_types = {
  3006. { LLM_KV_TOKENIZER_BOS_ID, vocab.special_bos_id },
  3007. { LLM_KV_TOKENIZER_EOS_ID, vocab.special_eos_id },
  3008. { LLM_KV_TOKENIZER_UNK_ID, vocab.special_unk_id },
  3009. { LLM_KV_TOKENIZER_SEP_ID, vocab.special_sep_id },
  3010. { LLM_KV_TOKENIZER_PAD_ID, vocab.special_pad_id },
  3011. };
  3012. for (const auto & it : special_token_types) {
  3013. const std::string & key = kv(std::get<0>(it));
  3014. int32_t & id = std::get<1>(it);
  3015. uint32_t new_id;
  3016. if (!ml.get_key(std::get<0>(it), new_id, false)) {
  3017. continue;
  3018. }
  3019. if (new_id >= vocab.id_to_token.size()) {
  3020. LLAMA_LOG_WARN("%s: bad special token: '%s' = %ud, using default id %d\n",
  3021. __func__, key.c_str(), new_id, id);
  3022. } else {
  3023. id = new_id;
  3024. }
  3025. }
  3026. // Handle add_bos_token and add_eos_token
  3027. {
  3028. bool temp = true;
  3029. if (ml.get_key(LLM_KV_TOKENIZER_ADD_BOS, temp, false)) {
  3030. vocab.special_add_bos = int(temp);
  3031. }
  3032. if (ml.get_key(LLM_KV_TOKENIZER_ADD_EOS, temp, false)) {
  3033. vocab.special_add_eos = int(temp);
  3034. }
  3035. }
  3036. }
  3037. // build special tokens cache
  3038. {
  3039. // TODO: It is unclear (to me) at this point, whether special tokes are guaranteed to be of a deterministic type,
  3040. // and will always be correctly labeled in 'added_tokens.json' etc.
  3041. // The assumption is, since special tokens aren't meant to be exposed to end user, they are designed
  3042. // to be unmatchable by the tokenizer, therefore tokens from the vocab, which are unmatchable by the tokenizer
  3043. // are special tokens.
  3044. // From testing, this appears to correlate 1:1 with special tokens.
  3045. //
  3046. // Counting special tokens and verifying in only one direction
  3047. // is sufficient to detect difference in those two sets.
  3048. //
  3049. uint32_t special_tokens_count_by_type = 0;
  3050. uint32_t special_tokens_count_from_verification = 0;
  3051. bool special_tokens_definition_mismatch = false;
  3052. for (const auto & t : vocab.token_to_id) {
  3053. const auto & token = t.first;
  3054. const auto & id = t.second;
  3055. // Count all non-normal tokens in the vocab while iterating
  3056. if (vocab.id_to_token[id].type != LLAMA_TOKEN_TYPE_NORMAL) {
  3057. special_tokens_count_by_type++;
  3058. }
  3059. // Skip single character tokens
  3060. if (token.length() > 1) {
  3061. bool is_tokenizable = false;
  3062. // Split token string representation in two, in all possible ways
  3063. // and check if both halves can be matched to a valid token
  3064. for (unsigned i = 1; i < token.length();) {
  3065. const auto left = token.substr(0, i);
  3066. const auto right = token.substr(i);
  3067. // check if we didnt partition in the middle of a utf sequence
  3068. auto utf = utf8_len(left.at(left.length() - 1));
  3069. if (utf == 1) {
  3070. if (vocab.token_to_id.find(left) != vocab.token_to_id.end() &&
  3071. vocab.token_to_id.find(right) != vocab.token_to_id.end() ) {
  3072. is_tokenizable = true;
  3073. break;
  3074. }
  3075. i++;
  3076. } else {
  3077. // skip over the rest of multibyte utf sequence
  3078. i += utf - 1;
  3079. }
  3080. }
  3081. if (!is_tokenizable) {
  3082. // Some tokens are multibyte, but they are utf sequences with equivalent text length of 1
  3083. // it's faster to re-filter them here, since there are way less candidates now
  3084. // Calculate a total "utf" length of a token string representation
  3085. size_t utf8_str_len = 0;
  3086. for (unsigned i = 0; i < token.length();) {
  3087. utf8_str_len++;
  3088. i += utf8_len(token.at(i));
  3089. }
  3090. // And skip the ones which are one character
  3091. if (utf8_str_len > 1) {
  3092. // At this point what we have left are special tokens only
  3093. vocab.special_tokens_cache[token] = id;
  3094. // Count manually found special tokens
  3095. special_tokens_count_from_verification++;
  3096. // If this manually found special token is not marked as such, flag a mismatch
  3097. if (vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL) {
  3098. special_tokens_definition_mismatch = true;
  3099. }
  3100. }
  3101. }
  3102. }
  3103. }
  3104. if (special_tokens_definition_mismatch || special_tokens_count_from_verification != special_tokens_count_by_type) {
  3105. LLAMA_LOG_WARN("%s: mismatch in special tokens definition ( %u/%zu vs %u/%zu ).\n",
  3106. __func__,
  3107. special_tokens_count_from_verification, vocab.id_to_token.size(),
  3108. special_tokens_count_by_type, vocab.id_to_token.size()
  3109. );
  3110. } else {
  3111. LLAMA_LOG_INFO("%s: special tokens definition check successful ( %u/%zu ).\n",
  3112. __func__,
  3113. special_tokens_count_from_verification, vocab.id_to_token.size()
  3114. );
  3115. }
  3116. }
  3117. }
  3118. static void llm_load_print_meta(llama_model_loader & ml, llama_model & model) {
  3119. const auto & hparams = model.hparams;
  3120. const auto & vocab = model.vocab;
  3121. const char * rope_scaling_type = LLAMA_ROPE_SCALING_TYPES.at(hparams.rope_scaling_type_train);
  3122. // hparams
  3123. LLAMA_LOG_INFO("%s: format = %s\n", __func__, llama_file_version_name(ml.fver));
  3124. LLAMA_LOG_INFO("%s: arch = %s\n", __func__, LLM_ARCH_NAMES.at(model.arch));
  3125. LLAMA_LOG_INFO("%s: vocab type = %s\n", __func__, llama_model_vocab_type_name(vocab.type));
  3126. LLAMA_LOG_INFO("%s: n_vocab = %u\n", __func__, hparams.n_vocab);
  3127. LLAMA_LOG_INFO("%s: n_merges = %u\n", __func__, (int) vocab.bpe_ranks.size());
  3128. LLAMA_LOG_INFO("%s: n_ctx_train = %u\n", __func__, hparams.n_ctx_train);
  3129. LLAMA_LOG_INFO("%s: n_embd = %u\n", __func__, hparams.n_embd);
  3130. LLAMA_LOG_INFO("%s: n_head = %u\n", __func__, hparams.n_head);
  3131. LLAMA_LOG_INFO("%s: n_head_kv = %u\n", __func__, hparams.n_head_kv);
  3132. LLAMA_LOG_INFO("%s: n_layer = %u\n", __func__, hparams.n_layer);
  3133. LLAMA_LOG_INFO("%s: n_rot = %u\n", __func__, hparams.n_rot);
  3134. LLAMA_LOG_INFO("%s: n_embd_head_k = %u\n", __func__, hparams.n_embd_head_k);
  3135. LLAMA_LOG_INFO("%s: n_embd_head_v = %u\n", __func__, hparams.n_embd_head_v);
  3136. LLAMA_LOG_INFO("%s: n_gqa = %u\n", __func__, hparams.n_gqa());
  3137. LLAMA_LOG_INFO("%s: n_embd_k_gqa = %u\n", __func__, hparams.n_embd_k_gqa());
  3138. LLAMA_LOG_INFO("%s: n_embd_v_gqa = %u\n", __func__, hparams.n_embd_v_gqa());
  3139. LLAMA_LOG_INFO("%s: f_norm_eps = %.1e\n", __func__, hparams.f_norm_eps);
  3140. LLAMA_LOG_INFO("%s: f_norm_rms_eps = %.1e\n", __func__, hparams.f_norm_rms_eps);
  3141. LLAMA_LOG_INFO("%s: f_clamp_kqv = %.1e\n", __func__, hparams.f_clamp_kqv);
  3142. LLAMA_LOG_INFO("%s: f_max_alibi_bias = %.1e\n", __func__, hparams.f_max_alibi_bias);
  3143. LLAMA_LOG_INFO("%s: n_ff = %u\n", __func__, hparams.n_ff);
  3144. LLAMA_LOG_INFO("%s: n_expert = %u\n", __func__, hparams.n_expert);
  3145. LLAMA_LOG_INFO("%s: n_expert_used = %u\n", __func__, hparams.n_expert_used);
  3146. LLAMA_LOG_INFO("%s: pooling type = %d\n", __func__, hparams.pooling_type);
  3147. LLAMA_LOG_INFO("%s: rope type = %d\n", __func__, hparams.rope_type);
  3148. LLAMA_LOG_INFO("%s: rope scaling = %s\n", __func__, rope_scaling_type);
  3149. LLAMA_LOG_INFO("%s: freq_base_train = %.1f\n", __func__, hparams.rope_freq_base_train);
  3150. LLAMA_LOG_INFO("%s: freq_scale_train = %g\n", __func__, hparams.rope_freq_scale_train);
  3151. LLAMA_LOG_INFO("%s: n_yarn_orig_ctx = %u\n", __func__, hparams.n_yarn_orig_ctx);
  3152. LLAMA_LOG_INFO("%s: rope_finetuned = %s\n", __func__, hparams.rope_finetuned ? "yes" : "unknown");
  3153. LLAMA_LOG_INFO("%s: model type = %s\n", __func__, llama_model_type_name(model.type));
  3154. LLAMA_LOG_INFO("%s: model ftype = %s\n", __func__, llama_model_ftype_name(model.ftype).c_str());
  3155. if (ml.n_elements >= 1e12) {
  3156. LLAMA_LOG_INFO("%s: model params = %.2f T\n", __func__, ml.n_elements*1e-12);
  3157. } else if (ml.n_elements >= 1e9) {
  3158. LLAMA_LOG_INFO("%s: model params = %.2f B\n", __func__, ml.n_elements*1e-9);
  3159. } else if (ml.n_elements >= 1e6) {
  3160. LLAMA_LOG_INFO("%s: model params = %.2f M\n", __func__, ml.n_elements*1e-6);
  3161. } else {
  3162. LLAMA_LOG_INFO("%s: model params = %.2f K\n", __func__, ml.n_elements*1e-3);
  3163. }
  3164. if (ml.n_bytes < GiB) {
  3165. 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);
  3166. } else {
  3167. 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);
  3168. }
  3169. // general kv
  3170. LLAMA_LOG_INFO("%s: general.name = %s\n", __func__, model.name.c_str());
  3171. // special tokens
  3172. 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() ); }
  3173. 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() ); }
  3174. 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() ); }
  3175. 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() ); }
  3176. 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() ); }
  3177. 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() ); }
  3178. }
  3179. // Returns false if cancelled by progress_callback
  3180. static bool llm_load_tensors(
  3181. llama_model_loader & ml,
  3182. llama_model & model,
  3183. int n_gpu_layers,
  3184. enum llama_split_mode split_mode,
  3185. int main_gpu,
  3186. const float * tensor_split,
  3187. bool use_mlock,
  3188. llama_progress_callback progress_callback,
  3189. void * progress_callback_user_data) {
  3190. model.t_start_us = ggml_time_us();
  3191. auto & hparams = model.hparams;
  3192. model.split_mode = split_mode;
  3193. model.main_gpu = main_gpu;
  3194. model.n_gpu_layers = n_gpu_layers;
  3195. const int64_t n_layer = hparams.n_layer;
  3196. const int64_t i_gpu_start = std::max((int64_t) hparams.n_layer - n_gpu_layers, (int64_t) 0);
  3197. // there is very little benefit to offloading the input layer, so always keep it on the CPU
  3198. model.buft_input = llama_default_buffer_type_cpu(true);
  3199. model.buft_layer.resize(n_layer);
  3200. // assign cpu layers
  3201. for (int64_t i = 0; i < i_gpu_start; ++i) {
  3202. model.buft_layer[i] = llama_default_buffer_type_cpu(true);
  3203. }
  3204. if (split_mode == LLAMA_SPLIT_MODE_LAYER) {
  3205. // calculate the split points
  3206. int device_count = llama_get_device_count();
  3207. bool all_zero = tensor_split == nullptr || std::all_of(tensor_split, tensor_split + device_count, [](float x) { return x == 0.0f; });
  3208. std::vector<float> splits(device_count);
  3209. if (all_zero) {
  3210. // default split, by free memory
  3211. for (int i = 0; i < device_count; ++i) {
  3212. splits[i] = llama_get_device_memory(i);
  3213. }
  3214. } else {
  3215. std::copy(tensor_split, tensor_split + device_count, splits.begin());
  3216. }
  3217. // sum and normalize the splits to get the split points
  3218. float split_sum = 0.0f;
  3219. for (int i = 0; i < device_count; ++i) {
  3220. split_sum += splits[i];
  3221. splits[i] = split_sum;
  3222. }
  3223. for (int i = 0; i < device_count; ++i) {
  3224. splits[i] /= split_sum;
  3225. }
  3226. // assign the repeating layers to the devices according to the splits
  3227. int act_gpu_layers = std::min(n_gpu_layers, (int)n_layer + 1);
  3228. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  3229. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(i - i_gpu_start)/act_gpu_layers) - splits.begin();
  3230. model.buft_layer[i] = llama_default_buffer_type_offload(layer_gpu);
  3231. }
  3232. // assign the output layer
  3233. if (n_gpu_layers > n_layer) {
  3234. int layer_gpu = std::upper_bound(splits.begin(), splits.begin() + device_count, float(act_gpu_layers - 1)/act_gpu_layers) - splits.begin();
  3235. model.buft_output = llama_default_buffer_type_offload(layer_gpu);
  3236. } else {
  3237. model.buft_output = llama_default_buffer_type_cpu(true);
  3238. }
  3239. } else {
  3240. ggml_backend_buffer_type_t split_buft;
  3241. if (split_mode == LLAMA_SPLIT_MODE_ROW) {
  3242. split_buft = llama_default_buffer_type_split(main_gpu, tensor_split);
  3243. } else {
  3244. // LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_LAYER in backends where it is not supported
  3245. split_buft = llama_default_buffer_type_offload(main_gpu);
  3246. }
  3247. // assign the repeating layers
  3248. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  3249. model.buft_layer[i] = {
  3250. split_buft,
  3251. llama_default_buffer_type_offload(main_gpu)
  3252. };
  3253. }
  3254. // assign the output layer
  3255. if (n_gpu_layers > n_layer) {
  3256. model.buft_output = {
  3257. split_buft,
  3258. llama_default_buffer_type_offload(main_gpu)
  3259. };
  3260. } else {
  3261. model.buft_output = llama_default_buffer_type_cpu(true);
  3262. }
  3263. }
  3264. // count used buffer types
  3265. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  3266. buft_layer_count[model.buft_input.buft]++;
  3267. buft_layer_count[model.buft_input.buft_matrix]++;
  3268. buft_layer_count[model.buft_output.buft]++;
  3269. buft_layer_count[model.buft_output.buft_matrix]++;
  3270. for (int64_t i = 0; i < n_layer; ++i) {
  3271. buft_layer_count[model.buft_layer[i].buft]++;
  3272. buft_layer_count[model.buft_layer[i].buft_matrix]++;
  3273. }
  3274. // create one context per buffer type
  3275. size_t ctx_size = ggml_tensor_overhead()*(ml.n_tensors + 1); // +1 for models where tok_embd is duplicated as output
  3276. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  3277. for (auto & it : buft_layer_count) {
  3278. struct ggml_init_params params = {
  3279. /*.mem_size =*/ ctx_size,
  3280. /*.mem_buffer =*/ NULL,
  3281. /*.no_alloc =*/ true,
  3282. };
  3283. ggml_context * ctx = ggml_init(params);
  3284. if (!ctx) {
  3285. throw std::runtime_error(format("failed to create context"));
  3286. }
  3287. ctx_map[it.first] = ctx;
  3288. model.ctxs.push_back(ctx);
  3289. }
  3290. LLAMA_LOG_INFO("%s: ggml ctx size = %7.2f MiB\n", __func__, model.ctxs.size()*ctx_size/1024.0/1024.0);
  3291. // create tensors for the weights
  3292. {
  3293. const int64_t n_embd = hparams.n_embd;
  3294. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3295. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  3296. const int64_t n_embd_gqa = n_embd_v_gqa;
  3297. const int64_t n_vocab = hparams.n_vocab;
  3298. const int64_t n_vocab_type = hparams.n_vocab_type;
  3299. const int64_t n_ff = hparams.n_ff;
  3300. GGML_ASSERT(n_embd_gqa == n_embd_k_gqa);
  3301. ggml_context * ctx_input = ctx_map.at(model.buft_input.buft);
  3302. ggml_context * ctx_output = ctx_map.at(model.buft_output.buft);
  3303. ggml_context * ctx_output_split = ctx_map.at(model.buft_output.buft_matrix);
  3304. auto ctx_for_layer = [&](int i) { return ctx_map.at(model.buft_layer[i].buft); };
  3305. auto ctx_for_layer_split = [&](int i) { return ctx_map.at(model.buft_layer[i].buft_matrix); };
  3306. model.layers.resize(n_layer);
  3307. const auto tn = LLM_TN(model.arch);
  3308. switch (model.arch) {
  3309. case LLM_ARCH_LLAMA:
  3310. case LLM_ARCH_REFACT:
  3311. case LLM_ARCH_MINICPM:
  3312. {
  3313. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3314. // output
  3315. {
  3316. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3317. if (model.arch != LLM_ARCH_MINICPM){
  3318. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3319. }
  3320. }
  3321. for (int i = 0; i < n_layer; ++i) {
  3322. ggml_context * ctx_layer = ctx_for_layer(i);
  3323. ggml_context * ctx_split = ctx_for_layer_split(i);
  3324. auto & layer = model.layers[i];
  3325. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3326. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3327. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3328. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3329. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3330. // optional bias tensors
  3331. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, false);
  3332. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, false);
  3333. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, false);
  3334. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, false);
  3335. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3336. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd}, false);
  3337. if (layer.ffn_gate_inp == nullptr) {
  3338. GGML_ASSERT(hparams.n_expert == 0);
  3339. GGML_ASSERT(hparams.n_expert_used == 0);
  3340. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3341. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3342. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3343. } else {
  3344. GGML_ASSERT(hparams.n_expert > 0);
  3345. GGML_ASSERT(hparams.n_expert_used > 0);
  3346. // MoE branch
  3347. for (uint32_t x = 0; x < hparams.n_expert; ++x) {
  3348. layer.ffn_gate_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, x), {n_embd, n_ff});
  3349. layer.ffn_down_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, x), { n_ff, n_embd});
  3350. layer.ffn_up_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, x), {n_embd, n_ff});
  3351. }
  3352. }
  3353. }
  3354. } break;
  3355. case LLM_ARCH_BAICHUAN:
  3356. {
  3357. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3358. {
  3359. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3360. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3361. }
  3362. for (int i = 0; i < n_layer; ++i) {
  3363. ggml_context * ctx_layer = ctx_for_layer(i);
  3364. ggml_context * ctx_split = ctx_for_layer_split(i);
  3365. auto & layer = model.layers[i];
  3366. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3367. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3368. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3369. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3370. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3371. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {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_FALCON:
  3378. {
  3379. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3380. // output
  3381. {
  3382. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3383. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3384. if (gguf_find_tensor(ml.ctx_gguf, tn(LLM_TENSOR_OUTPUT, "weight").c_str()) >= 0) {
  3385. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3386. } else {
  3387. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}); // needs to be on GPU
  3388. ml.n_created--; // artificial tensor
  3389. ml.size_data += ggml_nbytes(model.output);
  3390. }
  3391. }
  3392. for (int i = 0; i < n_layer; ++i) {
  3393. ggml_context * ctx_layer = ctx_for_layer(i);
  3394. ggml_context * ctx_split = ctx_for_layer_split(i);
  3395. auto & layer = model.layers[i];
  3396. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3397. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3398. if (gguf_find_tensor(ml.ctx_gguf, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i).c_str()) >= 0) {
  3399. layer.attn_norm_2 = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i), {n_embd});
  3400. layer.attn_norm_2_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "bias", i), {n_embd});
  3401. }
  3402. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3403. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3404. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3405. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3406. }
  3407. } break;
  3408. case LLM_ARCH_STARCODER:
  3409. {
  3410. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3411. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3412. // output
  3413. {
  3414. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3415. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3416. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3417. }
  3418. for (int i = 0; i < n_layer; ++i) {
  3419. ggml_context * ctx_layer = ctx_for_layer(i);
  3420. ggml_context * ctx_split = ctx_for_layer_split(i);
  3421. auto & layer = model.layers[i];
  3422. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3423. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3424. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3425. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3426. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3427. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3428. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3429. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3430. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3431. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3432. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3433. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3434. }
  3435. } break;
  3436. case LLM_ARCH_PERSIMMON:
  3437. {
  3438. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3439. {
  3440. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3441. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3442. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3443. }
  3444. for (int i = 0; i < n_layer; ++i) {
  3445. ggml_context * ctx_layer = ctx_for_layer(i);
  3446. ggml_context * ctx_split = ctx_for_layer_split(i);
  3447. auto & layer = model.layers[i];
  3448. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3449. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3450. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3451. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3452. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3453. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3454. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3455. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3456. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3457. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3458. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3459. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3460. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {64});
  3461. layer.attn_q_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "bias", i), {64});
  3462. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {64});
  3463. layer.attn_k_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "bias", i), {64});
  3464. }
  3465. } break;
  3466. case LLM_ARCH_BERT:
  3467. case LLM_ARCH_NOMIC_BERT:
  3468. {
  3469. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3470. model.type_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_TYPES, "weight"), {n_embd, n_vocab_type});
  3471. if (model.arch == LLM_ARCH_BERT) {
  3472. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3473. }
  3474. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  3475. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  3476. for (int i = 0; i < n_layer; ++i) {
  3477. ggml_context * ctx_layer = ctx_for_layer(i);
  3478. ggml_context * ctx_split = ctx_for_layer_split(i);
  3479. auto & layer = model.layers[i];
  3480. if (model.arch == LLM_ARCH_BERT) {
  3481. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3482. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  3483. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3484. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  3485. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3486. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  3487. } else {
  3488. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3489. }
  3490. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3491. layer.attn_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "weight", i), {n_embd});
  3492. layer.attn_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT_NORM, "bias", i), {n_embd});
  3493. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3494. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3495. if (model.arch == LLM_ARCH_BERT) {
  3496. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3497. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3498. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3499. } else {
  3500. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3501. }
  3502. layer.layer_out_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "weight", i), {n_embd});
  3503. layer.layer_out_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_LAYER_OUT_NORM, "bias", i), {n_embd});
  3504. }
  3505. } break;
  3506. case LLM_ARCH_BLOOM:
  3507. {
  3508. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3509. model.tok_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  3510. model.tok_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  3511. // output
  3512. {
  3513. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3514. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3515. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3516. }
  3517. for (int i = 0; i < n_layer; ++i) {
  3518. ggml_context * ctx_layer = ctx_for_layer(i);
  3519. ggml_context * ctx_split = ctx_for_layer_split(i);
  3520. auto & layer = model.layers[i];
  3521. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3522. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3523. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3524. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3525. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3526. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3527. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3528. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3529. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3530. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3531. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3532. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3533. }
  3534. } break;
  3535. case LLM_ARCH_MPT:
  3536. {
  3537. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3538. // output
  3539. {
  3540. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3541. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd}, false);
  3542. // same as tok_embd, duplicated to allow offloading
  3543. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3544. ml.n_created--; // artificial tensor
  3545. ml.size_data += ggml_nbytes(model.output);
  3546. }
  3547. for (int i = 0; i < n_layer; ++i) {
  3548. ggml_context * ctx_layer = ctx_for_layer(i);
  3549. ggml_context * ctx_split = ctx_for_layer_split(i);
  3550. auto & layer = model.layers[i];
  3551. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3552. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd}, false);
  3553. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3554. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, false);
  3555. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3556. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, false);
  3557. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3558. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd}, false);
  3559. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3560. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, false);
  3561. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3562. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, false);
  3563. // AWQ ScaleActivation layer
  3564. layer.ffn_act = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_ACT, "scales", i), {n_ff}, false);
  3565. }
  3566. } break;
  3567. case LLM_ARCH_STABLELM:
  3568. {
  3569. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3570. // output
  3571. {
  3572. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3573. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3574. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3575. }
  3576. for (int i = 0; i < n_layer; ++i) {
  3577. ggml_context * ctx_layer = ctx_for_layer(i);
  3578. ggml_context * ctx_split = ctx_for_layer_split(i);
  3579. auto & layer = model.layers[i];
  3580. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3581. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3582. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3583. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3584. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3585. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3586. // optional bias tensors, present in Stable LM 2 1.6B
  3587. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, false);
  3588. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, false);
  3589. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, false);
  3590. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3591. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3592. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3593. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3594. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3595. }
  3596. } break;
  3597. case LLM_ARCH_QWEN:
  3598. {
  3599. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3600. // output
  3601. {
  3602. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3603. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3604. }
  3605. for (int i = 0; i < n_layer; ++i) {
  3606. ggml_context * ctx_layer = ctx_for_layer(i);
  3607. ggml_context * ctx_split = ctx_for_layer_split(i);
  3608. auto & layer = model.layers[i];
  3609. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3610. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd*3});
  3611. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd*3});
  3612. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3613. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3614. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff/2});
  3615. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff/2, n_embd});
  3616. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff/2});
  3617. }
  3618. } break;
  3619. case LLM_ARCH_QWEN2:
  3620. {
  3621. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3622. // output
  3623. {
  3624. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3625. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3626. }
  3627. for (int i = 0; i < n_layer; ++i) {
  3628. ggml_context * ctx_layer = ctx_for_layer(i);
  3629. ggml_context * ctx_split = ctx_for_layer_split(i);
  3630. auto & layer = model.layers[i];
  3631. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3632. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3633. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3634. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3635. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3636. // optional bias tensors
  3637. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  3638. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  3639. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  3640. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3641. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3642. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3643. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3644. }
  3645. } break;
  3646. case LLM_ARCH_PHI2:
  3647. {
  3648. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3649. // output
  3650. {
  3651. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3652. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3653. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3654. model.output_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT, "bias"), {n_vocab});
  3655. }
  3656. for (int i = 0; i < n_layer; ++i) {
  3657. ggml_context * ctx_layer = ctx_for_layer(i);
  3658. ggml_context * ctx_split = ctx_for_layer_split(i);
  3659. auto & layer = model.layers[i];
  3660. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3661. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3662. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, false);
  3663. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, false);
  3664. if (layer.wqkv == nullptr) {
  3665. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3666. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  3667. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3668. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  3669. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3670. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  3671. }
  3672. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3673. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3674. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3675. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3676. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3677. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3678. }
  3679. } break;
  3680. case LLM_ARCH_PLAMO:
  3681. {
  3682. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3683. // output
  3684. {
  3685. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3686. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3687. }
  3688. for (int i = 0; i < n_layer; ++i) {
  3689. ggml_context * ctx_layer = ctx_for_layer(i);
  3690. ggml_context * ctx_split = ctx_for_layer_split(i);
  3691. auto & layer = model.layers[i];
  3692. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3693. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3694. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3695. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3696. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3697. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3698. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3699. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3700. }
  3701. } break;
  3702. case LLM_ARCH_GPT2:
  3703. {
  3704. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3705. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3706. // output
  3707. {
  3708. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3709. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3710. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3711. }
  3712. for (int i = 0; i < n_layer; ++i) {
  3713. ggml_context * ctx_layer = ctx_for_layer(i);
  3714. ggml_context * ctx_split = ctx_for_layer_split(i);
  3715. auto & layer = model.layers[i];
  3716. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3717. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3718. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3719. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3720. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3721. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3722. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3723. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3724. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3725. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3726. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3727. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3728. }
  3729. } break;
  3730. case LLM_ARCH_CODESHELL:
  3731. {
  3732. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3733. // output
  3734. {
  3735. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3736. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3737. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3738. }
  3739. for (int i = 0; i < n_layer; ++i) {
  3740. ggml_context * ctx_layer = ctx_for_layer(i);
  3741. ggml_context * ctx_split = ctx_for_layer_split(i);
  3742. auto & layer = model.layers[i];
  3743. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3744. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3745. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3746. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3747. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3748. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3749. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3750. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3751. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3752. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3753. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3754. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3755. }
  3756. } break;
  3757. case LLM_ARCH_ORION:
  3758. {
  3759. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3760. {
  3761. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3762. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3763. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3764. }
  3765. for (int i = 0; i < n_layer; ++i) {
  3766. ggml_context * ctx_layer = ctx_for_layer(i);
  3767. ggml_context * ctx_split = ctx_for_layer_split(i);
  3768. auto & layer = model.layers[i];
  3769. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3770. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3771. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3772. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3773. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3774. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3775. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3776. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3777. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3778. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3779. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3780. }
  3781. } break;
  3782. case LLM_ARCH_INTERNLM2:
  3783. {
  3784. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3785. // output
  3786. {
  3787. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3788. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3789. }
  3790. for (int i = 0; i < n_layer; ++i) {
  3791. ggml_context * ctx_layer = ctx_for_layer(i);
  3792. ggml_context * ctx_split = ctx_for_layer_split(i);
  3793. auto & layer = model.layers[i];
  3794. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3795. // layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3796. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3797. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3798. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3799. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3800. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3801. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3802. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3803. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3804. }
  3805. } break;
  3806. case LLM_ARCH_GEMMA:
  3807. {
  3808. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3809. // output
  3810. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3811. model.output = ml.create_tensor(ctx_output, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}); // same as tok_embd, duplicated to allow offloading
  3812. ml.n_created--; // artificial tensor
  3813. ml.size_data += ggml_nbytes(model.output);
  3814. const int64_t n_ff = hparams.n_ff;
  3815. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  3816. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3817. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  3818. for (uint32_t i = 0; i < n_layer; ++i) {
  3819. ggml_context * ctx_layer = ctx_for_layer(i);
  3820. ggml_context * ctx_split = ctx_for_layer_split(i);
  3821. auto & layer = model.layers[i];
  3822. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3823. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head_k * hparams.n_head});
  3824. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k_gqa});
  3825. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v_gqa});
  3826. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_k * hparams.n_head, n_embd});
  3827. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3828. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3829. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3830. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3831. }
  3832. } break;
  3833. default:
  3834. throw std::runtime_error("unknown architecture");
  3835. }
  3836. }
  3837. ml.done_getting_tensors();
  3838. ml.init_mapping(true, use_mlock ? &model.mlock_mmap : nullptr);
  3839. // create the backend buffers
  3840. std::vector<std::pair<ggml_context *, ggml_backend_buffer_t>> ctx_bufs;
  3841. for (auto & it : ctx_map) {
  3842. ggml_backend_buffer_type_t buft = it.first;
  3843. ggml_context * ctx = it.second;
  3844. ggml_backend_buffer_t buf = nullptr;
  3845. // only the mmap region containing the tensors in the model is mapped to the backend buffer
  3846. // 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
  3847. // this allows using partial offloading when the model size exceeds the metal buffer size, but not the RAM size
  3848. if (ml.use_mmap && buft == llama_default_buffer_type_cpu(true)) {
  3849. size_t first, last;
  3850. ml.get_mapping_range(&first, &last, ctx);
  3851. buf = ggml_backend_cpu_buffer_from_ptr((char *) ml.mapping->addr + first, last - first);
  3852. }
  3853. #ifdef GGML_USE_METAL
  3854. else if (ml.use_mmap && buft == ggml_backend_metal_buffer_type()) {
  3855. const size_t max_size = ggml_get_max_tensor_size(ctx);
  3856. size_t first, last;
  3857. ml.get_mapping_range(&first, &last, ctx);
  3858. buf = ggml_backend_metal_buffer_from_ptr((char *) ml.mapping->addr + first, last - first, max_size);
  3859. }
  3860. #endif
  3861. else {
  3862. buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  3863. if (buf != nullptr && use_mlock && ggml_backend_buffer_is_host(buf)) {
  3864. model.mlock_bufs.emplace_back(new llama_mlock);
  3865. auto & mlock_buf = model.mlock_bufs.back();
  3866. mlock_buf->init (ggml_backend_buffer_get_base(buf));
  3867. mlock_buf->grow_to(ggml_backend_buffer_get_size(buf));
  3868. }
  3869. }
  3870. if (buf == nullptr) {
  3871. throw std::runtime_error("failed to allocate buffer");
  3872. }
  3873. // indicate that this buffer contains weights
  3874. // 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
  3875. ggml_backend_buffer_set_usage(buf, GGML_BACKEND_BUFFER_USAGE_WEIGHTS);
  3876. model.bufs.push_back(buf);
  3877. ctx_bufs.emplace_back(ctx, buf);
  3878. }
  3879. if (llama_supports_gpu_offload()) {
  3880. const int n_gpu = std::min(n_gpu_layers, int(hparams.n_layer));
  3881. LLAMA_LOG_INFO("%s: offloading %d repeating layers to GPU\n", __func__, n_gpu);
  3882. if (n_gpu_layers > (int) hparams.n_layer) {
  3883. LLAMA_LOG_INFO("%s: offloading non-repeating layers to GPU\n", __func__);
  3884. }
  3885. const int max_backend_supported_layers = hparams.n_layer + 1;
  3886. const int max_offloadable_layers = hparams.n_layer + 1;
  3887. LLAMA_LOG_INFO("%s: offloaded %d/%d layers to GPU\n", __func__, std::min(n_gpu_layers, max_offloadable_layers), max_backend_supported_layers);
  3888. }
  3889. // print memory requirements
  3890. for (ggml_backend_buffer_t buf : model.bufs) {
  3891. 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);
  3892. }
  3893. // populate tensors_by_name
  3894. for (ggml_context * ctx : model.ctxs) {
  3895. for (auto * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  3896. model.tensors_by_name.emplace_back(ggml_get_name(cur), cur);
  3897. }
  3898. }
  3899. // load tensor data
  3900. for (auto & it : ctx_bufs) {
  3901. ggml_context * ctx = it.first;
  3902. ggml_backend_buffer_t buf = it.second;
  3903. if (!ml.load_all_data(ctx, progress_callback, progress_callback_user_data, buf, use_mlock ? &model.mlock_mmap : NULL)) {
  3904. return false;
  3905. }
  3906. }
  3907. model.mapping = std::move(ml.mapping);
  3908. // loading time will be recalculate after the first eval, so
  3909. // we take page faults deferred by mmap() into consideration
  3910. model.t_load_us = ggml_time_us() - model.t_start_us;
  3911. return true;
  3912. }
  3913. // Returns 0 on success, -1 on error, and -2 on cancellation via llama_progress_callback
  3914. static int llama_model_load(const std::string & fname, llama_model & model, llama_model_params & params) {
  3915. try {
  3916. llama_model_loader ml(fname, params.use_mmap, params.kv_overrides);
  3917. model.hparams.vocab_only = params.vocab_only;
  3918. try {
  3919. llm_load_arch(ml, model);
  3920. } catch(const std::exception & e) {
  3921. throw std::runtime_error("error loading model architecture: " + std::string(e.what()));
  3922. }
  3923. try {
  3924. llm_load_hparams(ml, model);
  3925. } catch(const std::exception & e) {
  3926. throw std::runtime_error("error loading model hyperparameters: " + std::string(e.what()));
  3927. }
  3928. try {
  3929. llm_load_vocab(ml, model);
  3930. } catch(const std::exception & e) {
  3931. throw std::runtime_error("error loading model vocabulary: " + std::string(e.what()));
  3932. }
  3933. llm_load_print_meta(ml, model);
  3934. if (model.hparams.n_vocab != model.vocab.id_to_token.size()) {
  3935. throw std::runtime_error("vocab size mismatch");
  3936. }
  3937. if (params.vocab_only) {
  3938. LLAMA_LOG_INFO("%s: vocab only - skipping tensors\n", __func__);
  3939. return 0;
  3940. }
  3941. #ifdef GGML_USE_KOMPUTE
  3942. if (params.n_gpu_layers > 0 && (
  3943. !(model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON)
  3944. || !(
  3945. model.ftype == LLAMA_FTYPE_ALL_F32 ||
  3946. model.ftype == LLAMA_FTYPE_MOSTLY_F16 ||
  3947. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ||
  3948. model.ftype == LLAMA_FTYPE_MOSTLY_Q4_1
  3949. )
  3950. )) {
  3951. // TODO(cebtenzzre): propagate this error outside of llama_load_model_from_file
  3952. LLAMA_LOG_WARN("%s: disabling Kompute due to unsupported model arch or quantization\n", __func__);
  3953. params.n_gpu_layers = 0;
  3954. }
  3955. #endif
  3956. if (!llm_load_tensors(
  3957. ml, model, params.n_gpu_layers, params.split_mode, params.main_gpu, params.tensor_split, params.use_mlock,
  3958. params.progress_callback, params.progress_callback_user_data
  3959. )) {
  3960. return -2;
  3961. }
  3962. } catch (const std::exception & err) {
  3963. LLAMA_LOG_ERROR("%s: error loading model: %s\n", __func__, err.what());
  3964. return -1;
  3965. }
  3966. return 0;
  3967. }
  3968. //
  3969. // llm_build
  3970. //
  3971. using llm_build_cb = std::function<void(struct ggml_tensor * cur, const char * name, int nl)>;
  3972. enum llm_ffn_op_type {
  3973. LLM_FFN_SILU,
  3974. LLM_FFN_GELU,
  3975. LLM_FFN_RELU,
  3976. LLM_FFN_RELU_SQR,
  3977. };
  3978. enum llm_ffn_gate_type {
  3979. LLM_FFN_SEQ,
  3980. LLM_FFN_PAR, // ffn_gate is parallel to ffn_up
  3981. };
  3982. enum llm_norm_type {
  3983. LLM_NORM,
  3984. LLM_NORM_RMS,
  3985. };
  3986. static struct ggml_tensor * llm_build_inp_embd(
  3987. struct ggml_context * ctx,
  3988. const llama_hparams & hparams,
  3989. const llama_batch & batch,
  3990. struct ggml_tensor * tok_embd,
  3991. struct ggml_tensor * inp_tokens,
  3992. struct ggml_tensor * inp_embd,
  3993. const llm_build_cb & cb) {
  3994. const int64_t n_embd = hparams.n_embd;
  3995. struct ggml_tensor * inpL;
  3996. if (batch.token) {
  3997. struct ggml_tensor * inp_tokens_v = ggml_view_1d(ctx, inp_tokens, batch.n_tokens, 0);
  3998. cb(inp_tokens, "inp_tokens", -1);
  3999. inpL = ggml_get_rows(ctx, tok_embd, inp_tokens_v);
  4000. } else {
  4001. #ifdef GGML_USE_MPI
  4002. GGML_ASSERT(false && "not implemented");
  4003. #endif
  4004. inpL = ggml_view_2d(ctx, inp_embd, n_embd, batch.n_tokens, inp_embd->nb[1], 0);
  4005. }
  4006. return inpL;
  4007. }
  4008. static void llm_build_kv_store(
  4009. struct ggml_context * ctx,
  4010. const llama_hparams & hparams,
  4011. const llama_kv_cache & kv,
  4012. struct ggml_cgraph * graph,
  4013. struct ggml_tensor * k_cur,
  4014. struct ggml_tensor * v_cur,
  4015. int64_t n_ctx,
  4016. int32_t n_tokens,
  4017. int32_t kv_head,
  4018. const llm_build_cb & cb,
  4019. int64_t il) {
  4020. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  4021. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  4022. // compute the transposed [n_tokens, n_embd] V matrix
  4023. struct ggml_tensor * v_cur_t = ggml_transpose(ctx, ggml_reshape_2d(ctx, v_cur, n_embd_v_gqa, n_tokens));
  4024. //struct ggml_tensor * v_cur_t = ggml_transpose(ctx, v_cur); // TODO: reshape above is likely not needed
  4025. cb(v_cur_t, "v_cur_t", il);
  4026. struct ggml_tensor * k_cache_view = ggml_view_1d(ctx, kv.k_l[il], n_tokens*n_embd_k_gqa,
  4027. (ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa))*kv_head);
  4028. cb(k_cache_view, "k_cache_view", il);
  4029. struct ggml_tensor * v_cache_view = ggml_view_2d(ctx, kv.v_l[il], n_tokens, n_embd_v_gqa,
  4030. ( n_ctx)*ggml_element_size(kv.v_l[il]),
  4031. (kv_head)*ggml_element_size(kv.v_l[il]));
  4032. cb(v_cache_view, "v_cache_view", il);
  4033. // important: storing RoPE-ed version of K in the KV cache!
  4034. ggml_build_forward_expand(graph, ggml_cpy(ctx, k_cur, k_cache_view));
  4035. ggml_build_forward_expand(graph, ggml_cpy(ctx, v_cur_t, v_cache_view));
  4036. }
  4037. static struct ggml_tensor * llm_build_norm(
  4038. struct ggml_context * ctx,
  4039. struct ggml_tensor * cur,
  4040. const llama_hparams & hparams,
  4041. struct ggml_tensor * mw,
  4042. struct ggml_tensor * mb,
  4043. llm_norm_type type,
  4044. const llm_build_cb & cb,
  4045. int il) {
  4046. switch (type) {
  4047. case LLM_NORM: cur = ggml_norm (ctx, cur, hparams.f_norm_eps); break;
  4048. case LLM_NORM_RMS: cur = ggml_rms_norm(ctx, cur, hparams.f_norm_rms_eps); break;
  4049. }
  4050. if (mw || mb) {
  4051. cb(cur, "norm", il);
  4052. }
  4053. if (mw) {
  4054. cur = ggml_mul(ctx, cur, mw);
  4055. if (mb) {
  4056. cb(cur, "norm_w", il);
  4057. }
  4058. }
  4059. if (mb) {
  4060. cur = ggml_add(ctx, cur, mb);
  4061. }
  4062. return cur;
  4063. }
  4064. static struct ggml_tensor * llm_build_ffn(
  4065. struct ggml_context * ctx,
  4066. struct ggml_tensor * cur,
  4067. struct ggml_tensor * up,
  4068. struct ggml_tensor * up_b,
  4069. struct ggml_tensor * gate,
  4070. struct ggml_tensor * gate_b,
  4071. struct ggml_tensor * down,
  4072. struct ggml_tensor * down_b,
  4073. struct ggml_tensor * act_scales,
  4074. llm_ffn_op_type type_op,
  4075. llm_ffn_gate_type type_gate,
  4076. const llm_build_cb & cb,
  4077. int il) {
  4078. struct ggml_tensor * tmp = ggml_mul_mat(ctx, up, cur);
  4079. cb(tmp, "ffn_up", il);
  4080. if (up_b) {
  4081. tmp = ggml_add(ctx, tmp, up_b);
  4082. cb(tmp, "ffn_up_b", il);
  4083. }
  4084. if (gate) {
  4085. switch (type_gate) {
  4086. case LLM_FFN_SEQ:
  4087. {
  4088. cur = ggml_mul_mat(ctx, gate, tmp);
  4089. cb(cur, "ffn_gate", il);
  4090. } break;
  4091. case LLM_FFN_PAR:
  4092. {
  4093. cur = ggml_mul_mat(ctx, gate, cur);
  4094. cb(cur, "ffn_gate", il);
  4095. } break;
  4096. }
  4097. if (gate_b) {
  4098. cur = ggml_add(ctx, cur, gate_b);
  4099. cb(cur, "ffn_gate_b", il);
  4100. }
  4101. } else {
  4102. cur = tmp;
  4103. }
  4104. switch (type_op) {
  4105. case LLM_FFN_SILU:
  4106. {
  4107. cur = ggml_silu(ctx, cur);
  4108. cb(cur, "ffn_silu", il);
  4109. } break;
  4110. case LLM_FFN_GELU:
  4111. {
  4112. cur = ggml_gelu(ctx, cur);
  4113. cb(cur, "ffn_gelu", il);
  4114. if (act_scales != NULL) {
  4115. cur = ggml_div(ctx, cur, act_scales);
  4116. cb(cur, "ffn_act", il);
  4117. }
  4118. } break;
  4119. case LLM_FFN_RELU:
  4120. {
  4121. cur = ggml_relu(ctx, cur);
  4122. cb(cur, "ffn_relu", il);
  4123. } break;
  4124. case LLM_FFN_RELU_SQR:
  4125. {
  4126. cur = ggml_relu(ctx, cur);
  4127. cb(cur, "ffn_relu", il);
  4128. cur = ggml_sqr(ctx, cur);
  4129. cb(cur, "ffn_sqr(relu)", il);
  4130. } break;
  4131. }
  4132. if (type_gate == LLM_FFN_PAR) {
  4133. cur = ggml_mul(ctx, cur, tmp);
  4134. cb(cur, "ffn_gate_par", il);
  4135. }
  4136. cur = ggml_mul_mat(ctx, down, cur);
  4137. if (down_b) {
  4138. cb(cur, "ffn_down", il);
  4139. }
  4140. if (down_b) {
  4141. cur = ggml_add(ctx, cur, down_b);
  4142. }
  4143. return cur;
  4144. }
  4145. // if max_alibi_bias > 0 then apply ALiBi
  4146. static struct ggml_tensor * llm_build_kqv(
  4147. struct ggml_context * ctx,
  4148. const llama_model & model,
  4149. const llama_hparams & hparams,
  4150. const llama_kv_cache & kv,
  4151. struct ggml_cgraph * graph,
  4152. struct ggml_tensor * wo,
  4153. struct ggml_tensor * wo_b,
  4154. struct ggml_tensor * q_cur,
  4155. struct ggml_tensor * kq_mask,
  4156. struct ggml_tensor * kq_pos,
  4157. int64_t n_ctx,
  4158. int32_t n_tokens,
  4159. int32_t n_kv,
  4160. float kq_scale,
  4161. const llm_build_cb & cb,
  4162. int il) {
  4163. const int64_t n_head = hparams.n_head;
  4164. const int64_t n_head_kv = hparams.n_head_kv;
  4165. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  4166. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  4167. const int64_t n_embd_head_v = hparams.n_embd_head_v;
  4168. struct ggml_tensor * q = ggml_permute(ctx, q_cur, 0, 2, 1, 3);
  4169. cb(q, "q", il);
  4170. struct ggml_tensor * k =
  4171. ggml_view_3d(ctx, kv.k_l[il],
  4172. n_embd_head_k, n_kv, n_head_kv,
  4173. ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa),
  4174. ggml_row_size(kv.k_l[il]->type, n_embd_head_k),
  4175. 0);
  4176. cb(k, "k", il);
  4177. struct ggml_tensor * kq = ggml_mul_mat(ctx, k, q);
  4178. cb(kq, "kq", il);
  4179. if (model.arch == LLM_ARCH_PHI2) {
  4180. // for this arch, we need to perform the KQ multiplication with F32 precision, otherwise we get NaNs
  4181. // ref: https://github.com/ggerganov/llama.cpp/pull/4490#issuecomment-1859055847
  4182. ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  4183. }
  4184. #if defined(GGML_USE_VULKAN) || defined(GGML_USE_KOMPUTE)
  4185. #pragma message("TODO: ALiBi support in ggml_soft_max_ext is not implemented for Vulkan, and Kompute")
  4186. #pragma message(" Falling back to ggml_alibi(). Will become an error in Mar 2024")
  4187. #pragma message("ref: https://github.com/ggerganov/llama.cpp/pull/5488")
  4188. if (hparams.f_max_alibi_bias > 0.0f) {
  4189. kq = ggml_scale(ctx, kq, kq_scale);
  4190. cb(kq, "kq_scaled", il);
  4191. kq = ggml_alibi(ctx, kq, /*n_past*/ 0, n_head, hparams.f_max_alibi_bias);
  4192. cb(kq, "kq_scaled_alibi", il);
  4193. kq = ggml_add(ctx, kq, kq_mask);
  4194. cb(kq, "kq_masked", il);
  4195. kq = ggml_soft_max(ctx, kq);
  4196. cb(kq, "kq_soft_max", il);
  4197. } else
  4198. #endif
  4199. {
  4200. kq = ggml_soft_max_ext(ctx, kq, kq_mask, kq_pos, kq_scale, hparams.f_max_alibi_bias);
  4201. cb(kq, "kq_soft_max_ext", il);
  4202. }
  4203. // split cached v into n_head heads
  4204. struct ggml_tensor * v =
  4205. ggml_view_3d(ctx, kv.v_l[il],
  4206. n_kv, n_embd_head_v, n_head_kv,
  4207. ggml_element_size(kv.v_l[il])*n_ctx,
  4208. ggml_element_size(kv.v_l[il])*n_ctx*n_embd_head_v,
  4209. 0);
  4210. cb(v, "v", il);
  4211. struct ggml_tensor * kqv = ggml_mul_mat(ctx, v, kq);
  4212. cb(kqv, "kqv", il);
  4213. struct ggml_tensor * kqv_merged = ggml_permute(ctx, kqv, 0, 2, 1, 3);
  4214. cb(kqv_merged, "kqv_merged", il);
  4215. struct ggml_tensor * cur = ggml_cont_2d(ctx, kqv_merged, n_embd_head_k*n_head, n_tokens);
  4216. cb(cur, "kqv_merged_cont", il);
  4217. ggml_build_forward_expand(graph, cur);
  4218. cur = ggml_mul_mat(ctx, wo, cur);
  4219. if (wo_b) {
  4220. cb(cur, "kqv_wo", il);
  4221. }
  4222. if (wo_b) {
  4223. cur = ggml_add(ctx, cur, wo_b);
  4224. }
  4225. return cur;
  4226. }
  4227. static struct ggml_tensor * llm_build_kv(
  4228. struct ggml_context * ctx,
  4229. const llama_model & model,
  4230. const llama_hparams & hparams,
  4231. const llama_kv_cache & kv,
  4232. struct ggml_cgraph * graph,
  4233. struct ggml_tensor * wo,
  4234. struct ggml_tensor * wo_b,
  4235. struct ggml_tensor * k_cur,
  4236. struct ggml_tensor * v_cur,
  4237. struct ggml_tensor * q_cur,
  4238. struct ggml_tensor * kq_mask,
  4239. struct ggml_tensor * kq_pos,
  4240. int64_t n_ctx,
  4241. int32_t n_tokens,
  4242. int32_t kv_head,
  4243. int32_t n_kv,
  4244. float kq_scale,
  4245. const llm_build_cb & cb,
  4246. int il) {
  4247. // these nodes are added to the graph together so that they are not reordered
  4248. // by doing so, the number of splits in the graph is reduced
  4249. ggml_build_forward_expand(graph, q_cur);
  4250. ggml_build_forward_expand(graph, k_cur);
  4251. ggml_build_forward_expand(graph, v_cur);
  4252. llm_build_kv_store(ctx, hparams, kv, graph, k_cur, v_cur, n_ctx, n_tokens, kv_head, cb, il);
  4253. struct ggml_tensor * cur;
  4254. cur = llm_build_kqv(ctx, model, hparams, kv, graph, wo, wo_b,
  4255. q_cur, kq_mask, kq_pos, n_ctx, n_tokens, n_kv, kq_scale, cb, il);
  4256. cb(cur, "kqv_out", il);
  4257. return cur;
  4258. }
  4259. struct llm_build_context {
  4260. const llama_model & model;
  4261. const llama_context & lctx;
  4262. const llama_hparams & hparams;
  4263. const llama_cparams & cparams;
  4264. const llama_batch & batch;
  4265. const llama_kv_cache & kv_self;
  4266. const int64_t n_embd;
  4267. const int64_t n_layer;
  4268. const int64_t n_rot;
  4269. const int64_t n_ctx; // user-specified context size (can be different from n_ctx_train)
  4270. const int64_t n_head;
  4271. const int64_t n_head_kv;
  4272. const int64_t n_embd_head_k;
  4273. const int64_t n_embd_k_gqa;
  4274. const int64_t n_embd_head_v;
  4275. const int64_t n_embd_v_gqa;
  4276. const int64_t n_expert;
  4277. const int64_t n_expert_used;
  4278. const float freq_base;
  4279. const float freq_scale;
  4280. const float ext_factor;
  4281. const float attn_factor;
  4282. const float beta_fast;
  4283. const float beta_slow;
  4284. const float norm_eps;
  4285. const float norm_rms_eps;
  4286. const int32_t n_tokens;
  4287. const int32_t n_kv; // size of KV cache to consider (n_kv <= n_ctx)
  4288. const int32_t kv_head; // index of where we store new KV data in the cache
  4289. const int32_t n_orig_ctx;
  4290. const enum llama_pooling_type pooling_type;
  4291. const enum llama_rope_type rope_type;
  4292. const llm_build_cb & cb;
  4293. std::vector<uint8_t> & buf_compute_meta;
  4294. struct ggml_context * ctx0 = nullptr;
  4295. // TODO: consider making the entire interface noexcept
  4296. llm_build_context(
  4297. llama_context & lctx,
  4298. const llama_batch & batch,
  4299. const llm_build_cb & cb,
  4300. bool worst_case) :
  4301. model (lctx.model),
  4302. lctx (lctx),
  4303. hparams (model.hparams),
  4304. cparams (lctx.cparams),
  4305. batch (batch),
  4306. kv_self (lctx.kv_self),
  4307. n_embd (hparams.n_embd),
  4308. n_layer (hparams.n_layer),
  4309. n_rot (hparams.n_rot),
  4310. n_ctx (cparams.n_ctx),
  4311. n_head (hparams.n_head),
  4312. n_head_kv (hparams.n_head_kv),
  4313. n_embd_head_k (hparams.n_embd_head_k),
  4314. n_embd_k_gqa (hparams.n_embd_k_gqa()),
  4315. n_embd_head_v (hparams.n_embd_head_v),
  4316. n_embd_v_gqa (hparams.n_embd_v_gqa()),
  4317. n_expert (hparams.n_expert),
  4318. n_expert_used (hparams.n_expert_used),
  4319. freq_base (cparams.rope_freq_base),
  4320. freq_scale (cparams.rope_freq_scale),
  4321. ext_factor (cparams.yarn_ext_factor),
  4322. attn_factor (cparams.yarn_attn_factor),
  4323. beta_fast (cparams.yarn_beta_fast),
  4324. beta_slow (cparams.yarn_beta_slow),
  4325. norm_eps (hparams.f_norm_eps),
  4326. norm_rms_eps (hparams.f_norm_rms_eps),
  4327. n_tokens (batch.n_tokens),
  4328. n_kv (worst_case ? n_ctx : kv_self.n),
  4329. kv_head (worst_case ? n_ctx - n_tokens : kv_self.head),
  4330. n_orig_ctx (cparams.n_yarn_orig_ctx),
  4331. pooling_type (cparams.do_pooling ? hparams.pooling_type : LLAMA_POOLING_TYPE_NONE),
  4332. rope_type (hparams.rope_type),
  4333. cb (cb),
  4334. buf_compute_meta (lctx.buf_compute_meta) {
  4335. // all initializations should be done in init()
  4336. }
  4337. void init() {
  4338. struct ggml_init_params params = {
  4339. /*.mem_size =*/ buf_compute_meta.size(),
  4340. /*.mem_buffer =*/ buf_compute_meta.data(),
  4341. /*.no_alloc =*/ true,
  4342. };
  4343. ctx0 = ggml_init(params);
  4344. }
  4345. void free() {
  4346. if (ctx0) {
  4347. ggml_free(ctx0);
  4348. ctx0 = nullptr;
  4349. }
  4350. }
  4351. struct ggml_cgraph * build_k_shift() {
  4352. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4353. for (int il = 0; il < n_layer; ++il) {
  4354. struct ggml_tensor * tmp =
  4355. // we rotate only the first n_rot dimensions
  4356. ggml_rope_custom_inplace(ctx0,
  4357. ggml_view_3d(ctx0, kv_self.k_l[il],
  4358. n_embd_head_k, n_head_kv, n_ctx,
  4359. ggml_row_size(kv_self.k_l[il]->type, n_embd_head_k),
  4360. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  4361. 0),
  4362. lctx.inp_K_shift, n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  4363. ext_factor, attn_factor, beta_fast, beta_slow);
  4364. cb(tmp, "K_shifted", il);
  4365. ggml_build_forward_expand(gf, tmp);
  4366. }
  4367. return gf;
  4368. }
  4369. struct ggml_cgraph * build_defrag(const std::vector<uint32_t> & ids) {
  4370. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4371. for (uint32_t i = 0; i < ids.size(); ++i) {
  4372. const uint32_t id = ids[i];
  4373. if (i == id || id == ids.size()) {
  4374. continue;
  4375. }
  4376. uint32_t nm = 1;
  4377. while (i + nm < ids.size() && ids[i + nm] == id + nm) {
  4378. nm++;
  4379. }
  4380. for (int il = 0; il < n_layer; ++il) {
  4381. ggml_tensor * view_k_src = ggml_view_2d(ctx0, kv_self.k_l[il],
  4382. n_embd_k_gqa, nm,
  4383. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  4384. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*i));
  4385. ggml_tensor * view_k_dst = ggml_view_2d(ctx0, kv_self.k_l[il],
  4386. n_embd_k_gqa, nm,
  4387. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa),
  4388. ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*id));
  4389. ggml_tensor * view_v_src = ggml_view_2d(ctx0, kv_self.v_l[il],
  4390. nm, n_embd_v_gqa,
  4391. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  4392. ggml_row_size(kv_self.v_l[il]->type, i));
  4393. ggml_tensor * view_v_dst = ggml_view_2d(ctx0, kv_self.v_l[il],
  4394. nm, n_embd_v_gqa,
  4395. ggml_row_size(kv_self.v_l[il]->type, kv_self.size),
  4396. ggml_row_size(kv_self.v_l[il]->type, id));
  4397. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_k_src, view_k_dst));
  4398. ggml_build_forward_expand(gf, ggml_cpy(ctx0, view_v_src, view_v_dst));
  4399. }
  4400. i += nm - 1;
  4401. }
  4402. //LLAMA_LOG_INFO("gf->n_nodes = %d\n", gf->n_nodes);
  4403. return gf;
  4404. }
  4405. struct ggml_cgraph * build_llama() {
  4406. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4407. const int64_t n_embd_head = hparams.n_embd_head_v;
  4408. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4409. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4410. struct ggml_tensor * cur;
  4411. struct ggml_tensor * inpL;
  4412. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4413. cb(inpL, "inp_embd", -1);
  4414. // inp_pos - contains the positions
  4415. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4416. cb(inp_pos, "inp_pos", -1);
  4417. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4418. 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);
  4419. cb(KQ_mask, "KQ_mask", -1);
  4420. for (int il = 0; il < n_layer; ++il) {
  4421. struct ggml_tensor * inpSA = inpL;
  4422. // norm
  4423. cur = llm_build_norm(ctx0, inpL, hparams,
  4424. model.layers[il].attn_norm, NULL,
  4425. LLM_NORM_RMS, cb, il);
  4426. cb(cur, "attn_norm", il);
  4427. // self-attention
  4428. {
  4429. // compute Q and K and RoPE them
  4430. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4431. cb(Qcur, "Qcur", il);
  4432. if (model.layers[il].bq) {
  4433. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  4434. cb(Qcur, "Qcur", il);
  4435. }
  4436. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4437. cb(Kcur, "Kcur", il);
  4438. if (model.layers[il].bk) {
  4439. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  4440. cb(Kcur, "Kcur", il);
  4441. }
  4442. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4443. cb(Vcur, "Vcur", il);
  4444. if (model.layers[il].bv) {
  4445. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  4446. cb(Vcur, "Vcur", il);
  4447. }
  4448. Qcur = ggml_rope_custom(
  4449. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  4450. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  4451. ext_factor, attn_factor, beta_fast, beta_slow
  4452. );
  4453. cb(Qcur, "Qcur", il);
  4454. Kcur = ggml_rope_custom(
  4455. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  4456. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  4457. ext_factor, attn_factor, beta_fast, beta_slow
  4458. );
  4459. cb(Kcur, "Kcur", il);
  4460. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4461. model.layers[il].wo, model.layers[il].bo,
  4462. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4463. cb(cur, "kqv_out", il);
  4464. }
  4465. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4466. cb(ffn_inp, "ffn_inp", il);
  4467. // feed-forward network
  4468. if (model.layers[il].ffn_gate_inp == nullptr) {
  4469. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4470. model.layers[il].ffn_norm, NULL,
  4471. LLM_NORM_RMS, cb, il);
  4472. cb(cur, "ffn_norm", il);
  4473. cur = llm_build_ffn(ctx0, cur,
  4474. model.layers[il].ffn_up, NULL,
  4475. model.layers[il].ffn_gate, NULL,
  4476. model.layers[il].ffn_down, NULL,
  4477. NULL,
  4478. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4479. cb(cur, "ffn_out", il);
  4480. } else {
  4481. // MoE branch
  4482. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4483. model.layers[il].ffn_norm, NULL,
  4484. LLM_NORM_RMS, cb, il);
  4485. cb(cur, "ffn_norm", il);
  4486. ggml_tensor * logits = ggml_mul_mat(ctx0, model.layers[il].ffn_gate_inp, cur); // [n_tokens, num_experts]
  4487. cb(logits, "ffn_moe_logits", il);
  4488. ggml_tensor * probs = ggml_soft_max(ctx0, logits); // [n_tokens, num_experts]
  4489. cb(probs, "ffn_moe_probs", il);
  4490. // select experts
  4491. ggml_tensor * selected_experts = ggml_top_k(ctx0, probs, n_expert_used); // [n_tokens, num_experts_per_tok]
  4492. cb(selected_experts->src[0], "ffn_moe_argsort", il);
  4493. ggml_tensor * weights = ggml_get_rows(ctx0,
  4494. ggml_reshape_3d(ctx0, probs, 1, n_expert, n_tokens), selected_experts);
  4495. cb(weights, "ffn_moe_weights", il);
  4496. weights = ggml_reshape_2d(ctx0, weights, n_expert_used, n_tokens); // [n_tokens, num_experts_per_tok]
  4497. ggml_tensor * weights_sum = ggml_sum_rows(ctx0, weights);
  4498. cb(weights_sum, "ffn_moe_weights_sum", il);
  4499. weights = ggml_div(ctx0, weights, weights_sum); // [n_tokens, num_experts_per_tok]
  4500. cb(weights, "ffn_moe_weights_norm", il);
  4501. // compute expert outputs
  4502. ggml_tensor * moe_out = nullptr;
  4503. for (int i = 0; i < n_expert_used; ++i) {
  4504. ggml_tensor * cur_expert;
  4505. ggml_tensor * cur_up = ggml_mul_mat_id(ctx0, model.layers[il].ffn_up_exp, n_expert, selected_experts, i, cur);
  4506. cb(cur_up, "ffn_moe_up", il);
  4507. ggml_tensor * cur_gate = ggml_mul_mat_id(ctx0, model.layers[il].ffn_gate_exp, n_expert, selected_experts, i, cur);
  4508. cb(cur_gate, "ffn_moe_gate", il);
  4509. cur_gate = ggml_silu(ctx0, cur_gate);
  4510. cb(cur_gate, "ffn_moe_silu", il);
  4511. cur_expert = ggml_mul(ctx0, cur_up, cur_gate); // [n_tokens, n_embd]
  4512. cb(cur_expert, "ffn_moe_gate_par", il);
  4513. cur_expert = ggml_mul_mat_id(ctx0, model.layers[il].ffn_down_exp, n_expert, selected_experts, i, cur_expert); // [n_tokens, n_embd]
  4514. cb(cur_expert, "ffn_moe_down", il);
  4515. cur_expert = ggml_mul(ctx0, cur_expert,
  4516. ggml_view_2d(ctx0, weights, 1, n_tokens, weights->nb[1], i*weights->nb[0]));
  4517. cb(cur_expert, "ffn_moe_weighted", il);
  4518. if (i == 0) {
  4519. moe_out = cur_expert;
  4520. } else {
  4521. moe_out = ggml_add(ctx0, moe_out, cur_expert);
  4522. cb(moe_out, "ffn_moe_out", il);
  4523. }
  4524. }
  4525. cur = moe_out;
  4526. }
  4527. cur = ggml_add(ctx0, cur, ffn_inp);
  4528. cb(cur, "l_out", il);
  4529. // input for next layer
  4530. inpL = cur;
  4531. }
  4532. cur = inpL;
  4533. cur = llm_build_norm(ctx0, cur, hparams,
  4534. model.output_norm, NULL,
  4535. LLM_NORM_RMS, cb, -1);
  4536. cb(cur, "result_norm", -1);
  4537. // lm_head
  4538. cur = ggml_mul_mat(ctx0, model.output, cur);
  4539. cb(cur, "result_output", -1);
  4540. ggml_build_forward_expand(gf, cur);
  4541. return gf;
  4542. }
  4543. struct ggml_cgraph * build_baichuan() {
  4544. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4545. const int64_t n_embd_head = hparams.n_embd_head_v;
  4546. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4547. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4548. struct ggml_tensor * cur;
  4549. struct ggml_tensor * inpL;
  4550. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4551. cb(inpL, "inp_embd", -1);
  4552. // inp_pos - contains the positions
  4553. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4554. cb(inp_pos, "inp_pos", -1);
  4555. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4556. 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);
  4557. cb(KQ_mask, "KQ_mask", -1);
  4558. // positions of the tokens in the KV cache
  4559. struct ggml_tensor * KQ_pos = ggml_view_1d(ctx0, lctx.inp_KQ_pos, n_kv, 0);
  4560. cb(KQ_pos, "KQ_pos", -1);
  4561. for (int il = 0; il < n_layer; ++il) {
  4562. struct ggml_tensor * inpSA = inpL;
  4563. cur = llm_build_norm(ctx0, inpL, hparams,
  4564. model.layers[il].attn_norm, NULL,
  4565. LLM_NORM_RMS, cb, il);
  4566. cb(cur, "attn_norm", il);
  4567. // self-attention
  4568. {
  4569. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4570. cb(Qcur, "Qcur", il);
  4571. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4572. cb(Kcur, "Kcur", il);
  4573. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4574. cb(Vcur, "Vcur", il);
  4575. switch (model.type) {
  4576. case MODEL_7B:
  4577. Qcur = ggml_rope_custom(
  4578. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  4579. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  4580. ext_factor, attn_factor, beta_fast, beta_slow
  4581. );
  4582. Kcur = ggml_rope_custom(
  4583. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  4584. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  4585. ext_factor, attn_factor, beta_fast, beta_slow
  4586. );
  4587. break;
  4588. case MODEL_13B:
  4589. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd/n_head, n_head, n_tokens);
  4590. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd/n_head, n_head, n_tokens);
  4591. break;
  4592. default:
  4593. GGML_ASSERT(false);
  4594. }
  4595. cb(Qcur, "Qcur", il);
  4596. cb(Kcur, "Kcur", il);
  4597. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4598. model.layers[il].wo, NULL,
  4599. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4600. cb(cur, "kqv_out", il);
  4601. }
  4602. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4603. cb(ffn_inp, "ffn_inp", il);
  4604. // feed-forward network
  4605. {
  4606. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4607. model.layers[il].ffn_norm, NULL,
  4608. LLM_NORM_RMS, cb, il);
  4609. cb(cur, "ffn_norm", il);
  4610. cur = llm_build_ffn(ctx0, cur,
  4611. model.layers[il].ffn_up, NULL,
  4612. model.layers[il].ffn_gate, NULL,
  4613. model.layers[il].ffn_down, NULL,
  4614. NULL,
  4615. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4616. cb(cur, "ffn_out", il);
  4617. }
  4618. cur = ggml_add(ctx0, cur, ffn_inp);
  4619. cb(cur, "l_out", il);
  4620. // input for next layer
  4621. inpL = cur;
  4622. }
  4623. cur = inpL;
  4624. cur = llm_build_norm(ctx0, cur, hparams,
  4625. model.output_norm, NULL,
  4626. LLM_NORM_RMS, cb, -1);
  4627. cb(cur, "result_norm", -1);
  4628. // lm_head
  4629. cur = ggml_mul_mat(ctx0, model.output, cur);
  4630. cb(cur, "result_output", -1);
  4631. ggml_build_forward_expand(gf, cur);
  4632. return gf;
  4633. }
  4634. struct ggml_cgraph * build_falcon() {
  4635. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4636. const int64_t n_embd_head = hparams.n_embd_head_v;
  4637. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4638. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4639. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4640. struct ggml_tensor * cur;
  4641. struct ggml_tensor * inpL;
  4642. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4643. cb(inpL, "inp_embd", -1);
  4644. // inp_pos - contains the positions
  4645. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4646. cb(inp_pos, "inp_pos", -1);
  4647. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4648. 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);
  4649. cb(KQ_mask, "KQ_mask", -1);
  4650. for (int il = 0; il < n_layer; ++il) {
  4651. struct ggml_tensor * attn_norm;
  4652. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  4653. model.layers[il].attn_norm,
  4654. model.layers[il].attn_norm_b,
  4655. LLM_NORM, cb, il);
  4656. cb(attn_norm, "attn_norm", il);
  4657. // self-attention
  4658. {
  4659. if (model.layers[il].attn_norm_2) {
  4660. // Falcon-40B
  4661. cur = llm_build_norm(ctx0, inpL, hparams,
  4662. model.layers[il].attn_norm_2,
  4663. model.layers[il].attn_norm_2_b,
  4664. LLM_NORM, cb, il);
  4665. cb(cur, "attn_norm_2", il);
  4666. } else {
  4667. cur = attn_norm;
  4668. }
  4669. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4670. cb(cur, "wqkv", il);
  4671. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4672. 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)));
  4673. 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)));
  4674. cb(Qcur, "Qcur", il);
  4675. cb(Kcur, "Kcur", il);
  4676. cb(Vcur, "Vcur", il);
  4677. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4678. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  4679. // using mode = 2 for neox mode
  4680. Qcur = ggml_rope_custom(
  4681. ctx0, Qcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  4682. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4683. );
  4684. cb(Qcur, "Qcur", il);
  4685. Kcur = ggml_rope_custom(
  4686. ctx0, Kcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  4687. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4688. );
  4689. cb(Kcur, "Kcur", il);
  4690. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4691. model.layers[il].wo, NULL,
  4692. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4693. cb(cur, "kqv_out", il);
  4694. }
  4695. struct ggml_tensor * ffn_inp = cur;
  4696. // feed forward
  4697. {
  4698. cur = llm_build_ffn(ctx0, attn_norm, // !! use the attn norm, not the result
  4699. model.layers[il].ffn_up, NULL,
  4700. NULL, NULL,
  4701. model.layers[il].ffn_down, NULL,
  4702. NULL,
  4703. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4704. cb(cur, "ffn_out", il);
  4705. }
  4706. cur = ggml_add(ctx0, cur, ffn_inp);
  4707. cb(cur, "l_out", il);
  4708. cur = ggml_add(ctx0, cur, inpL);
  4709. cb(cur, "l_out", il);
  4710. // input for next layer
  4711. inpL = cur;
  4712. }
  4713. cur = inpL;
  4714. // norm
  4715. cur = llm_build_norm(ctx0, cur, hparams,
  4716. model.output_norm,
  4717. model.output_norm_b,
  4718. LLM_NORM, cb, -1);
  4719. cb(cur, "result_norm", -1);
  4720. cur = ggml_mul_mat(ctx0, model.output, cur);
  4721. cb(cur, "result_output", -1);
  4722. ggml_build_forward_expand(gf, cur);
  4723. return gf;
  4724. }
  4725. struct ggml_cgraph * build_starcoder() {
  4726. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4727. const int64_t n_embd_head = hparams.n_embd_head_v;
  4728. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4729. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4730. struct ggml_tensor * cur;
  4731. struct ggml_tensor * pos;
  4732. struct ggml_tensor * inpL;
  4733. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4734. cb(inpL, "inp_embd", -1);
  4735. // inp_pos - contains the positions
  4736. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4737. cb(inp_pos, "inp_pos", -1);
  4738. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4739. 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);
  4740. cb(KQ_mask, "KQ_mask", -1);
  4741. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  4742. cb(pos, "pos_embd", -1);
  4743. inpL = ggml_add(ctx0, inpL, pos);
  4744. cb(inpL, "inpL", -1);
  4745. for (int il = 0; il < n_layer; ++il) {
  4746. cur = llm_build_norm(ctx0, inpL, hparams,
  4747. model.layers[il].attn_norm,
  4748. model.layers[il].attn_norm_b,
  4749. LLM_NORM, cb, il);
  4750. cb(cur, "attn_norm", il);
  4751. // self-attention
  4752. {
  4753. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4754. cb(cur, "wqkv", il);
  4755. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4756. cb(cur, "bqkv", il);
  4757. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4758. 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)));
  4759. 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)));
  4760. cb(Qcur, "Qcur", il);
  4761. cb(Kcur, "Kcur", il);
  4762. cb(Vcur, "Vcur", il);
  4763. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4764. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4765. model.layers[il].wo, model.layers[il].bo,
  4766. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4767. cb(cur, "kqv_out", il);
  4768. }
  4769. // add the input
  4770. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  4771. cb(ffn_inp, "ffn_inp", il);
  4772. // FF
  4773. {
  4774. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4775. model.layers[il].ffn_norm,
  4776. model.layers[il].ffn_norm_b,
  4777. LLM_NORM, cb, il);
  4778. cb(cur, "ffn_norm", il);
  4779. cur = llm_build_ffn(ctx0, cur,
  4780. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  4781. NULL, NULL,
  4782. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  4783. NULL,
  4784. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4785. cb(cur, "ffn_out", il);
  4786. }
  4787. inpL = ggml_add(ctx0, cur, ffn_inp);
  4788. cb(inpL, "l_out", il);
  4789. }
  4790. cur = llm_build_norm(ctx0, inpL, hparams,
  4791. model.output_norm,
  4792. model.output_norm_b,
  4793. LLM_NORM, cb, -1);
  4794. cb(cur, "result_norm", -1);
  4795. cur = ggml_mul_mat(ctx0, model.output, cur);
  4796. cb(cur, "result_output", -1);
  4797. ggml_build_forward_expand(gf, cur);
  4798. return gf;
  4799. }
  4800. struct ggml_cgraph * build_persimmon() {
  4801. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4802. const int64_t n_embd_head = hparams.n_embd_head_v;
  4803. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4804. GGML_ASSERT(n_embd_head/2 == hparams.n_rot);
  4805. struct ggml_tensor * cur;
  4806. struct ggml_tensor * inpL;
  4807. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4808. cb(inpL, "inp_embd", -1);
  4809. // inp_pos - contains the positions
  4810. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4811. cb(inp_pos, "inp_pos", -1);
  4812. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4813. 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);
  4814. cb(KQ_mask, "KQ_mask", -1);
  4815. for (int il = 0; il < n_layer; ++il) {
  4816. struct ggml_tensor * residual = inpL;
  4817. cur = llm_build_norm(ctx0, inpL, hparams,
  4818. model.layers[il].attn_norm,
  4819. model.layers[il].attn_norm_b,
  4820. LLM_NORM, cb, il);
  4821. cb(cur, "attn_norm", il);
  4822. // self attention
  4823. {
  4824. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4825. cb(cur, "wqkv", il);
  4826. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4827. cb(cur, "bqkv", il);
  4828. // split qkv
  4829. GGML_ASSERT(n_head_kv == n_head);
  4830. struct ggml_tensor * tmpqkv = ggml_reshape_4d(ctx0, cur, n_embd_head, 3, n_head, n_tokens);
  4831. cb(tmpqkv, "tmpqkv", il);
  4832. struct ggml_tensor * tmpqkv_perm = ggml_cont(ctx0, ggml_permute(ctx0, tmpqkv, 0, 3, 1, 2));
  4833. cb(tmpqkv_perm, "tmpqkv", il);
  4834. struct ggml_tensor * tmpq = ggml_view_3d(
  4835. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  4836. ggml_element_size(tmpqkv_perm) * n_embd_head,
  4837. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  4838. 0
  4839. );
  4840. cb(tmpq, "tmpq", il);
  4841. struct ggml_tensor * tmpk = ggml_view_3d(
  4842. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  4843. ggml_element_size(tmpqkv_perm) * n_embd_head,
  4844. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  4845. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens
  4846. );
  4847. cb(tmpk, "tmpk", il);
  4848. // Q/K Layernorm
  4849. tmpq = llm_build_norm(ctx0, tmpq, hparams,
  4850. model.layers[il].attn_q_norm,
  4851. model.layers[il].attn_q_norm_b,
  4852. LLM_NORM, cb, il);
  4853. cb(tmpq, "tmpq", il);
  4854. tmpk = llm_build_norm(ctx0, tmpk, hparams,
  4855. model.layers[il].attn_k_norm,
  4856. model.layers[il].attn_k_norm_b,
  4857. LLM_NORM, cb, il);
  4858. cb(tmpk, "tmpk", il);
  4859. // RoPE the first n_rot of q/k, pass the other half, and concat.
  4860. struct ggml_tensor * qrot = ggml_view_3d(
  4861. ctx0, tmpq, n_rot, n_head, n_tokens,
  4862. ggml_element_size(tmpq) * n_embd_head,
  4863. ggml_element_size(tmpq) * n_embd_head * n_head,
  4864. 0
  4865. );
  4866. cb(qrot, "qrot", il);
  4867. struct ggml_tensor * krot = ggml_view_3d(
  4868. ctx0, tmpk, n_rot, n_head, n_tokens,
  4869. ggml_element_size(tmpk) * n_embd_head,
  4870. ggml_element_size(tmpk) * n_embd_head * n_head,
  4871. 0
  4872. );
  4873. cb(krot, "krot", il);
  4874. // get the second half of tmpq, e.g tmpq[n_rot:, :, :]
  4875. struct ggml_tensor * qpass = ggml_view_3d(
  4876. ctx0, tmpq, n_rot, n_head, n_tokens,
  4877. ggml_element_size(tmpq) * n_embd_head,
  4878. ggml_element_size(tmpq) * n_embd_head * n_head,
  4879. ggml_element_size(tmpq) * n_rot
  4880. );
  4881. cb(qpass, "qpass", il);
  4882. struct ggml_tensor * kpass = ggml_view_3d(
  4883. ctx0, tmpk, n_rot, n_head, n_tokens,
  4884. ggml_element_size(tmpk) * n_embd_head,
  4885. ggml_element_size(tmpk) * n_embd_head * n_head,
  4886. ggml_element_size(tmpk) * n_rot
  4887. );
  4888. cb(kpass, "kpass", il);
  4889. struct ggml_tensor * qrotated = ggml_rope_custom(
  4890. ctx0, qrot, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  4891. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4892. );
  4893. cb(qrotated, "qrotated", il);
  4894. struct ggml_tensor * krotated = ggml_rope_custom(
  4895. ctx0, krot, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  4896. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4897. );
  4898. cb(krotated, "krotated", il);
  4899. // ggml currently only supports concatenation on dim=2
  4900. // so we need to permute qrot, qpass, concat, then permute back.
  4901. qrotated = ggml_cont(ctx0, ggml_permute(ctx0, qrotated, 2, 1, 0, 3));
  4902. cb(qrotated, "qrotated", il);
  4903. krotated = ggml_cont(ctx0, ggml_permute(ctx0, krotated, 2, 1, 0, 3));
  4904. cb(krotated, "krotated", il);
  4905. qpass = ggml_cont(ctx0, ggml_permute(ctx0, qpass, 2, 1, 0, 3));
  4906. cb(qpass, "qpass", il);
  4907. kpass = ggml_cont(ctx0, ggml_permute(ctx0, kpass, 2, 1, 0, 3));
  4908. cb(kpass, "kpass", il);
  4909. struct ggml_tensor * Qcur = ggml_concat(ctx0, qrotated, qpass);
  4910. cb(Qcur, "Qcur", il);
  4911. struct ggml_tensor * Kcur = ggml_concat(ctx0, krotated, kpass);
  4912. cb(Kcur, "Kcur", il);
  4913. struct ggml_tensor * Q = ggml_cont(ctx0, ggml_permute(ctx0, Qcur, 2, 1, 0, 3));
  4914. cb(Q, "Q", il);
  4915. Kcur = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 2, 1, 0, 3));
  4916. cb(Kcur, "Kcur", il);
  4917. struct ggml_tensor * Vcur = ggml_view_3d(
  4918. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  4919. ggml_element_size(tmpqkv_perm) * n_embd_head,
  4920. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  4921. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens * 2
  4922. );
  4923. cb(Vcur, "Vcur", il);
  4924. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4925. model.layers[il].wo, model.layers[il].bo,
  4926. Kcur, Vcur, Q, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4927. cb(cur, "kqv_out", il);
  4928. }
  4929. struct ggml_tensor * ffn_inp = ggml_add(ctx0, residual, cur);
  4930. cb(ffn_inp, "ffn_inp", il);
  4931. // feed-forward network
  4932. {
  4933. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4934. model.layers[il].ffn_norm,
  4935. model.layers[il].ffn_norm_b,
  4936. LLM_NORM, cb, il);
  4937. cb(cur, "ffn_norm", il);
  4938. cur = llm_build_ffn(ctx0, cur,
  4939. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  4940. NULL, NULL,
  4941. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  4942. NULL,
  4943. LLM_FFN_RELU_SQR, LLM_FFN_SEQ, cb, il);
  4944. cb(cur, "ffn_out", il);
  4945. }
  4946. cur = ggml_add(ctx0, cur, ffn_inp);
  4947. cb(cur, "l_out", il);
  4948. inpL = cur;
  4949. }
  4950. cur = inpL;
  4951. cur = llm_build_norm(ctx0, cur, hparams,
  4952. model.output_norm,
  4953. model.output_norm_b,
  4954. LLM_NORM, cb, -1);
  4955. cb(cur, "result_norm", -1);
  4956. cur = ggml_mul_mat(ctx0, model.output, cur);
  4957. cb(cur, "result_output", -1);
  4958. ggml_build_forward_expand(gf, cur);
  4959. return gf;
  4960. }
  4961. struct ggml_cgraph * build_refact() {
  4962. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4963. const int64_t n_embd_head = hparams.n_embd_head_v;
  4964. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4965. struct ggml_tensor * cur;
  4966. struct ggml_tensor * inpL;
  4967. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4968. cb(inpL, "inp_embd", -1);
  4969. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4970. 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);
  4971. cb(KQ_mask, "KQ_mask", -1);
  4972. // positions of the tokens in the KV cache
  4973. struct ggml_tensor * KQ_pos = ggml_view_1d(ctx0, lctx.inp_KQ_pos, n_kv, 0);
  4974. cb(KQ_pos, "KQ_pos", -1);
  4975. for (int il = 0; il < n_layer; ++il) {
  4976. struct ggml_tensor * inpSA = inpL;
  4977. cur = llm_build_norm(ctx0, inpL, hparams,
  4978. model.layers[il].attn_norm, NULL,
  4979. LLM_NORM_RMS, cb, il);
  4980. cb(cur, "attn_norm", il);
  4981. // self-attention
  4982. {
  4983. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4984. cb(Qcur, "Qcur", il);
  4985. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4986. cb(Kcur, "Kcur", il);
  4987. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4988. cb(Vcur, "Vcur", il);
  4989. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  4990. cb(Kcur, "Kcur", il);
  4991. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4992. cb(Qcur, "Qcur", il);
  4993. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4994. model.layers[il].wo, NULL,
  4995. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4996. cb(cur, "kqv_out", il);
  4997. }
  4998. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4999. cb(ffn_inp, "ffn_inp", il);
  5000. // feed-forward network
  5001. {
  5002. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5003. model.layers[il].ffn_norm, NULL,
  5004. LLM_NORM_RMS, cb, il);
  5005. cb(cur, "ffn_norm", il);
  5006. cur = llm_build_ffn(ctx0, cur,
  5007. model.layers[il].ffn_up, NULL,
  5008. model.layers[il].ffn_gate, NULL,
  5009. model.layers[il].ffn_down, NULL,
  5010. NULL,
  5011. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5012. cb(cur, "ffn_out", il);
  5013. }
  5014. cur = ggml_add(ctx0, cur, ffn_inp);
  5015. cb(cur, "l_out", il);
  5016. // input for next layer
  5017. inpL = cur;
  5018. }
  5019. cur = inpL;
  5020. cur = llm_build_norm(ctx0, cur, hparams,
  5021. model.output_norm, NULL,
  5022. LLM_NORM_RMS, cb, -1);
  5023. cb(cur, "result_norm", -1);
  5024. // lm_head
  5025. cur = ggml_mul_mat(ctx0, model.output, cur);
  5026. cb(cur, "result_output", -1);
  5027. ggml_build_forward_expand(gf, cur);
  5028. return gf;
  5029. }
  5030. struct ggml_cgraph * build_bert() {
  5031. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5032. const int64_t n_embd_head = hparams.n_embd_head_v;
  5033. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5034. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5035. struct ggml_tensor * cur;
  5036. struct ggml_tensor * inpL;
  5037. // get input vectors with right size
  5038. const size_t stride1 = n_tokens * ggml_type_size(lctx.inp_tokens->type);
  5039. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5040. struct ggml_tensor * inp_mean = ggml_view_2d(ctx0, lctx.inp_mean, n_tokens, n_tokens, stride1, 0);
  5041. struct ggml_tensor * inp_cls = ggml_view_1d(ctx0, lctx.inp_cls, n_tokens, 0);
  5042. // construct input embeddings (token, type, position)
  5043. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5044. // token types are hardcoded to zero ("Sentence A")
  5045. struct ggml_tensor * type_row0 = ggml_view_1d(ctx0, model.type_embd, n_embd, 0);
  5046. inpL = ggml_add(ctx0, inpL, type_row0);
  5047. if (model.arch == LLM_ARCH_BERT) {
  5048. inpL = ggml_add(ctx0, ggml_get_rows(ctx0, model.pos_embd, inp_pos), inpL);
  5049. }
  5050. cb(inpL, "inp_embd", -1);
  5051. // embed layer norm
  5052. inpL = llm_build_norm(ctx0, inpL, hparams, model.tok_norm, model.tok_norm_b, LLM_NORM, cb, -1);
  5053. cb(inpL, "inp_norm", -1);
  5054. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5055. 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);
  5056. cb(KQ_mask, "KQ_mask", -1); // [n_kv, n_tokens]
  5057. // iterate layers
  5058. for (int il = 0; il < n_layer; ++il) {
  5059. struct ggml_tensor * cur = inpL;
  5060. // self-attention
  5061. if (model.arch == LLM_ARCH_BERT) {
  5062. struct ggml_tensor * Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, cur), model.layers[il].bq);
  5063. cb(Qcur, "Qcur", il);
  5064. struct ggml_tensor * Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, cur), model.layers[il].bk);
  5065. cb(Kcur, "Kcur", il);
  5066. struct ggml_tensor * Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, cur), model.layers[il].bv);
  5067. cb(Vcur, "Vcur", il);
  5068. // seems like we just need to do this for Q?
  5069. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5070. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5071. model.layers[il].wo, model.layers[il].bo,
  5072. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5073. cb(cur, "kqv_out", il);
  5074. } else {
  5075. // compute Q and K and RoPE them
  5076. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5077. cb(cur, "wqkv", il);
  5078. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5079. 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)));
  5080. 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)));
  5081. cb(Qcur, "Qcur", il);
  5082. cb(Kcur, "Kcur", il);
  5083. cb(Vcur, "Vcur", il);
  5084. Qcur = ggml_rope_custom(
  5085. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5086. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5087. ext_factor, attn_factor, beta_fast, beta_slow
  5088. );
  5089. cb(Qcur, "Qcur", il);
  5090. Kcur = ggml_rope_custom(
  5091. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5092. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5093. ext_factor, attn_factor, beta_fast, beta_slow
  5094. );
  5095. cb(Kcur, "Kcur", il);
  5096. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5097. model.layers[il].wo, model.layers[il].bo,
  5098. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5099. cb(cur, "kqv_out", il);
  5100. }
  5101. // re-add the layer input
  5102. cur = ggml_add(ctx0, cur, inpL);
  5103. // attention layer norm
  5104. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].attn_out_norm, model.layers[il].attn_out_norm_b, LLM_NORM, cb, il);
  5105. struct ggml_tensor * ffn_inp = cur;
  5106. cb(ffn_inp, "ffn_inp", il);
  5107. // feed-forward network
  5108. if (model.arch == LLM_ARCH_BERT) {
  5109. cur = llm_build_ffn(ctx0, cur,
  5110. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5111. NULL, NULL,
  5112. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5113. NULL,
  5114. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5115. } else {
  5116. cur = llm_build_ffn(ctx0, cur,
  5117. model.layers[il].ffn_up, NULL,
  5118. model.layers[il].ffn_gate, NULL,
  5119. model.layers[il].ffn_down, NULL,
  5120. NULL,
  5121. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5122. }
  5123. cb(cur, "ffn_out", il);
  5124. // attentions bypass the intermediate layer
  5125. cur = ggml_add(ctx0, cur, ffn_inp);
  5126. // output layer norm
  5127. cur = llm_build_norm(ctx0, cur, hparams, model.layers[il].layer_out_norm, model.layers[il].layer_out_norm_b, LLM_NORM, cb, il);
  5128. // input for next layer
  5129. inpL = cur;
  5130. }
  5131. // final output
  5132. cur = inpL;
  5133. // pooling layer
  5134. if (pooling_type == LLAMA_POOLING_TYPE_MEAN) {
  5135. cur = ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, cur)), inp_mean);
  5136. } else if (pooling_type == LLAMA_POOLING_TYPE_CLS) {
  5137. cur = ggml_get_rows(ctx0, cur, inp_cls);
  5138. } else {
  5139. GGML_ASSERT(pooling_type == LLAMA_POOLING_TYPE_NONE && "Invalid pooling type");
  5140. }
  5141. cb(cur, "result_embd", -1);
  5142. ggml_build_forward_expand(gf, cur);
  5143. return gf;
  5144. }
  5145. struct ggml_cgraph * build_bloom() {
  5146. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5147. const int64_t n_embd_head = hparams.n_embd_head_v;
  5148. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5149. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5150. struct ggml_tensor * cur;
  5151. struct ggml_tensor * inpL;
  5152. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5153. cb(inpL, "inp_embd", -1);
  5154. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5155. 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);
  5156. cb(KQ_mask, "KQ_mask", -1);
  5157. // positions of the tokens in the KV cache
  5158. struct ggml_tensor * KQ_pos = ggml_view_1d(ctx0, lctx.inp_KQ_pos, n_kv, 0);
  5159. cb(KQ_pos, "KQ_pos", -1);
  5160. inpL = llm_build_norm(ctx0, inpL, hparams,
  5161. model.tok_norm,
  5162. model.tok_norm_b,
  5163. LLM_NORM, cb, -1);
  5164. cb(inpL, "inp_norm", -1);
  5165. for (int il = 0; il < n_layer; ++il) {
  5166. cur = llm_build_norm(ctx0, inpL, hparams,
  5167. model.layers[il].attn_norm,
  5168. model.layers[il].attn_norm_b,
  5169. LLM_NORM, cb, il);
  5170. cb(cur, "attn_norm", il);
  5171. // self-attention
  5172. {
  5173. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5174. cb(cur, "wqkv", il);
  5175. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5176. cb(cur, "bqkv", il);
  5177. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5178. 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)));
  5179. 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)));
  5180. cb(Qcur, "Qcur", il);
  5181. cb(Kcur, "Kcur", il);
  5182. cb(Vcur, "Vcur", il);
  5183. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5184. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5185. model.layers[il].wo, model.layers[il].bo,
  5186. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5187. cb(cur, "kqv_out", il);
  5188. }
  5189. // Add the input
  5190. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5191. cb(ffn_inp, "ffn_inp", il);
  5192. // FF
  5193. {
  5194. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5195. model.layers[il].ffn_norm,
  5196. model.layers[il].ffn_norm_b,
  5197. LLM_NORM, cb, il);
  5198. cb(cur, "ffn_norm", il);
  5199. cur = llm_build_ffn(ctx0, cur,
  5200. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5201. NULL, NULL,
  5202. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5203. NULL,
  5204. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5205. cb(cur, "ffn_out", il);
  5206. }
  5207. inpL = ggml_add(ctx0, cur, ffn_inp);
  5208. cb(inpL, "l_out", il);
  5209. }
  5210. cur = llm_build_norm(ctx0, inpL, hparams,
  5211. model.output_norm,
  5212. model.output_norm_b,
  5213. LLM_NORM, cb, -1);
  5214. cb(cur, "result_norm", -1);
  5215. cur = ggml_mul_mat(ctx0, model.output, cur);
  5216. cb(cur, "result_output", -1);
  5217. ggml_build_forward_expand(gf, cur);
  5218. return gf;
  5219. }
  5220. struct ggml_cgraph * build_mpt() {
  5221. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5222. const int64_t n_embd_head = hparams.n_embd_head_v;
  5223. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5224. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5225. struct ggml_tensor * cur;
  5226. struct ggml_tensor * inpL;
  5227. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5228. cb(inpL, "inp_embd", -1);
  5229. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5230. 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);
  5231. cb(KQ_mask, "KQ_mask", -1);
  5232. // positions of the tokens in the KV cache
  5233. struct ggml_tensor * KQ_pos = ggml_view_1d(ctx0, lctx.inp_KQ_pos, n_kv, 0);
  5234. cb(KQ_pos, "KQ_pos", -1);
  5235. for (int il = 0; il < n_layer; ++il) {
  5236. struct ggml_tensor * attn_norm;
  5237. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  5238. model.layers[il].attn_norm,
  5239. model.layers[il].attn_norm_b,
  5240. LLM_NORM, cb, il);
  5241. cb(attn_norm, "attn_norm", il);
  5242. // self-attention
  5243. {
  5244. cur = attn_norm;
  5245. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5246. cb(cur, "wqkv", il);
  5247. if (model.layers[il].bqkv){
  5248. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5249. cb(cur, "bqkv", il);
  5250. }
  5251. if (hparams.f_clamp_kqv > 0.0f) {
  5252. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  5253. cb(cur, "wqkv_clamped", il);
  5254. }
  5255. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5256. 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)));
  5257. 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)));
  5258. cb(Qcur, "Qcur", il);
  5259. cb(Kcur, "Kcur", il);
  5260. cb(Vcur, "Vcur", il);
  5261. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5262. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5263. model.layers[il].wo, model.layers[il].bo,
  5264. Kcur, Vcur, Qcur, KQ_mask, KQ_pos, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5265. cb(cur, "kqv_out", il);
  5266. }
  5267. // Add the input
  5268. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5269. cb(ffn_inp, "ffn_inp", il);
  5270. // feed forward
  5271. {
  5272. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5273. model.layers[il].ffn_norm,
  5274. model.layers[il].ffn_norm_b,
  5275. LLM_NORM, cb, il);
  5276. cb(cur, "ffn_norm", il);
  5277. cur = llm_build_ffn(ctx0, cur,
  5278. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5279. NULL, NULL,
  5280. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5281. model.layers[il].ffn_act,
  5282. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5283. cb(cur, "ffn_out", il);
  5284. }
  5285. cur = ggml_add(ctx0, cur, ffn_inp);
  5286. cb(cur, "l_out", il);
  5287. // input for next layer
  5288. inpL = cur;
  5289. }
  5290. cur = inpL;
  5291. cur = llm_build_norm(ctx0, cur, hparams,
  5292. model.output_norm,
  5293. model.output_norm_b,
  5294. LLM_NORM, cb, -1);
  5295. cb(cur, "result_norm", -1);
  5296. cur = ggml_mul_mat(ctx0, model.output, cur);
  5297. cb(cur, "result_output", -1);
  5298. ggml_build_forward_expand(gf, cur);
  5299. return gf;
  5300. }
  5301. struct ggml_cgraph * build_stablelm() {
  5302. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  5303. const int64_t n_embd_head = hparams.n_embd_head_v;
  5304. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5305. struct ggml_tensor * cur;
  5306. struct ggml_tensor * inpL;
  5307. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5308. cb(inpL, "inp_embd", -1);
  5309. // inp_pos - contains the positions
  5310. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5311. cb(inp_pos, "inp_pos", -1);
  5312. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5313. 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);
  5314. cb(KQ_mask, "KQ_mask", -1);
  5315. for (int il = 0; il < n_layer; ++il) {
  5316. struct ggml_tensor * inpSA = inpL;
  5317. // norm
  5318. cur = llm_build_norm(ctx0, inpL, hparams,
  5319. model.layers[il].attn_norm,
  5320. model.layers[il].attn_norm_b,
  5321. LLM_NORM, cb, il);
  5322. cb(cur, "attn_norm", il);
  5323. // self-attention
  5324. {
  5325. // compute Q and K and RoPE them
  5326. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5327. cb(Qcur, "Qcur", il);
  5328. if (model.layers[il].bq) {
  5329. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5330. cb(Qcur, "Qcur", il);
  5331. }
  5332. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5333. cb(Kcur, "Kcur", il);
  5334. if (model.layers[il].bk) {
  5335. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5336. cb(Kcur, "Kcur", il);
  5337. }
  5338. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5339. cb(Vcur, "Vcur", il);
  5340. if (model.layers[il].bv) {
  5341. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  5342. cb(Vcur, "Vcur", il);
  5343. }
  5344. Qcur = ggml_rope_custom(
  5345. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5346. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5347. ext_factor, attn_factor, beta_fast, beta_slow
  5348. );
  5349. cb(Qcur, "Qcur", il);
  5350. Kcur = ggml_rope_custom(
  5351. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5352. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5353. ext_factor, attn_factor, beta_fast, beta_slow
  5354. );
  5355. cb(Kcur, "Kcur", il);
  5356. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5357. model.layers[il].wo, NULL,
  5358. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5359. cb(cur, "kqv_out", il);
  5360. }
  5361. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5362. cb(ffn_inp, "ffn_inp", il);
  5363. // feed-forward network
  5364. {
  5365. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5366. model.layers[il].ffn_norm,
  5367. model.layers[il].ffn_norm_b,
  5368. LLM_NORM, cb, il);
  5369. cb(cur, "ffn_norm", il);
  5370. cur = llm_build_ffn(ctx0, cur,
  5371. model.layers[il].ffn_up, NULL,
  5372. model.layers[il].ffn_gate, NULL,
  5373. model.layers[il].ffn_down, NULL,
  5374. NULL,
  5375. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5376. cb(cur, "ffn_out", il);
  5377. }
  5378. cur = ggml_add(ctx0, cur, ffn_inp);
  5379. cb(cur, "l_out", il);
  5380. // input for next layer
  5381. inpL = cur;
  5382. }
  5383. cur = inpL;
  5384. cur = llm_build_norm(ctx0, cur, hparams,
  5385. model.output_norm,
  5386. model.output_norm_b,
  5387. LLM_NORM, cb, -1);
  5388. cb(cur, "result_norm", -1);
  5389. // lm_head
  5390. cur = ggml_mul_mat(ctx0, model.output, cur);
  5391. cb(cur, "result_output", -1);
  5392. ggml_build_forward_expand(gf, cur);
  5393. return gf;
  5394. }
  5395. struct ggml_cgraph * build_qwen() {
  5396. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5397. const int64_t n_embd_head = hparams.n_embd_head_v;
  5398. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5399. struct ggml_tensor * cur;
  5400. struct ggml_tensor * inpL;
  5401. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5402. cb(inpL, "inp_embd", -1);
  5403. // inp_pos - contains the positions
  5404. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5405. cb(inp_pos, "inp_pos", -1);
  5406. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5407. 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);
  5408. cb(KQ_mask, "KQ_mask", -1);
  5409. for (int il = 0; il < n_layer; ++il) {
  5410. struct ggml_tensor * inpSA = inpL;
  5411. cur = llm_build_norm(ctx0, inpL, hparams,
  5412. model.layers[il].attn_norm, NULL,
  5413. LLM_NORM_RMS, cb, il);
  5414. cb(cur, "attn_norm", il);
  5415. // self-attention
  5416. {
  5417. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5418. cb(cur, "wqkv", il);
  5419. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5420. cb(cur, "bqkv", il);
  5421. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5422. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  5423. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 2*sizeof(float)*(n_embd)));
  5424. cb(Qcur, "Qcur", il);
  5425. cb(Kcur, "Kcur", il);
  5426. cb(Vcur, "Vcur", il);
  5427. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5428. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  5429. // using mode = 2 for neox mode
  5430. Qcur = ggml_rope_custom(
  5431. ctx0, Qcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5432. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5433. );
  5434. cb(Qcur, "Qcur", il);
  5435. Kcur = ggml_rope_custom(
  5436. ctx0, Kcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5437. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5438. );
  5439. cb(Kcur, "Kcur", il);
  5440. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5441. model.layers[il].wo, NULL,
  5442. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5443. cb(cur, "kqv_out", il);
  5444. }
  5445. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5446. cb(ffn_inp, "ffn_inp", il);
  5447. // feed-forward forward
  5448. {
  5449. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5450. model.layers[il].ffn_norm, NULL,
  5451. LLM_NORM_RMS, cb, il);
  5452. cb(cur, "ffn_norm", il);
  5453. cur = llm_build_ffn(ctx0, cur,
  5454. model.layers[il].ffn_up, NULL,
  5455. model.layers[il].ffn_gate, NULL,
  5456. model.layers[il].ffn_down, NULL,
  5457. NULL,
  5458. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5459. cb(cur, "ffn_out", il);
  5460. }
  5461. cur = ggml_add(ctx0, cur, ffn_inp);
  5462. cb(cur, "l_out", il);
  5463. // input for next layer
  5464. inpL = cur;
  5465. }
  5466. cur = inpL;
  5467. cur = llm_build_norm(ctx0, cur, hparams,
  5468. model.output_norm, NULL,
  5469. LLM_NORM_RMS, cb, -1);
  5470. cb(cur, "result_norm", -1);
  5471. // lm_head
  5472. cur = ggml_mul_mat(ctx0, model.output, cur);
  5473. cb(cur, "result_output", -1);
  5474. ggml_build_forward_expand(gf, cur);
  5475. return gf;
  5476. }
  5477. struct ggml_cgraph * build_qwen2() {
  5478. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5479. const int64_t n_embd_head = hparams.n_embd_head_v;
  5480. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5481. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5482. struct ggml_tensor * cur;
  5483. struct ggml_tensor * inpL;
  5484. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5485. cb(inpL, "inp_embd", -1);
  5486. // inp_pos - contains the positions
  5487. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5488. cb(inp_pos, "inp_pos", -1);
  5489. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5490. 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);
  5491. cb(KQ_mask, "KQ_mask", -1);
  5492. for (int il = 0; il < n_layer; ++il) {
  5493. struct ggml_tensor * inpSA = inpL;
  5494. // norm
  5495. cur = llm_build_norm(ctx0, inpL, hparams,
  5496. model.layers[il].attn_norm, NULL,
  5497. LLM_NORM_RMS, cb, il);
  5498. cb(cur, "attn_norm", il);
  5499. // self-attention
  5500. {
  5501. // compute Q and K and RoPE them
  5502. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5503. cb(Qcur, "Qcur", il);
  5504. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5505. cb(Qcur, "Qcur", il);
  5506. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5507. cb(Kcur, "Kcur", il);
  5508. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5509. cb(Kcur, "Kcur", il);
  5510. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5511. cb(Vcur, "Vcur", il);
  5512. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  5513. cb(Vcur, "Vcur", il);
  5514. // these nodes are added to the graph together so that they are not reordered
  5515. // by doing so, the number of splits in the graph is reduced
  5516. ggml_build_forward_expand(gf, Qcur);
  5517. ggml_build_forward_expand(gf, Kcur);
  5518. ggml_build_forward_expand(gf, Vcur);
  5519. Qcur = ggml_rope_custom(
  5520. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5521. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5522. ext_factor, attn_factor, beta_fast, beta_slow
  5523. );
  5524. cb(Qcur, "Qcur", il);
  5525. Kcur = ggml_rope_custom(
  5526. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5527. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5528. ext_factor, attn_factor, beta_fast, beta_slow
  5529. );
  5530. cb(Kcur, "Kcur", il);
  5531. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5532. model.layers[il].wo, model.layers[il].bo,
  5533. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5534. cb(cur, "kqv_out", il);
  5535. }
  5536. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5537. cb(ffn_inp, "ffn_inp", il);
  5538. // feed-forward network
  5539. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5540. model.layers[il].ffn_norm, NULL,
  5541. LLM_NORM_RMS, cb, il);
  5542. cb(cur, "ffn_norm", il);
  5543. cur = llm_build_ffn(ctx0, cur,
  5544. model.layers[il].ffn_up, NULL,
  5545. model.layers[il].ffn_gate, NULL,
  5546. model.layers[il].ffn_down, NULL,
  5547. NULL,
  5548. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5549. cb(cur, "ffn_out", il);
  5550. cur = ggml_add(ctx0, cur, ffn_inp);
  5551. cb(cur, "l_out", il);
  5552. // input for next layer
  5553. inpL = cur;
  5554. }
  5555. cur = inpL;
  5556. cur = llm_build_norm(ctx0, cur, hparams,
  5557. model.output_norm, NULL,
  5558. LLM_NORM_RMS, cb, -1);
  5559. cb(cur, "result_norm", -1);
  5560. // lm_head
  5561. cur = ggml_mul_mat(ctx0, model.output, cur);
  5562. cb(cur, "result_output", -1);
  5563. ggml_build_forward_expand(gf, cur);
  5564. return gf;
  5565. }
  5566. struct ggml_cgraph * build_phi2() {
  5567. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5568. const int64_t n_embd_head = hparams.n_embd_head_v;
  5569. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5570. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5571. struct ggml_tensor * cur;
  5572. struct ggml_tensor * attn_norm_output;
  5573. struct ggml_tensor * ffn_output;
  5574. struct ggml_tensor * inpL;
  5575. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5576. cb(inpL, "inp_embd", -1);
  5577. // inp_pos - contains the positions
  5578. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5579. cb(inp_pos, "inp_pos", -1);
  5580. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5581. 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);
  5582. cb(KQ_mask, "KQ_mask", -1);
  5583. for (int il = 0; il < n_layer; ++il) {
  5584. attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  5585. model.layers[il].attn_norm,
  5586. model.layers[il].attn_norm_b,
  5587. LLM_NORM, cb, il);
  5588. cb(attn_norm_output, "attn_norm", il);
  5589. // self-attention
  5590. {
  5591. struct ggml_tensor * Qcur = nullptr;
  5592. struct ggml_tensor * Kcur = nullptr;
  5593. struct ggml_tensor * Vcur = nullptr;
  5594. if (model.layers[il].wqkv) {
  5595. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, attn_norm_output);
  5596. cb(cur, "wqkv", il);
  5597. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5598. cb(cur, "bqkv", il);
  5599. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5600. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  5601. 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)));
  5602. } else {
  5603. Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  5604. Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  5605. Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  5606. }
  5607. cb(Qcur, "Qcur", il);
  5608. cb(Kcur, "Kcur", il);
  5609. cb(Vcur, "Vcur", il);
  5610. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5611. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  5612. Qcur = ggml_rope_custom(
  5613. ctx0, Qcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5614. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5615. );
  5616. cb(Qcur, "Qcur", il);
  5617. // with phi2, we scale the Q to avoid precision issues
  5618. // ref: https://github.com/ml-explore/mlx-examples/blob/08e862336ade809bc37d1035f94b359e7d1a5152/phi2/phi2.py#L64-L66
  5619. Qcur = ggml_scale(ctx0, Qcur, 1.0f/sqrtf(float(n_embd_head)));
  5620. cb(Qcur, "Qcur", il);
  5621. Kcur = ggml_rope_custom(
  5622. ctx0, Kcur, inp_pos, n_rot, rope_type, 0, n_orig_ctx,
  5623. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  5624. );
  5625. cb(Kcur, "Kcur", il);
  5626. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5627. model.layers[il].wo, model.layers[il].bo,
  5628. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  5629. cb(cur, "kqv_out", il);
  5630. }
  5631. // FF
  5632. {
  5633. ffn_output = llm_build_ffn(ctx0, attn_norm_output,
  5634. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5635. NULL, NULL,
  5636. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5637. NULL,
  5638. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5639. cb(ffn_output, "ffn_out", il);
  5640. }
  5641. cur = ggml_add(ctx0, cur, ffn_output);
  5642. cb(cur, "l_out", il);
  5643. cur = ggml_add(ctx0, cur, inpL);
  5644. cb(cur, "l_out", il);
  5645. inpL = cur;
  5646. }
  5647. cur = llm_build_norm(ctx0, inpL, hparams,
  5648. model.output_norm,
  5649. model.output_norm_b,
  5650. LLM_NORM, cb, -1);
  5651. cb(cur, "result_norm", -1);
  5652. cur = ggml_mul_mat(ctx0, model.output, cur);
  5653. cb(cur, "result_output_no_bias", -1);
  5654. cur = ggml_add(ctx0, cur, model.output_b);
  5655. cb(cur, "result_output", -1);
  5656. ggml_build_forward_expand(gf, cur);
  5657. return gf;
  5658. }
  5659. struct ggml_cgraph * build_plamo() {
  5660. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  5661. const int64_t n_embd_head = hparams.n_embd_head_v;
  5662. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5663. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5664. struct ggml_tensor * cur;
  5665. struct ggml_tensor * inpL;
  5666. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5667. cb(inpL, "inp_embd", -1);
  5668. // inp_pos - contains the positions
  5669. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5670. cb(inp_pos, "inp_pos", -1);
  5671. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5672. 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);
  5673. cb(KQ_mask, "KQ_mask", -1);
  5674. for (int il = 0; il < n_layer; ++il) {
  5675. // norm
  5676. cur = llm_build_norm(ctx0, inpL, hparams,
  5677. model.layers[il].attn_norm, NULL,
  5678. LLM_NORM_RMS, cb, il);
  5679. cb(cur, "attn_norm", il);
  5680. struct ggml_tensor * attention_norm = cur;
  5681. // self-attention
  5682. {
  5683. // compute Q and K and RoPE them
  5684. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5685. cb(Qcur, "Qcur", il);
  5686. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5687. cb(Kcur, "Kcur", il);
  5688. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5689. cb(Vcur, "Vcur", il);
  5690. Qcur = ggml_rope_custom(
  5691. ctx0, ggml_reshape_3d(ctx0, Qcur, n_rot, n_head, n_tokens), inp_pos,
  5692. n_embd_head, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5693. ext_factor, attn_factor, beta_fast, beta_slow);
  5694. cb(Qcur, "Qcur", il);
  5695. Kcur = ggml_rope_custom(
  5696. ctx0, ggml_reshape_3d(ctx0, Kcur, n_rot, n_head_kv, n_tokens), inp_pos,
  5697. n_embd_head, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5698. ext_factor, attn_factor, beta_fast, beta_slow);
  5699. cb(Kcur, "Kcur", il);
  5700. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5701. model.layers[il].wo, NULL,
  5702. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5703. cb(cur, "kqv_out", il);
  5704. }
  5705. struct ggml_tensor * sa_out = cur;
  5706. cur = attention_norm;
  5707. // feed-forward network
  5708. {
  5709. cur = llm_build_ffn(ctx0, cur,
  5710. model.layers[il].ffn_up, NULL,
  5711. model.layers[il].ffn_gate, NULL,
  5712. model.layers[il].ffn_down, NULL,
  5713. NULL,
  5714. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5715. cb(cur, "ffn_out", il);
  5716. }
  5717. cur = ggml_add(ctx0, cur, sa_out);
  5718. cb(cur, "l_out", il);
  5719. cur = ggml_add(ctx0, cur, inpL);
  5720. cb(cur, "l_out", il);
  5721. // input for next layer
  5722. inpL = cur;
  5723. }
  5724. cur = inpL;
  5725. cur = llm_build_norm(ctx0, cur, hparams,
  5726. model.output_norm, NULL,
  5727. LLM_NORM_RMS, cb, -1);
  5728. cb(cur, "result_norm", -1);
  5729. // lm_head
  5730. cur = ggml_mul_mat(ctx0, model.output, cur);
  5731. cb(cur, "result_output", -1);
  5732. ggml_build_forward_expand(gf, cur);
  5733. return gf;
  5734. }
  5735. struct ggml_cgraph * build_gpt2() {
  5736. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5737. const int64_t n_embd_head = hparams.n_embd_head_v;
  5738. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5739. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5740. struct ggml_tensor * cur;
  5741. struct ggml_tensor * pos;
  5742. struct ggml_tensor * inpL;
  5743. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5744. cb(inpL, "inp_embd", -1);
  5745. // inp_pos - contains the positions
  5746. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5747. cb(inp_pos, "inp_pos", -1);
  5748. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5749. 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);
  5750. cb(KQ_mask, "KQ_mask", -1);
  5751. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  5752. cb(pos, "pos_embd", -1);
  5753. inpL = ggml_add(ctx0, inpL, pos);
  5754. cb(inpL, "inpL", -1);
  5755. for (int il = 0; il < n_layer; ++il) {
  5756. cur = llm_build_norm(ctx0, inpL, hparams,
  5757. model.layers[il].attn_norm,
  5758. model.layers[il].attn_norm_b,
  5759. LLM_NORM, cb, il);
  5760. cb(cur, "attn_norm", il);
  5761. // self-attention
  5762. {
  5763. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5764. cb(cur, "wqkv", il);
  5765. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5766. cb(cur, "bqkv", il);
  5767. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5768. 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)));
  5769. 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)));
  5770. cb(Qcur, "Qcur", il);
  5771. cb(Kcur, "Kcur", il);
  5772. cb(Vcur, "Vcur", il);
  5773. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5774. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5775. model.layers[il].wo, model.layers[il].bo,
  5776. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5777. cb(cur, "kqv_out", il);
  5778. }
  5779. // add the input
  5780. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5781. cb(ffn_inp, "ffn_inp", il);
  5782. // FF
  5783. {
  5784. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5785. model.layers[il].ffn_norm,
  5786. model.layers[il].ffn_norm_b,
  5787. LLM_NORM, cb, il);
  5788. cb(cur, "ffn_norm", il);
  5789. cur = llm_build_ffn(ctx0, cur,
  5790. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5791. NULL, NULL,
  5792. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5793. NULL,
  5794. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5795. cb(cur, "ffn_out", il);
  5796. }
  5797. inpL = ggml_add(ctx0, cur, ffn_inp);
  5798. cb(inpL, "l_out", il);
  5799. }
  5800. cur = llm_build_norm(ctx0, inpL, hparams,
  5801. model.output_norm,
  5802. model.output_norm_b,
  5803. LLM_NORM, cb, -1);
  5804. cb(cur, "result_norm", -1);
  5805. cur = ggml_mul_mat(ctx0, model.output, cur);
  5806. cb(cur, "result_output", -1);
  5807. ggml_build_forward_expand(gf, cur);
  5808. return gf;
  5809. }
  5810. struct ggml_cgraph * build_codeshell() {
  5811. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5812. const int64_t n_embd_head = hparams.n_embd_head_v;
  5813. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5814. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5815. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5816. struct ggml_tensor * cur;
  5817. struct ggml_tensor * inpL;
  5818. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5819. cb(inpL, "inp_embd", -1);
  5820. // inp_pos - contains the positions
  5821. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5822. cb(inp_pos, "inp_pos", -1);
  5823. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5824. 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);
  5825. cb(KQ_mask, "KQ_mask", -1);
  5826. for (int il = 0; il < n_layer; ++il) {
  5827. cur = llm_build_norm(ctx0, inpL, hparams,
  5828. model.layers[il].attn_norm,
  5829. model.layers[il].attn_norm_b,
  5830. LLM_NORM, cb, il);
  5831. cb(cur, "attn_norm", il);
  5832. // self-attention
  5833. {
  5834. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5835. cb(cur, "wqkv", il);
  5836. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5837. cb(cur, "bqkv", il);
  5838. struct ggml_tensor * tmpq = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5839. 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)));
  5840. 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)));
  5841. cb(tmpq, "tmpq", il);
  5842. cb(tmpk, "tmpk", il);
  5843. cb(Vcur, "Vcur", il);
  5844. struct ggml_tensor * Qcur = ggml_rope_custom(
  5845. ctx0, ggml_reshape_3d(ctx0, tmpq, n_embd_head, n_head, n_tokens), inp_pos,
  5846. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5847. ext_factor, attn_factor, beta_fast, beta_slow
  5848. );
  5849. cb(Qcur, "Qcur", il);
  5850. struct ggml_tensor * Kcur = ggml_rope_custom(
  5851. ctx0, ggml_reshape_3d(ctx0, tmpk, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5852. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5853. ext_factor, attn_factor, beta_fast, beta_slow
  5854. );
  5855. cb(Kcur, "Kcur", il);
  5856. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5857. model.layers[il].wo, model.layers[il].bo,
  5858. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5859. cb(cur, "kqv_out", il);
  5860. }
  5861. // add the input
  5862. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5863. cb(ffn_inp, "ffn_inp", il);
  5864. // FF
  5865. {
  5866. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5867. model.layers[il].ffn_norm,
  5868. model.layers[il].ffn_norm_b,
  5869. LLM_NORM, cb, il);
  5870. cb(cur, "ffn_norm", il);
  5871. cur = llm_build_ffn(ctx0, cur,
  5872. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5873. NULL, NULL,
  5874. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5875. NULL,
  5876. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5877. cb(cur, "ffn_out", il);
  5878. }
  5879. inpL = ggml_add(ctx0, cur, ffn_inp);
  5880. cb(inpL, "l_out", il);
  5881. }
  5882. cur = llm_build_norm(ctx0, inpL, hparams,
  5883. model.output_norm,
  5884. model.output_norm_b,
  5885. LLM_NORM, cb, -1);
  5886. cb(cur, "result_norm", -1);
  5887. cur = ggml_mul_mat(ctx0, model.output, cur);
  5888. cb(cur, "result_output", -1);
  5889. ggml_build_forward_expand(gf, cur);
  5890. return gf;
  5891. }
  5892. struct ggml_cgraph * build_orion() {
  5893. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5894. const int64_t n_embd_head = hparams.n_embd_head_v;
  5895. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5896. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5897. struct ggml_tensor * cur;
  5898. struct ggml_tensor * inpL;
  5899. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5900. cb(inpL, "inp_embd", -1);
  5901. // inp_pos - contains the positions
  5902. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5903. cb(inp_pos, "inp_pos", -1);
  5904. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5905. 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);
  5906. cb(KQ_mask, "KQ_mask", -1);
  5907. for (int il = 0; il < n_layer; ++il) {
  5908. struct ggml_tensor * inpSA = inpL;
  5909. // norm
  5910. cur = llm_build_norm(ctx0, inpL, hparams,
  5911. model.layers[il].attn_norm, model.layers[il].attn_norm_b,
  5912. LLM_NORM, cb, il);
  5913. cb(cur, "attn_norm", il);
  5914. // self-attention
  5915. {
  5916. // compute Q and K and RoPE them
  5917. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5918. cb(Qcur, "Qcur", il);
  5919. // if (model.layers[il].bq) {
  5920. // Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  5921. // cb(Qcur, "Qcur", il);
  5922. // }
  5923. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5924. cb(Kcur, "Kcur", il);
  5925. // if (model.layers[il].bk) {
  5926. // Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  5927. // cb(Kcur, "Kcur", il);
  5928. // }
  5929. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5930. cb(Vcur, "Vcur", il);
  5931. // if (model.layers[il].bv) {
  5932. // Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  5933. // cb(Vcur, "Vcur", il);
  5934. // }
  5935. Qcur = ggml_rope_custom(
  5936. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  5937. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5938. ext_factor, attn_factor, beta_fast, beta_slow
  5939. );
  5940. cb(Qcur, "Qcur", il);
  5941. Kcur = ggml_rope_custom(
  5942. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5943. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  5944. ext_factor, attn_factor, beta_fast, beta_slow
  5945. );
  5946. cb(Kcur, "Kcur", il);
  5947. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5948. model.layers[il].wo, NULL,
  5949. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5950. cb(cur, "kqv_out", il);
  5951. }
  5952. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  5953. cb(ffn_inp, "ffn_inp", il);
  5954. // feed-forward network
  5955. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5956. model.layers[il].ffn_norm, model.layers[il].ffn_norm_b,
  5957. LLM_NORM, cb, il);
  5958. cb(cur, "ffn_norm", il);
  5959. cur = llm_build_ffn(ctx0, cur,
  5960. model.layers[il].ffn_up, NULL,
  5961. model.layers[il].ffn_gate, NULL,
  5962. model.layers[il].ffn_down, NULL,
  5963. NULL,
  5964. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5965. cb(cur, "ffn_out", il);
  5966. cur = ggml_add(ctx0, cur, ffn_inp);
  5967. cb(cur, "l_out", il);
  5968. // input for next layer
  5969. inpL = cur;
  5970. }
  5971. cur = inpL;
  5972. cur = llm_build_norm(ctx0, cur, hparams,
  5973. model.output_norm, model.output_norm_b,
  5974. LLM_NORM, cb, -1);
  5975. cb(cur, "result_norm", -1);
  5976. // lm_head
  5977. cur = ggml_mul_mat(ctx0, model.output, cur);
  5978. cb(cur, "result_output", -1);
  5979. ggml_build_forward_expand(gf, cur);
  5980. return gf;
  5981. }
  5982. struct ggml_cgraph * build_internlm2() {
  5983. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5984. const int64_t n_embd_head = hparams.n_embd_head_v;
  5985. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5986. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5987. struct ggml_tensor * cur;
  5988. struct ggml_tensor * inpL;
  5989. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5990. cb(inpL, "inp_embd", -1);
  5991. // inp_pos - contains the positions
  5992. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5993. cb(inp_pos, "inp_pos", -1);
  5994. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5995. 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);
  5996. cb(KQ_mask, "KQ_mask", -1);
  5997. for (int il = 0; il < n_layer; ++il) {
  5998. struct ggml_tensor * inpSA = inpL;
  5999. // norm
  6000. cur = llm_build_norm(ctx0, inpL, hparams,
  6001. model.layers[il].attn_norm, NULL,
  6002. LLM_NORM_RMS, cb, il);
  6003. cb(cur, "attn_norm", il);
  6004. // self-attention
  6005. {
  6006. // compute Q and K and RoPE them
  6007. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6008. cb(Qcur, "Qcur", il);
  6009. if (model.layers[il].bq) {
  6010. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6011. cb(Qcur, "Qcur", il);
  6012. }
  6013. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6014. cb(Kcur, "Kcur", il);
  6015. if (model.layers[il].bk) {
  6016. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6017. cb(Kcur, "Kcur", il);
  6018. }
  6019. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6020. cb(Vcur, "Vcur", il);
  6021. if (model.layers[il].bv) {
  6022. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6023. cb(Vcur, "Vcur", il);
  6024. }
  6025. Qcur = ggml_rope_custom(
  6026. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6027. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6028. ext_factor, attn_factor, beta_fast, beta_slow
  6029. );
  6030. cb(Qcur, "Qcur", il);
  6031. Kcur = ggml_rope_custom(
  6032. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6033. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6034. ext_factor, attn_factor, beta_fast, beta_slow
  6035. );
  6036. cb(Kcur, "Kcur", il);
  6037. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6038. model.layers[il].wo, model.layers[il].bo,
  6039. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6040. cb(cur, "kqv_out", il);
  6041. }
  6042. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6043. cb(ffn_inp, "ffn_inp", il);
  6044. // feed-forward network
  6045. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6046. model.layers[il].ffn_norm, NULL,
  6047. LLM_NORM_RMS, cb, il);
  6048. cb(cur, "ffn_norm", il);
  6049. cur = llm_build_ffn(ctx0, cur,
  6050. model.layers[il].ffn_up, NULL,
  6051. model.layers[il].ffn_gate, NULL,
  6052. model.layers[il].ffn_down, NULL,
  6053. NULL,
  6054. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6055. cb(cur, "ffn_out", il);
  6056. cur = ggml_add(ctx0, cur, ffn_inp);
  6057. cb(cur, "l_out", il);
  6058. // input for next layer
  6059. inpL = cur;
  6060. }
  6061. cur = inpL;
  6062. cur = llm_build_norm(ctx0, cur, hparams,
  6063. model.output_norm, NULL,
  6064. LLM_NORM_RMS, cb, -1);
  6065. cb(cur, "result_norm", -1);
  6066. // lm_head
  6067. cur = ggml_mul_mat(ctx0, model.output, cur);
  6068. cb(cur, "result_output", -1);
  6069. ggml_build_forward_expand(gf, cur);
  6070. return gf;
  6071. }
  6072. // ref: https://arxiv.org/abs/2203.03466
  6073. // https://github.com/ggerganov/llama.cpp/issues/5276#issuecomment-1925774738
  6074. // based on the original build_llama() function
  6075. struct ggml_cgraph * build_minicpm() {
  6076. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6077. const int64_t n_embd_head = hparams.n_embd_head_v;
  6078. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  6079. GGML_ASSERT(n_embd_head == hparams.n_rot);
  6080. const int64_t n_embd = hparams.n_embd;
  6081. //TODO: if the model varies, these parameters need to be read from the model
  6082. const int64_t n_embd_base = 256;
  6083. const float scale_embd = 12.0f;
  6084. const float scale_depth = 1.4f;
  6085. struct ggml_tensor * cur;
  6086. struct ggml_tensor * inpL;
  6087. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  6088. cb(inpL, "inp_embd", -1);
  6089. // scale the input embeddings
  6090. inpL = ggml_scale(ctx0, inpL, scale_embd);
  6091. cb(inpL, "inp_scaled", -1);
  6092. // inp_pos - contains the positions
  6093. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  6094. cb(inp_pos, "inp_pos", -1);
  6095. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6096. 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);
  6097. cb(KQ_mask, "KQ_mask", -1);
  6098. for (int il = 0; il < n_layer; ++il) {
  6099. struct ggml_tensor * inpSA = inpL;
  6100. // norm
  6101. cur = llm_build_norm(ctx0, inpL, hparams,
  6102. model.layers[il].attn_norm, NULL,
  6103. LLM_NORM_RMS, cb, il);
  6104. cb(cur, "attn_norm", il);
  6105. // self-attention
  6106. {
  6107. // compute Q and K and RoPE them
  6108. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6109. cb(Qcur, "Qcur", il);
  6110. if (model.layers[il].bq) {
  6111. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  6112. cb(Qcur, "Qcur", il);
  6113. }
  6114. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6115. cb(Kcur, "Kcur", il);
  6116. if (model.layers[il].bk) {
  6117. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  6118. cb(Kcur, "Kcur", il);
  6119. }
  6120. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6121. cb(Vcur, "Vcur", il);
  6122. if (model.layers[il].bv) {
  6123. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  6124. cb(Vcur, "Vcur", il);
  6125. }
  6126. Qcur = ggml_rope_custom(
  6127. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  6128. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6129. ext_factor, attn_factor, beta_fast, beta_slow
  6130. );
  6131. cb(Qcur, "Qcur", il);
  6132. Kcur = ggml_rope_custom(
  6133. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  6134. n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6135. ext_factor, attn_factor, beta_fast, beta_slow
  6136. );
  6137. cb(Kcur, "Kcur", il);
  6138. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6139. model.layers[il].wo, model.layers[il].bo,
  6140. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  6141. cb(cur, "kqv_out", il);
  6142. }
  6143. // scale_res - scale the hidden states for residual connection
  6144. const float scale_res = scale_depth/sqrtf(float(n_layer));
  6145. cur = ggml_scale(ctx0, cur, scale_res);
  6146. cb(cur, "hidden_scaled", -1);
  6147. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  6148. cb(ffn_inp, "ffn_inp", il);
  6149. // feed-forward network
  6150. {
  6151. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  6152. model.layers[il].ffn_norm, NULL,
  6153. LLM_NORM_RMS, cb, il);
  6154. cb(cur, "ffn_norm", il);
  6155. cur = llm_build_ffn(ctx0, cur,
  6156. model.layers[il].ffn_up, NULL,
  6157. model.layers[il].ffn_gate, NULL,
  6158. model.layers[il].ffn_down, NULL,
  6159. NULL,
  6160. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  6161. cb(cur, "ffn_out", il);
  6162. }
  6163. // scale the hidden states for residual connection
  6164. cur = ggml_scale(ctx0, cur, scale_res);
  6165. cb(cur, "hidden_scaled_ffn", -1);
  6166. cur = ggml_add(ctx0, cur, ffn_inp);
  6167. cb(cur, "l_out", il);
  6168. // input for next layer
  6169. inpL = cur;
  6170. }
  6171. cur = inpL;
  6172. cur = llm_build_norm(ctx0, cur, hparams,
  6173. model.output_norm, NULL,
  6174. LLM_NORM_RMS, cb, -1);
  6175. cb(cur, "result_norm", -1);
  6176. // lm_head scaling
  6177. const float scale_lmhead = float(n_embd_base)/float(n_embd);
  6178. cur = ggml_scale(ctx0, cur, scale_lmhead);
  6179. cb(cur, "lmhead_scaling", -1);
  6180. // lm_head
  6181. cur = ggml_mul_mat(ctx0, model.tok_embd, cur);
  6182. cb(cur, "result_output", -1);
  6183. ggml_build_forward_expand(gf, cur);
  6184. return gf;
  6185. }
  6186. struct ggml_cgraph * build_gemma() {
  6187. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  6188. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  6189. struct ggml_tensor * cur;
  6190. struct ggml_tensor * inpL;
  6191. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  6192. cb(inpL, "inp_embd", -1);
  6193. inpL = ggml_scale(ctx0, inpL, sqrtf(n_embd));
  6194. cb(inpL, "inp_scaled", -1);
  6195. // inp_pos - contains the positions
  6196. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  6197. cb(inp_pos, "inp_pos", -1);
  6198. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  6199. 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);
  6200. cb(KQ_mask, "KQ_mask", -1);
  6201. for (int il = 0; il < n_layer; ++il) {
  6202. // norm
  6203. cur = llm_build_norm(ctx0, inpL, hparams,
  6204. model.layers[il].attn_norm, NULL,
  6205. LLM_NORM_RMS, cb, il);
  6206. cb(cur, "attn_norm", il);
  6207. // self-attention
  6208. {
  6209. // compute Q and K and RoPE them
  6210. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  6211. cb(Qcur, "Qcur", il);
  6212. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  6213. cb(Kcur, "Kcur", il);
  6214. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  6215. cb(Vcur, "Vcur", il);
  6216. Qcur = ggml_rope_custom(
  6217. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head_k, n_head, n_tokens), inp_pos,
  6218. n_embd_head_k, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6219. ext_factor, attn_factor, beta_fast, beta_slow);
  6220. cb(Qcur, "Qcur", il);
  6221. Qcur = ggml_scale(ctx0, Qcur, 1.0f / sqrtf(float(n_embd_head_k)));
  6222. cb(Qcur, "Qcur_scaled", il);
  6223. Kcur = ggml_rope_custom(
  6224. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head_k, n_head_kv, n_tokens), inp_pos,
  6225. n_embd_head_k, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  6226. ext_factor, attn_factor, beta_fast, beta_slow);
  6227. cb(Kcur, "Kcur", il);
  6228. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  6229. model.layers[il].wo, NULL,
  6230. Kcur, Vcur, Qcur, KQ_mask, nullptr, n_ctx, n_tokens, kv_head, n_kv, 1.0f, cb, il);
  6231. cb(cur, "kqv_out", il);
  6232. }
  6233. struct ggml_tensor * sa_out = ggml_add(ctx0, cur, inpL);
  6234. cb(sa_out, "sa_out", il);
  6235. cur = llm_build_norm(ctx0, sa_out, hparams,
  6236. model.layers[il].ffn_norm, NULL,
  6237. LLM_NORM_RMS, cb, il);
  6238. cb(cur, "ffn_norm", il);
  6239. // feed-forward network
  6240. {
  6241. cur = llm_build_ffn(ctx0, cur,
  6242. model.layers[il].ffn_up, NULL,
  6243. model.layers[il].ffn_gate, NULL,
  6244. model.layers[il].ffn_down, NULL,
  6245. NULL,
  6246. LLM_FFN_GELU, LLM_FFN_PAR, cb, il);
  6247. cb(cur, "ffn_out", il);
  6248. }
  6249. cur = ggml_add(ctx0, cur, sa_out);
  6250. cb(cur, "l_out", il);
  6251. // input for next layer
  6252. inpL = cur;
  6253. }
  6254. cur = inpL;
  6255. cur = llm_build_norm(ctx0, cur, hparams,
  6256. model.output_norm, NULL,
  6257. LLM_NORM_RMS, cb, -1);
  6258. cb(cur, "result_norm", -1);
  6259. // lm_head
  6260. cur = ggml_mul_mat(ctx0, model.output, cur);
  6261. cb(cur, "result_output", -1);
  6262. ggml_build_forward_expand(gf, cur);
  6263. return gf;
  6264. }
  6265. };
  6266. static struct ggml_cgraph * llama_build_graph_defrag(llama_context & lctx, const std::vector<uint32_t> & ids) {
  6267. llama_batch dummy;
  6268. dummy.n_tokens = 0;
  6269. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  6270. struct llm_build_context llm(lctx, dummy, cb, false);
  6271. llm.init();
  6272. struct ggml_cgraph * result = llm.build_defrag(ids);
  6273. llm.free();
  6274. return result;
  6275. }
  6276. static struct ggml_cgraph * llama_build_graph_k_shift(llama_context & lctx) {
  6277. llama_batch dummy;
  6278. dummy.n_tokens = 0;
  6279. llm_build_cb cb = [&](struct ggml_tensor * , const char * , int ) { };
  6280. struct llm_build_context llm(lctx, dummy, cb, false);
  6281. llm.init();
  6282. struct ggml_cgraph * result = llm.build_k_shift();
  6283. llm.free();
  6284. return result;
  6285. }
  6286. static struct ggml_cgraph * llama_build_graph(
  6287. llama_context & lctx,
  6288. const llama_batch & batch,
  6289. bool worst_case) {
  6290. const auto & model = lctx.model;
  6291. // this callback allows us to apply custom logic to each tensor (e.g. ggml-alloc, offloading, etc.)
  6292. llm_build_cb cb = [&](struct ggml_tensor * cur, const char * name, int il) {
  6293. if (il >= 0) {
  6294. ggml_format_name(cur, "%s-%d", name, il);
  6295. } else {
  6296. ggml_set_name(cur, name);
  6297. }
  6298. if (!lctx.cparams.offload_kqv) {
  6299. if (strcmp(name, "kqv_merged_cont") == 0) {
  6300. // all nodes between the KV store and the attention output are run on the CPU
  6301. ggml_backend_sched_set_node_backend(lctx.sched, cur, lctx.backend_cpu);
  6302. }
  6303. }
  6304. };
  6305. struct ggml_cgraph * result = NULL;
  6306. struct llm_build_context llm(lctx, batch, cb, worst_case);
  6307. llm.init();
  6308. switch (model.arch) {
  6309. case LLM_ARCH_LLAMA:
  6310. {
  6311. result = llm.build_llama();
  6312. } break;
  6313. case LLM_ARCH_BAICHUAN:
  6314. {
  6315. result = llm.build_baichuan();
  6316. } break;
  6317. case LLM_ARCH_FALCON:
  6318. {
  6319. result = llm.build_falcon();
  6320. } break;
  6321. case LLM_ARCH_STARCODER:
  6322. {
  6323. result = llm.build_starcoder();
  6324. } break;
  6325. case LLM_ARCH_PERSIMMON:
  6326. {
  6327. result = llm.build_persimmon();
  6328. } break;
  6329. case LLM_ARCH_REFACT:
  6330. {
  6331. result = llm.build_refact();
  6332. } break;
  6333. case LLM_ARCH_BERT:
  6334. case LLM_ARCH_NOMIC_BERT:
  6335. {
  6336. result = llm.build_bert();
  6337. } break;
  6338. case LLM_ARCH_BLOOM:
  6339. {
  6340. result = llm.build_bloom();
  6341. } break;
  6342. case LLM_ARCH_MPT:
  6343. {
  6344. result = llm.build_mpt();
  6345. } break;
  6346. case LLM_ARCH_STABLELM:
  6347. {
  6348. result = llm.build_stablelm();
  6349. } break;
  6350. case LLM_ARCH_QWEN:
  6351. {
  6352. result = llm.build_qwen();
  6353. } break;
  6354. case LLM_ARCH_QWEN2:
  6355. {
  6356. result = llm.build_qwen2();
  6357. } break;
  6358. case LLM_ARCH_PHI2:
  6359. {
  6360. result = llm.build_phi2();
  6361. } break;
  6362. case LLM_ARCH_PLAMO:
  6363. {
  6364. result = llm.build_plamo();
  6365. } break;
  6366. case LLM_ARCH_GPT2:
  6367. {
  6368. result = llm.build_gpt2();
  6369. } break;
  6370. case LLM_ARCH_CODESHELL:
  6371. {
  6372. result = llm.build_codeshell();
  6373. } break;
  6374. case LLM_ARCH_ORION:
  6375. {
  6376. result = llm.build_orion();
  6377. } break;
  6378. case LLM_ARCH_INTERNLM2:
  6379. {
  6380. result = llm.build_internlm2();
  6381. } break;
  6382. case LLM_ARCH_MINICPM:
  6383. {
  6384. result = llm.build_minicpm();
  6385. } break;
  6386. case LLM_ARCH_GEMMA:
  6387. {
  6388. result = llm.build_gemma();
  6389. } break;
  6390. default:
  6391. GGML_ASSERT(false);
  6392. }
  6393. llm.free();
  6394. return result;
  6395. }
  6396. static void llama_set_k_shift(llama_context & lctx) {
  6397. const auto & cparams = lctx.cparams;
  6398. const int64_t n_ctx = cparams.n_ctx;
  6399. assert(ggml_backend_buffer_is_host(lctx.inp_K_shift->buffer));
  6400. int32_t * data = (int32_t *) lctx.inp_K_shift->data;
  6401. for (int i = 0; i < n_ctx; ++i) {
  6402. data[i] = lctx.kv_self.cells[i].delta;
  6403. }
  6404. }
  6405. static void llama_set_inputs(llama_context & lctx, const llama_batch & batch) {
  6406. //
  6407. // set input data
  6408. //
  6409. const auto & hparams = lctx.model.hparams;
  6410. const auto & cparams = lctx.cparams;
  6411. const auto & kv_self = lctx.kv_self;
  6412. if (batch.token) {
  6413. const int64_t n_tokens = batch.n_tokens;
  6414. ggml_backend_tensor_set(lctx.inp_tokens, batch.token, 0, n_tokens*ggml_element_size(lctx.inp_tokens));
  6415. }
  6416. if (batch.embd) {
  6417. const int64_t n_embd = hparams.n_embd;
  6418. const int64_t n_tokens = batch.n_tokens;
  6419. ggml_backend_tensor_set(lctx.inp_embd, batch.embd, 0, n_tokens*n_embd*ggml_element_size(lctx.inp_embd));
  6420. }
  6421. if (batch.pos) {
  6422. const int64_t n_tokens = batch.n_tokens;
  6423. ggml_backend_tensor_set(lctx.inp_pos, batch.pos, 0, n_tokens*ggml_element_size(lctx.inp_pos));
  6424. }
  6425. {
  6426. const int64_t n_kv = kv_self.n;
  6427. const int64_t n_tokens = batch.n_tokens;
  6428. assert(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  6429. float * data = (float *) lctx.inp_KQ_mask->data;
  6430. for (int h = 0; h < 1; ++h) {
  6431. for (int j = 0; j < n_tokens; ++j) {
  6432. const llama_pos pos = batch.pos[j];
  6433. const llama_seq_id seq_id = batch.seq_id[j][0];
  6434. for (int i = 0; i < n_kv; ++i) {
  6435. float f;
  6436. if (!lctx.kv_self.cells[i].has_seq_id(seq_id) ||
  6437. (hparams.causal_attn && lctx.kv_self.cells[i].pos > pos)) {
  6438. f = -INFINITY;
  6439. } else {
  6440. f = 0;
  6441. }
  6442. data[h*(n_kv*n_tokens) + j*n_kv + i] = f;
  6443. }
  6444. }
  6445. }
  6446. }
  6447. if (hparams.need_kq_pos) {
  6448. const int64_t n_kv = kv_self.n;
  6449. assert(ggml_backend_buffer_is_host(lctx.inp_KQ_pos->buffer));
  6450. float * data = (float *) lctx.inp_KQ_pos->data;
  6451. for (int i = 0; i < n_kv; ++i) {
  6452. data[i] = float(lctx.kv_self.cells[i].pos);
  6453. }
  6454. }
  6455. if (cparams.do_pooling && hparams.pooling_type == LLAMA_POOLING_TYPE_MEAN) {
  6456. const int64_t n_tokens = batch.n_tokens;
  6457. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_mean->buffer));
  6458. float * data = (float *) lctx.inp_mean->data;
  6459. memset(lctx.inp_mean->data, 0, n_tokens * n_tokens * ggml_element_size(lctx.inp_mean));
  6460. std::vector<uint64_t> sum(n_tokens, 0);
  6461. for (int i = 0; i < n_tokens; ++i) {
  6462. const llama_seq_id seq_id = batch.seq_id[i][0];
  6463. sum[seq_id] += 1;
  6464. }
  6465. std::vector<float> div(n_tokens, 0.0f);
  6466. for (int i = 0; i < n_tokens; ++i) {
  6467. const uint64_t s = sum[i];
  6468. if (s > 0) {
  6469. div[i] = 1.0f/float(s);
  6470. }
  6471. }
  6472. for (int i = 0; i < n_tokens; ++i) {
  6473. const llama_seq_id seq_id = batch.seq_id[i][0];
  6474. data[seq_id*n_tokens + i] = div[seq_id];
  6475. }
  6476. }
  6477. if (cparams.do_pooling && hparams.pooling_type == LLAMA_POOLING_TYPE_CLS) {
  6478. const int64_t n_tokens = batch.n_tokens;
  6479. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_cls->buffer));
  6480. uint32_t * data = (uint32_t *) lctx.inp_cls->data;
  6481. for (int i = 0; i < n_tokens; ++i) {
  6482. const llama_seq_id seq_id = batch.seq_id[i][0];
  6483. const llama_pos pos = batch.pos[i];
  6484. if (pos == 0) {
  6485. data[seq_id] = i;
  6486. }
  6487. }
  6488. }
  6489. }
  6490. static void llama_graph_compute(
  6491. llama_context & lctx,
  6492. ggml_cgraph * gf,
  6493. int n_threads) {
  6494. #ifdef GGML_USE_MPI
  6495. const int64_t n_layer = lctx.model.hparams.n_layer;
  6496. ggml_mpi_graph_compute_pre(lctx.ctx_mpi, gf, n_layer);
  6497. #endif
  6498. #ifdef GGML_USE_METAL
  6499. if (ggml_backend_is_metal(lctx.backend_metal)) {
  6500. ggml_backend_metal_set_n_cb(lctx.backend_metal, n_threads);
  6501. }
  6502. #endif
  6503. if (lctx.backend_cpu != nullptr) {
  6504. ggml_backend_cpu_set_n_threads(lctx.backend_cpu, n_threads);
  6505. }
  6506. ggml_backend_sched_graph_compute(lctx.sched, gf);
  6507. // fprintf(stderr, "splits: %d\n", ggml_backend_sched_get_n_splits(lctx.sched));
  6508. #ifdef GGML_USE_MPI
  6509. ggml_mpi_graph_compute_post(lctx.ctx_mpi, gf, n_layer);
  6510. #endif
  6511. }
  6512. // decode a batch of tokens by evaluating the transformer
  6513. //
  6514. // - lctx: llama context
  6515. // - batch: batch to evaluate
  6516. //
  6517. // return 0 on success
  6518. // return positive int on warning
  6519. // return negative int on error
  6520. //
  6521. static int llama_decode_internal(
  6522. llama_context & lctx,
  6523. llama_batch batch) {
  6524. const uint32_t n_tokens = batch.n_tokens;
  6525. if (n_tokens == 0) {
  6526. LLAMA_LOG_ERROR("%s: n_tokens == 0", __func__);
  6527. return -1;
  6528. }
  6529. const auto & model = lctx.model;
  6530. const auto & hparams = model.hparams;
  6531. const auto & cparams = lctx.cparams;
  6532. const auto n_batch = cparams.n_batch;
  6533. GGML_ASSERT(n_tokens <= n_batch);
  6534. int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  6535. GGML_ASSERT((!batch.token && batch.embd) || (batch.token && !batch.embd)); // NOLINT
  6536. const int64_t t_start_us = ggml_time_us();
  6537. #ifdef GGML_USE_MPI
  6538. // TODO: needs fix after #3228
  6539. GGML_ASSERT(false && "not implemented");
  6540. //ggml_mpi_eval_init(lctx.ctx_mpi, &n_tokens, &n_past, &n_threads);
  6541. #endif
  6542. GGML_ASSERT(n_threads > 0);
  6543. auto & kv_self = lctx.kv_self;
  6544. const int64_t n_embd = hparams.n_embd;
  6545. const int64_t n_vocab = hparams.n_vocab;
  6546. // helpers for smoother batch API transition
  6547. // after deprecating the llama_eval calls, these will be removed
  6548. std::vector<llama_pos> pos;
  6549. std::vector<int32_t> n_seq_id;
  6550. std::vector<llama_seq_id *> seq_id_arr;
  6551. std::vector<std::vector<llama_seq_id>> seq_id;
  6552. if (batch.pos == nullptr) {
  6553. pos.resize(n_tokens);
  6554. for (uint32_t i = 0; i < n_tokens; i++) {
  6555. pos[i] = batch.all_pos_0 + i*batch.all_pos_1;
  6556. }
  6557. batch.pos = pos.data();
  6558. }
  6559. if (batch.seq_id == nullptr) {
  6560. n_seq_id.resize(n_tokens);
  6561. seq_id.resize(n_tokens);
  6562. seq_id_arr.resize(n_tokens);
  6563. for (uint32_t i = 0; i < n_tokens; i++) {
  6564. n_seq_id[i] = 1;
  6565. seq_id[i].resize(1);
  6566. seq_id[i][0] = batch.all_seq_id;
  6567. seq_id_arr[i] = seq_id[i].data();
  6568. }
  6569. batch.n_seq_id = n_seq_id.data();
  6570. batch.seq_id = seq_id_arr.data();
  6571. }
  6572. llama_kv_cache_update(&lctx);
  6573. // if we have enough unused cells before the current head ->
  6574. // better to start searching from the beginning of the cache, hoping to fill it
  6575. if (kv_self.head > kv_self.used + 2*n_tokens) {
  6576. kv_self.head = 0;
  6577. }
  6578. if (!llama_kv_cache_find_slot(kv_self, batch)) {
  6579. return 1;
  6580. }
  6581. // a heuristic, to avoid attending the full cache if it is not yet utilized
  6582. // after enough generations, the benefit from this heuristic disappears
  6583. // if we start defragmenting the cache, the benefit from this will be more important
  6584. kv_self.n = std::min((int32_t) cparams.n_ctx, std::max(32, GGML_PAD(llama_kv_cache_cell_max(kv_self), 32)));
  6585. //kv_self.n = llama_kv_cache_cell_max(kv_self);
  6586. //printf("kv_self.n = %5d, kv_self.used = %5d, kv_self.head = %5d\n", kv_self.n, kv_self.used, kv_self.head);
  6587. ggml_backend_sched_reset(lctx.sched);
  6588. ggml_backend_sched_set_eval_callback(lctx.sched, lctx.cparams.cb_eval, lctx.cparams.cb_eval_user_data);
  6589. ggml_cgraph * gf = llama_build_graph(lctx, batch, false);
  6590. // the output is always the last tensor in the graph
  6591. struct ggml_tensor * res = gf->nodes[gf->n_nodes - 1];
  6592. struct ggml_tensor * embeddings = gf->nodes[gf->n_nodes - 2];
  6593. if (strcmp(res->name, "result_output") == 0) {
  6594. // the embeddings could be the second to last tensor, or the third to last tensor
  6595. if (strcmp(embeddings->name, "result_norm") != 0) {
  6596. embeddings = gf->nodes[gf->n_nodes - 3];
  6597. GGML_ASSERT(strcmp(embeddings->name, "result_norm") == 0);
  6598. }
  6599. } else if (strcmp(res->name, "result_embd") == 0) {
  6600. embeddings = res;
  6601. res = nullptr;
  6602. } else {
  6603. GGML_ASSERT(false);
  6604. }
  6605. // 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);
  6606. // for big prompts, if BLAS is enabled, it is better to use only one thread
  6607. // otherwise, the threads are spin-lock waiting for the BLAS calls and are degrading the performance
  6608. // TODO: this is mostly important for Apple Silicon where CBLAS is still performing very well
  6609. // we still need some threads to process all non-mul_mat ops, but not too much to avoid interfering
  6610. // with the BLAS calls. need a better solution
  6611. // MoE Special Case: This logic applies when hparams.n_expert == 0, i.e. the model is NOT an MoE model. When an MoE is
  6612. // being processed then Accelerate/BLAS will not be involved, so capping would limit performance.
  6613. if (n_tokens >= 32 && hparams.n_expert == 0 && ggml_cpu_has_blas() && !ggml_cpu_has_gpublas()) {
  6614. n_threads = std::min(4, n_threads);
  6615. }
  6616. llama_set_inputs(lctx, batch);
  6617. llama_graph_compute(lctx, gf, n_threads);
  6618. // update the kv ring buffer
  6619. {
  6620. kv_self.head += n_tokens;
  6621. // Ensure kv cache head points to a valid index.
  6622. if (kv_self.head >= kv_self.size) {
  6623. kv_self.head = 0;
  6624. }
  6625. }
  6626. // decide if we need to defrag the kv cache
  6627. if (cparams.defrag_thold >= 0.0f) {
  6628. const float fragmentation = kv_self.n >= 128 ? 1.0f - float(kv_self.used + n_tokens)/float(kv_self.n) : 0.0f;
  6629. // queue defragmentation for next llama_kv_cache_update
  6630. if (fragmentation > cparams.defrag_thold) {
  6631. //LLAMA_LOG_INFO("fragmentation: %.2f\n", fragmentation);
  6632. llama_kv_cache_defrag(kv_self);
  6633. }
  6634. }
  6635. #ifdef GGML_PERF
  6636. // print timing information per ggml operation (for debugging purposes)
  6637. // requires GGML_PERF to be defined
  6638. ggml_graph_print(gf);
  6639. #endif
  6640. // plot the computation graph in dot format (for debugging purposes)
  6641. //if (n_past%100 == 0) {
  6642. // ggml_graph_dump_dot(gf, NULL, "llama.dot");
  6643. //}
  6644. // extract logits
  6645. // TODO: do not compute and extract logits if only embeddings are needed
  6646. // need to update the graphs to skip "result_output"
  6647. if (res) {
  6648. auto & logits_out = lctx.logits;
  6649. #ifndef NDEBUG
  6650. auto & logits_valid = lctx.logits_valid;
  6651. logits_valid.clear();
  6652. logits_valid.resize(n_tokens);
  6653. logits_out.clear();
  6654. #endif
  6655. ggml_backend_t res_backend = ggml_backend_sched_get_node_backend(lctx.sched, res);
  6656. GGML_ASSERT(res_backend != nullptr);
  6657. if (batch.logits) {
  6658. logits_out.resize(n_vocab * n_tokens);
  6659. for (uint32_t i = 0; i < n_tokens; i++) {
  6660. if (batch.logits[i] == 0) {
  6661. continue;
  6662. }
  6663. ggml_backend_tensor_get_async(res_backend, res, logits_out.data() + (n_vocab*i), (n_vocab*i)*sizeof(float), n_vocab*sizeof(float));
  6664. #ifndef NDEBUG
  6665. logits_valid[i] = true;
  6666. #endif
  6667. }
  6668. } else if (lctx.logits_all) {
  6669. logits_out.resize(n_vocab * n_tokens);
  6670. ggml_backend_tensor_get_async(res_backend, res, logits_out.data(), 0, n_vocab*n_tokens*sizeof(float));
  6671. #ifndef NDEBUG
  6672. std::fill(logits_valid.begin(), logits_valid.end(), true);
  6673. #endif
  6674. } else {
  6675. logits_out.resize(n_vocab);
  6676. ggml_backend_tensor_get_async(res_backend, res, logits_out.data(), (n_vocab*(n_tokens - 1))*sizeof(float), n_vocab*sizeof(float));
  6677. #ifndef NDEBUG
  6678. logits_valid[0] = true;
  6679. #endif
  6680. }
  6681. ggml_backend_synchronize(res_backend);
  6682. }
  6683. // extract embeddings
  6684. if (!lctx.embedding.empty()) {
  6685. auto & embedding_out = lctx.embedding;
  6686. const int64_t embd_pos = res ? n_embd * (n_tokens-1) : 0;
  6687. const int64_t embd_size = res ? n_embd : n_embd * n_tokens;
  6688. embedding_out.resize(embd_size);
  6689. ggml_backend_t embeddings_backend = ggml_backend_sched_get_node_backend(lctx.sched, embeddings);
  6690. ggml_backend_tensor_get_async(embeddings_backend, embeddings, embedding_out.data(), embd_pos*sizeof(float), embd_size*sizeof(float));
  6691. ggml_backend_synchronize(embeddings_backend);
  6692. }
  6693. // measure the performance only for the single-token evals
  6694. if (n_tokens == 1) {
  6695. lctx.t_eval_us += ggml_time_us() - t_start_us;
  6696. lctx.n_eval++;
  6697. }
  6698. else if (n_tokens > 1) {
  6699. lctx.t_p_eval_us += ggml_time_us() - t_start_us;
  6700. lctx.n_p_eval += n_tokens;
  6701. }
  6702. // get a more accurate load time, upon first eval
  6703. // TODO: fix this
  6704. if (!lctx.has_evaluated_once) {
  6705. lctx.t_load_us = ggml_time_us() - lctx.t_start_us;
  6706. lctx.has_evaluated_once = true;
  6707. }
  6708. return 0;
  6709. }
  6710. // find holes from the beginning of the KV cache and fill them by moving data from the end of the cache
  6711. static void llama_kv_cache_defrag_internal(struct llama_context & lctx) {
  6712. auto & kv_self = lctx.kv_self;
  6713. const auto & hparams = lctx.model.hparams;
  6714. const uint32_t n_layer = hparams.n_layer;
  6715. const uint32_t n_kv = llama_kv_cache_cell_max(kv_self);
  6716. const uint32_t n_used = kv_self.used;
  6717. assert(n_used <= n_kv);
  6718. //const int64_t t_start = ggml_time_us();
  6719. // number of cells moved
  6720. uint32_t n_moves = 0;
  6721. // determine which KV cells to move where
  6722. //
  6723. // cell i moves to ids[i]
  6724. //
  6725. // if ids[i] == i || ids[i] == n_kv, then cell i is not moved
  6726. //
  6727. std::vector<uint32_t> ids(n_kv, n_kv);
  6728. for (uint32_t i0 = 0; i0 < n_used; ++i0) {
  6729. const auto & cell0 = kv_self.cells[i0];
  6730. if (!cell0.is_empty()) {
  6731. ids[i0] = i0;
  6732. continue;
  6733. }
  6734. // found a hole - fill it with data from the end of the cache
  6735. uint32_t nh = 1;
  6736. // determine the size of the hole
  6737. while (i0 + nh < n_used && kv_self.cells[i0 + nh].is_empty()) {
  6738. nh++;
  6739. }
  6740. // each move requires 6*n_layer tensors (see build_defrag)
  6741. // - source view, destination view, copy operation
  6742. // - x2 for keys and values
  6743. //
  6744. if (6*(n_moves + nh)*n_layer >= LLAMA_MAX_NODES) {
  6745. // the graph is too big, we cannot move more cells
  6746. break;
  6747. }
  6748. uint32_t nf = 0;
  6749. uint32_t is = n_kv - 1;
  6750. // starting from the end, find nh non-empty cells
  6751. for (; is > i0; --is) {
  6752. const auto & cell1 = kv_self.cells[is];
  6753. if (cell1.is_empty() || ids[is] != n_kv) {
  6754. continue;
  6755. }
  6756. // non-empty cell which is not yet moved
  6757. nf++;
  6758. if (nf == nh) {
  6759. break;
  6760. }
  6761. }
  6762. // this can only happen if `n_used` is not accurate, which would be a bug
  6763. GGML_ASSERT(nf == nh && "KV defrag bug: nf != nh");
  6764. nf = 0;
  6765. uint32_t i1 = is;
  6766. // are we moving a continuous block of memory?
  6767. bool cont = false;
  6768. // go back and move the nf cells to the hole
  6769. for (; i1 < n_kv; ++i1) {
  6770. auto & cell1 = kv_self.cells[i1];
  6771. if (cell1.is_empty() || ids[i1] != n_kv) {
  6772. cont = false;
  6773. continue;
  6774. }
  6775. // this cell goes to (i0 + nf)
  6776. ids[i1] = i0 + nf;
  6777. // move the cell meta data
  6778. kv_self.cells[i0 + nf] = cell1;
  6779. // clear the old cell and move the head there
  6780. cell1 = llama_kv_cell();
  6781. kv_self.head = n_used;
  6782. if (!cont) {
  6783. n_moves++;
  6784. cont = true;
  6785. }
  6786. nf++;
  6787. if (nf == nh) {
  6788. break;
  6789. }
  6790. }
  6791. //LLAMA_LOG_INFO("(tmp log) KV defrag: move [%u, %u) to [%u, %u)\n", is, i1 + 1, i0, i0 + nh);
  6792. i0 += nh - 1;
  6793. }
  6794. if (n_moves == 0) {
  6795. return;
  6796. }
  6797. //LLAMA_LOG_INFO("(tmp log) KV defrag cell moves: %u\n", n_moves);
  6798. //LLAMA_LOG_INFO("expected gf nodes: %u\n", 6*n_moves*n_layer);
  6799. #if 0
  6800. // CPU defrag
  6801. //
  6802. // TODO: optimizations are possible:
  6803. // - multiple threads
  6804. // - avoid copying to the host memory when already there
  6805. //
  6806. // likely not worth the effort, as we have ggml_graph based defrag
  6807. //
  6808. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  6809. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  6810. const uint32_t kv_size = kv_self.size;
  6811. std::vector<uint8_t> buf_k;
  6812. std::vector<uint8_t> buf_v;
  6813. for (uint32_t il = 0; il < n_layer; ++il) {
  6814. const size_t k_size_row = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa);
  6815. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_size);
  6816. const size_t v_size_el = ggml_type_size(kv_self.v_l[il]->type);
  6817. const size_t v_size = ggml_row_size (kv_self.v_l[il]->type, n_embd_v_gqa*kv_size);
  6818. buf_k.resize(k_size);
  6819. buf_v.resize(v_size);
  6820. ggml_backend_tensor_get(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  6821. ggml_backend_tensor_get(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  6822. // batch move [i, i+nm) to [id, id+nm)
  6823. // note: cells can move only to a lower index
  6824. for (uint32_t i = 0; i < n_kv; ++i) {
  6825. const uint32_t id = ids[i];
  6826. if (i == id || id == n_kv) {
  6827. continue;
  6828. }
  6829. uint32_t nm = 1;
  6830. while (i + nm < n_kv && ids[i + nm] == id + nm) {
  6831. nm++;
  6832. }
  6833. // move keys
  6834. {
  6835. const int64_t os = i*k_size_row;
  6836. const int64_t od = id*k_size_row;
  6837. memcpy(buf_k.data() + od, buf_k.data() + os, nm*k_size_row);
  6838. }
  6839. // move values (note: they are transposed)
  6840. {
  6841. const int64_t os = i;
  6842. const int64_t od = id;
  6843. for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
  6844. memcpy(buf_v.data() + (od + j*kv_size)*v_size_el, buf_v.data() + (os + j*kv_size)*v_size_el, nm*v_size_el);
  6845. }
  6846. }
  6847. i += nm - 1;
  6848. }
  6849. ggml_backend_tensor_set(kv_self.k_l[il], buf_k.data(), 0, buf_k.size());
  6850. ggml_backend_tensor_set(kv_self.v_l[il], buf_v.data(), 0, buf_v.size());
  6851. }
  6852. #else
  6853. // ggml_graph defrag
  6854. ggml_cgraph * gf = llama_build_graph_defrag(lctx, ids);
  6855. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  6856. #endif
  6857. //const int64_t t_end = ggml_time_us();
  6858. //LLAMA_LOG_INFO("(tmp log) KV defrag time: %.3f ms\n", (t_end - t_start)/1000.0);
  6859. }
  6860. static void llama_kv_cache_update_internal(struct llama_context & lctx) {
  6861. // apply K-shift if needed
  6862. if (lctx.model.hparams.rope_type != LLAMA_ROPE_TYPE_NONE && lctx.kv_self.has_shift) {
  6863. llama_set_k_shift(lctx);
  6864. {
  6865. ggml_cgraph * gf = llama_build_graph_k_shift(lctx);
  6866. llama_graph_compute(lctx, gf, lctx.cparams.n_threads);
  6867. }
  6868. {
  6869. auto & kv_self = lctx.kv_self;
  6870. kv_self.has_shift = false;
  6871. for (uint32_t i = 0; i < kv_self.size; ++i) {
  6872. kv_self.cells[i].delta = 0;
  6873. }
  6874. }
  6875. }
  6876. // defragment the KV cache if needed
  6877. if (lctx.kv_self.do_defrag) {
  6878. llama_kv_cache_defrag_internal(lctx);
  6879. lctx.kv_self.do_defrag = false;
  6880. }
  6881. }
  6882. //
  6883. // tokenizer
  6884. //
  6885. static enum llama_vocab_type llama_vocab_get_type(const llama_vocab & vocab) {
  6886. return vocab.type;
  6887. }
  6888. static bool llama_is_normal_token(const llama_vocab & vocab, llama_token id) {
  6889. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL;
  6890. }
  6891. static bool llama_is_unknown_token(const llama_vocab & vocab, llama_token id) {
  6892. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_UNKNOWN;
  6893. }
  6894. static bool llama_is_control_token(const llama_vocab & vocab, llama_token id) {
  6895. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_CONTROL;
  6896. }
  6897. static bool llama_is_byte_token(const llama_vocab & vocab, llama_token id) {
  6898. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_BYTE;
  6899. }
  6900. static bool llama_is_user_defined_token(const llama_vocab& vocab, llama_token id) {
  6901. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_USER_DEFINED;
  6902. }
  6903. static uint8_t llama_token_to_byte(const llama_vocab& vocab, llama_token id) {
  6904. GGML_ASSERT(llama_is_byte_token(vocab, id));
  6905. const auto& token_data = vocab.id_to_token.at(id);
  6906. switch (llama_vocab_get_type(vocab)) {
  6907. case LLAMA_VOCAB_TYPE_SPM: {
  6908. auto buf = token_data.text.substr(3, 2);
  6909. return strtol(buf.c_str(), NULL, 16);
  6910. }
  6911. case LLAMA_VOCAB_TYPE_BPE: {
  6912. GGML_ASSERT(false);
  6913. return unicode_to_bytes_bpe(token_data.text);
  6914. }
  6915. case LLAMA_VOCAB_TYPE_WPM: {
  6916. GGML_ASSERT(false);
  6917. }
  6918. default:
  6919. GGML_ASSERT(false);
  6920. }
  6921. }
  6922. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch) {
  6923. static const char * hex = "0123456789ABCDEF";
  6924. switch (llama_vocab_get_type(vocab)) {
  6925. case LLAMA_VOCAB_TYPE_SPM: {
  6926. const char buf[7] = { '<', '0', 'x', hex[ch >> 4], hex[ch & 15], '>', 0 };
  6927. auto token = vocab.token_to_id.find(buf);
  6928. if (token != vocab.token_to_id.end()) {
  6929. return (*token).second;
  6930. }
  6931. // Try to fall back to just the byte as a string
  6932. const char buf2[2] = { (char)ch, 0 };
  6933. return vocab.token_to_id.at(buf2);
  6934. }
  6935. case LLAMA_VOCAB_TYPE_WPM:
  6936. case LLAMA_VOCAB_TYPE_BPE: {
  6937. return vocab.token_to_id.at(bytes_to_unicode_bpe(ch));
  6938. }
  6939. default:
  6940. GGML_ASSERT(false);
  6941. }
  6942. }
  6943. static void llama_escape_whitespace(std::string & text) {
  6944. replace_all(text, " ", "\xe2\x96\x81");
  6945. }
  6946. static void llama_unescape_whitespace(std::string & word) {
  6947. replace_all(word, "\xe2\x96\x81", " ");
  6948. }
  6949. struct llm_symbol {
  6950. using index = int;
  6951. index prev;
  6952. index next;
  6953. const char * text;
  6954. size_t n;
  6955. };
  6956. static_assert(std::is_trivially_copyable<llm_symbol>::value, "llm_symbol is not trivially copyable");
  6957. // SPM tokenizer
  6958. // original implementation:
  6959. // https://github.com/ggerganov/llama.cpp/commit/074bea2eb1f1349a0118239c4152914aecaa1be4
  6960. struct llm_bigram_spm {
  6961. struct comparator {
  6962. bool operator()(llm_bigram_spm & l, llm_bigram_spm & r) {
  6963. return (l.score < r.score) || (l.score == r.score && l.left > r.left);
  6964. }
  6965. };
  6966. using queue_storage = std::vector<llm_bigram_spm>;
  6967. using queue = std::priority_queue<llm_bigram_spm, queue_storage, comparator>;
  6968. llm_symbol::index left;
  6969. llm_symbol::index right;
  6970. float score;
  6971. size_t size;
  6972. };
  6973. struct llm_tokenizer_spm {
  6974. llm_tokenizer_spm(const llama_vocab & vocab) : vocab(vocab) {}
  6975. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  6976. // split string into utf8 chars
  6977. int index = 0;
  6978. size_t offs = 0;
  6979. while (offs < text.size()) {
  6980. llm_symbol sym;
  6981. size_t len = utf8_len(text[offs]);
  6982. sym.text = text.c_str() + offs;
  6983. sym.n = std::min(len, text.size() - offs);
  6984. offs += sym.n;
  6985. sym.prev = index - 1;
  6986. sym.next = offs == text.size() ? -1 : index + 1;
  6987. index++;
  6988. symbols.emplace_back(sym);
  6989. }
  6990. // seed the work queue with all possible 2-character tokens.
  6991. for (size_t i = 1; i < symbols.size(); ++i) {
  6992. try_add_bigram(i - 1, i);
  6993. }
  6994. // keep substituting the highest frequency pairs for as long as we can.
  6995. while (!work_queue.empty()) {
  6996. auto bigram = work_queue.top();
  6997. work_queue.pop();
  6998. auto & left_sym = symbols[bigram.left];
  6999. auto & right_sym = symbols[bigram.right];
  7000. // if one of the symbols already got merged, skip it.
  7001. if (left_sym.n == 0 || right_sym.n == 0 ||
  7002. left_sym.n + right_sym.n != bigram.size) {
  7003. continue;
  7004. }
  7005. // merge the right sym into the left one
  7006. left_sym.n += right_sym.n;
  7007. right_sym.n = 0;
  7008. //LLAMA_LOG_INFO("left = '%*s' size = %zu\n", (int) left_sym.n, left_sym.text, bigram.size);
  7009. // remove the right sym from the chain
  7010. left_sym.next = right_sym.next;
  7011. if (right_sym.next >= 0) {
  7012. symbols[right_sym.next].prev = bigram.left;
  7013. }
  7014. // find more substitutions
  7015. try_add_bigram(left_sym.prev, bigram.left);
  7016. try_add_bigram(bigram.left, left_sym.next);
  7017. }
  7018. for (int i = 0; i != -1; i = symbols[i].next) {
  7019. auto & symbol = symbols[i];
  7020. resegment(symbol, output);
  7021. }
  7022. }
  7023. private:
  7024. void resegment(llm_symbol & symbol, std::vector<llama_vocab::id> & output) {
  7025. auto text = std::string(symbol.text, symbol.n);
  7026. auto token = vocab.token_to_id.find(text);
  7027. // Do we need to support is_unused?
  7028. if (token != vocab.token_to_id.end()) {
  7029. output.push_back((*token).second);
  7030. return;
  7031. }
  7032. const auto p = rev_merge.find(text);
  7033. if (p == rev_merge.end()) {
  7034. // output any symbols that did not form tokens as bytes.
  7035. output.reserve(output.size() + symbol.n);
  7036. for (int j = 0; j < (int)symbol.n; ++j) {
  7037. llama_vocab::id token_id = llama_byte_to_token(vocab, symbol.text[j]);
  7038. output.push_back(token_id);
  7039. }
  7040. return;
  7041. }
  7042. resegment(symbols[p->second.first], output);
  7043. resegment(symbols[p->second.second], output);
  7044. }
  7045. void try_add_bigram(int left, int right) {
  7046. if (left == -1 || right == -1) {
  7047. return;
  7048. }
  7049. const std::string text = std::string(symbols[left].text, symbols[left].n + symbols[right].n);
  7050. auto token = vocab.token_to_id.find(text);
  7051. if (token == vocab.token_to_id.end()) {
  7052. return;
  7053. }
  7054. if (static_cast<size_t>((*token).second) >= vocab.id_to_token.size()) {
  7055. return;
  7056. }
  7057. const auto & tok_data = vocab.id_to_token[(*token).second];
  7058. llm_bigram_spm bigram;
  7059. bigram.left = left;
  7060. bigram.right = right;
  7061. bigram.score = tok_data.score;
  7062. bigram.size = text.size();
  7063. work_queue.push(bigram);
  7064. // Do we need to support is_unused?
  7065. rev_merge[text] = std::make_pair(left, right);
  7066. }
  7067. const llama_vocab & vocab;
  7068. std::vector<llm_symbol> symbols;
  7069. llm_bigram_spm::queue work_queue;
  7070. std::map<std::string, std::pair<int, int>> rev_merge;
  7071. };
  7072. // BPE tokenizer
  7073. // adapted from https://github.com/cmp-nct/ggllm.cpp [MIT License]
  7074. // tried to simplify unicode stuff, so most likely does not work 100% correctly!
  7075. // TODO: there are a lot of common parts between spm and bpe tokenizers, should be refactored and reused
  7076. struct llm_bigram_bpe {
  7077. struct comparator {
  7078. bool operator()(const llm_bigram_bpe & l, const llm_bigram_bpe & r) const {
  7079. return l.rank > r.rank || (l.rank == r.rank && l.left > r.left);
  7080. }
  7081. };
  7082. using queue_storage = std::vector<llm_bigram_bpe>;
  7083. using queue = std::priority_queue<llm_bigram_bpe, queue_storage, comparator>;
  7084. llm_symbol::index left;
  7085. llm_symbol::index right;
  7086. std::string text;
  7087. int rank;
  7088. size_t size;
  7089. };
  7090. struct llm_tokenizer_bpe {
  7091. llm_tokenizer_bpe(const llama_vocab & vocab): vocab(vocab) {}
  7092. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  7093. int final_prev_index = -1;
  7094. auto word_collection = bpe_gpt2_preprocess(text);
  7095. symbols_final.clear();
  7096. for (auto & word : word_collection) {
  7097. work_queue = llm_bigram_bpe::queue();
  7098. symbols.clear();
  7099. int index = 0;
  7100. size_t offset = 0;
  7101. while (offset < word.size()) {
  7102. llm_symbol sym;
  7103. size_t char_len = std::min(word.size() - offset, (size_t) ::utf8_len(word[offset]));
  7104. sym.text = word.c_str() + offset;
  7105. sym.n = char_len;
  7106. offset += sym.n;
  7107. sym.prev = index - 1;
  7108. sym.next = offset == word.size() ? -1 : index + 1;
  7109. index++;
  7110. symbols.emplace_back(sym);
  7111. }
  7112. for (size_t i = 1; i < symbols.size(); ++i) {
  7113. add_new_bigram(i - 1, i);
  7114. }
  7115. // build token(s)
  7116. while (!work_queue.empty()) {
  7117. auto bigram = work_queue.top();
  7118. work_queue.pop();
  7119. auto & left_symbol = symbols[bigram.left];
  7120. auto & right_symbol = symbols[bigram.right];
  7121. if (left_symbol.n == 0 || right_symbol.n == 0) {
  7122. continue;
  7123. }
  7124. std::string left_token = std::string(left_symbol.text, left_symbol.n);
  7125. std::string right_token = std::string(right_symbol.text, right_symbol.n);
  7126. if (left_token + right_token != bigram.text) {
  7127. continue; // Skip this bigram if it's outdated
  7128. }
  7129. // merge the right sym into the left one
  7130. left_symbol.n += right_symbol.n;
  7131. right_symbol.n = 0;
  7132. // remove the right sym from the chain
  7133. left_symbol.next = right_symbol.next;
  7134. if (right_symbol.next >= 0) {
  7135. symbols[right_symbol.next].prev = bigram.left;
  7136. }
  7137. add_new_bigram(left_symbol.prev, bigram.left); // left side of current symbol
  7138. add_new_bigram(bigram.left, left_symbol.next); // right side of current symbol
  7139. }
  7140. // add the fnished tokens to the final list keeping correct order for next and prev
  7141. for (auto & sym : symbols) {
  7142. if (sym.n > 0) {
  7143. sym.prev = final_prev_index;
  7144. sym.next = -1;
  7145. if (final_prev_index != -1) {
  7146. symbols_final[final_prev_index].next = symbols_final.size();
  7147. }
  7148. symbols_final.emplace_back(sym);
  7149. final_prev_index = symbols_final.size() - 1;
  7150. }
  7151. }
  7152. }
  7153. symbols = symbols_final;
  7154. if (!symbols.empty()) {
  7155. for (int i = 0; i != -1; i = symbols[i].next) {
  7156. auto & symbol = symbols[i];
  7157. if (symbol.n == 0) {
  7158. continue;
  7159. }
  7160. const std::string str = std::string(symbol.text, symbol.n);
  7161. const auto token = vocab.token_to_id.find(str);
  7162. if (token == vocab.token_to_id.end()) {
  7163. for (auto j = str.begin(); j != str.end(); ++j) {
  7164. std::string byte_str(1, *j);
  7165. auto token_multibyte = vocab.token_to_id.find(byte_str);
  7166. if (token_multibyte == vocab.token_to_id.end()) {
  7167. throw std::runtime_error("ERROR: byte not found in vocab");
  7168. }
  7169. output.push_back((*token_multibyte).second);
  7170. }
  7171. } else {
  7172. output.push_back((*token).second);
  7173. }
  7174. }
  7175. }
  7176. }
  7177. private:
  7178. void add_new_bigram(int left, int right) {
  7179. if (left == -1 || right == -1) {
  7180. return;
  7181. }
  7182. std::string left_token = std::string(symbols[left].text, symbols[left].n);
  7183. std::string right_token = std::string(symbols[right].text, symbols[right].n);
  7184. int rank_found = -1;
  7185. rank_found = vocab.find_bpe_rank(left_token, right_token);
  7186. if (rank_found < 0) {
  7187. return;
  7188. }
  7189. llm_bigram_bpe bigram;
  7190. bigram.left = left;
  7191. bigram.right = right;
  7192. bigram.text = left_token + right_token;
  7193. bigram.size = left_token.size() + right_token.size();
  7194. bigram.rank = rank_found;
  7195. work_queue.push(bigram);
  7196. }
  7197. std::vector<std::string> bpe_gpt2_preprocess(const std::string & text) {
  7198. std::vector<std::string> bpe_words;
  7199. std::vector<std::string> bpe_encoded_words;
  7200. std::string token = "";
  7201. // GPT2 system regex: 's|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+
  7202. bool collecting_numeric = false;
  7203. bool collecting_letter = false;
  7204. bool collecting_special = false;
  7205. bool collecting_whitespace_lookahead = false;
  7206. bool collecting = false;
  7207. std::vector<std::string> text_utf;
  7208. text_utf.reserve(text.size());
  7209. bpe_words.reserve(text.size());
  7210. bpe_encoded_words.reserve(text.size());
  7211. auto cps = codepoints_from_utf8(text);
  7212. for (size_t i = 0; i < cps.size(); ++i)
  7213. text_utf.emplace_back(codepoint_to_utf8(cps[i]));
  7214. for (int i = 0; i < (int)text_utf.size(); i++) {
  7215. const std::string & utf_char = text_utf[i];
  7216. bool split_condition = false;
  7217. int bytes_remain = text_utf.size() - i;
  7218. // forward backward lookups
  7219. const std::string & utf_char_next = (i + 1 < (int)text_utf.size()) ? text_utf[i + 1] : "";
  7220. const std::string & utf_char_next_next = (i + 2 < (int)text_utf.size()) ? text_utf[i + 2] : "";
  7221. // handling contractions
  7222. if (!split_condition && bytes_remain >= 2) {
  7223. // 's|'t|'m|'d
  7224. if (utf_char == "\'" && (utf_char_next == "s" || utf_char_next == "t" || utf_char_next == "m" || utf_char_next == "d")) {
  7225. split_condition = true;
  7226. }
  7227. if (split_condition) {
  7228. if (token.size()) {
  7229. bpe_words.emplace_back(token); // push previous content as token
  7230. }
  7231. token = utf_char + utf_char_next;
  7232. bpe_words.emplace_back(token);
  7233. token = "";
  7234. i++;
  7235. continue;
  7236. }
  7237. }
  7238. if (!split_condition && bytes_remain >= 3) {
  7239. // 're|'ve|'ll
  7240. if (utf_char == "\'" && (
  7241. (utf_char_next == "r" && utf_char_next_next == "e") ||
  7242. (utf_char_next == "v" && utf_char_next_next == "e") ||
  7243. (utf_char_next == "l" && utf_char_next_next == "l"))
  7244. ) {
  7245. split_condition = true;
  7246. }
  7247. if (split_condition) {
  7248. // current token + next token can be defined
  7249. if (token.size()) {
  7250. bpe_words.emplace_back(token); // push previous content as token
  7251. }
  7252. token = utf_char + utf_char_next + utf_char_next_next;
  7253. bpe_words.emplace_back(token); // the contraction
  7254. token = "";
  7255. i += 2;
  7256. continue;
  7257. }
  7258. }
  7259. if (!split_condition && !collecting) {
  7260. if (codepoint_type(utf_char) == CODEPOINT_TYPE_LETTER || (!token.size() && utf_char == " " && codepoint_type(utf_char_next) == CODEPOINT_TYPE_LETTER)) {
  7261. collecting_letter = true;
  7262. collecting = true;
  7263. }
  7264. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_DIGIT || (!token.size() && utf_char == " " && codepoint_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  7265. collecting_numeric = true;
  7266. collecting = true;
  7267. }
  7268. else if (
  7269. ((codepoint_type(utf_char) != CODEPOINT_TYPE_LETTER && codepoint_type(utf_char) != CODEPOINT_TYPE_DIGIT) && (codepoint_type(utf_char) != CODEPOINT_TYPE_WHITESPACE)) ||
  7270. (!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)
  7271. ) {
  7272. collecting_special = true;
  7273. collecting = true;
  7274. }
  7275. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_WHITESPACE && codepoint_type(utf_char_next) == CODEPOINT_TYPE_WHITESPACE) {
  7276. collecting_whitespace_lookahead = true;
  7277. collecting = true;
  7278. }
  7279. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_WHITESPACE) {
  7280. split_condition = true;
  7281. }
  7282. }
  7283. else if (!split_condition && collecting) {
  7284. if (collecting_letter && codepoint_type(utf_char) != CODEPOINT_TYPE_LETTER) {
  7285. split_condition = true;
  7286. }
  7287. else if (collecting_numeric && codepoint_type(utf_char) != CODEPOINT_TYPE_DIGIT) {
  7288. split_condition = true;
  7289. }
  7290. 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)) {
  7291. split_condition = true;
  7292. }
  7293. else if (collecting_whitespace_lookahead && (codepoint_type(utf_char_next) == CODEPOINT_TYPE_LETTER || codepoint_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  7294. split_condition = true;
  7295. }
  7296. }
  7297. if (utf_char_next == "") {
  7298. split_condition = true; // final
  7299. token += utf_char;
  7300. }
  7301. if (split_condition) {
  7302. if (token.size()) {
  7303. bpe_words.emplace_back(token);
  7304. }
  7305. token = utf_char;
  7306. collecting = false;
  7307. collecting_letter = false;
  7308. collecting_numeric = false;
  7309. collecting_special = false;
  7310. collecting_whitespace_lookahead = false;
  7311. }
  7312. else {
  7313. token += utf_char;
  7314. }
  7315. }
  7316. for (std::string & word : bpe_words) {
  7317. std::string encoded_token = "";
  7318. for (char & c : word) {
  7319. encoded_token += bytes_to_unicode_bpe(c);
  7320. }
  7321. bpe_encoded_words.emplace_back(encoded_token);
  7322. }
  7323. return bpe_encoded_words;
  7324. }
  7325. const llama_vocab & vocab;
  7326. std::vector<llm_symbol> symbols;
  7327. std::vector<llm_symbol> symbols_final;
  7328. llm_bigram_bpe::queue work_queue;
  7329. };
  7330. struct llm_tokenizer_wpm {
  7331. llm_tokenizer_wpm(const llama_vocab & vocab): vocab(vocab) {}
  7332. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  7333. auto * token_map = &vocab.token_to_id;
  7334. // normalize and split by whitespace
  7335. std::vector<std::string> words = preprocess(text);
  7336. // bos token prepended already
  7337. // find the longest tokens that form the words
  7338. for (const std::string &word : words) {
  7339. // skip empty words
  7340. if (word.size() == 0) {
  7341. continue;
  7342. }
  7343. // prepend phantom space
  7344. std::string word1 = "\xe2\x96\x81" + word;
  7345. int n = word1.size();
  7346. // we're at the start of a new word
  7347. int i = 0;
  7348. bool match_any = false;
  7349. // move through character position in word
  7350. while (i < n) {
  7351. // loop through possible match length
  7352. bool match = false;
  7353. for (int j = n; j > i; j--) {
  7354. auto it = token_map->find(word1.substr(i, j - i));
  7355. if (it != token_map->end()) {
  7356. output.push_back(it->second);
  7357. match = true;
  7358. match_any = true;
  7359. i = j;
  7360. break;
  7361. }
  7362. }
  7363. // must be an unknown character
  7364. if (!match) {
  7365. i++;
  7366. }
  7367. }
  7368. // we didn't find any matches for this word
  7369. if (!match_any) {
  7370. output.push_back(vocab.special_unk_id);
  7371. }
  7372. }
  7373. // append eos token
  7374. output.push_back(vocab.special_eos_id);
  7375. }
  7376. std::vector<std::string> preprocess(const std::string & text) {
  7377. // normalalization form D
  7378. std::vector<uint32_t> codepoints = codepoints_from_utf8(text);
  7379. std::vector<uint32_t> nfd_codepoints;
  7380. for (uint32_t code : codepoints) {
  7381. auto it = nfd_map.find(code);
  7382. if (it != nfd_map.end()) {
  7383. for (uint32_t c : it->second) {
  7384. nfd_codepoints.push_back(c);
  7385. }
  7386. } else {
  7387. nfd_codepoints.push_back(code);
  7388. }
  7389. }
  7390. // strip accents, strip control, uniformize whitespace,
  7391. // to lowercase, pad chinese characters, pad punctuation
  7392. std::string new_str = "";
  7393. for (uint32_t code : nfd_codepoints) {
  7394. int type = codepoint_type(code);
  7395. if (type == CODEPOINT_TYPE_ACCENT_MARK || type == CODEPOINT_TYPE_CONTROL) {
  7396. continue;
  7397. }
  7398. code = to_lower(code);
  7399. if (type == CODEPOINT_TYPE_WHITESPACE) {
  7400. code = ' ';
  7401. }
  7402. std::string s = codepoint_to_utf8(code);
  7403. if (type == CODEPOINT_TYPE_PUNCTUATION || is_ascii_punct(code) || is_chinese_char(code)) {
  7404. new_str += " ";
  7405. new_str += s;
  7406. new_str += " ";
  7407. } else {
  7408. new_str += s;
  7409. }
  7410. }
  7411. // split by whitespace
  7412. uint64_t l = 0;
  7413. uint64_t r = 0;
  7414. std::vector<std::string> words;
  7415. while (r < new_str.size()) {
  7416. // if is whitespace
  7417. if (isspace(new_str[r])) {
  7418. if (r > l) words.push_back(new_str.substr(l, (r - l)));
  7419. l = r + 1;
  7420. r = l;
  7421. }
  7422. else {
  7423. r += 1;
  7424. }
  7425. }
  7426. if (r > l) {
  7427. words.push_back(new_str.substr(l, (r - l)));
  7428. }
  7429. return words;
  7430. }
  7431. uint32_t to_lower(uint32_t code) {
  7432. #if defined(_WIN32)
  7433. if (code > 0xFFFF) {
  7434. return code;
  7435. }
  7436. #endif
  7437. return std::tolower(wchar_t(code), std::locale("en_US.UTF-8"));
  7438. }
  7439. bool is_ascii_punct(uint32_t code) {
  7440. return code < 256 && ispunct(code);
  7441. }
  7442. bool is_chinese_char(uint32_t codepoint) {
  7443. if ((codepoint >= 0x4E00 && codepoint <= 0x9FFF) ||
  7444. (codepoint >= 0x3400 && codepoint <= 0x4DBF) ||
  7445. (codepoint >= 0x20000 && codepoint <= 0x2A6DF) ||
  7446. (codepoint >= 0x2A700 && codepoint <= 0x2B73F) ||
  7447. (codepoint >= 0x2B740 && codepoint <= 0x2B81F) ||
  7448. (codepoint >= 0x2B920 && codepoint <= 0x2CEAF) || // this should be 0x2B820 but in hf rust code it is 0x2B920
  7449. (codepoint >= 0xF900 && codepoint <= 0xFAFF) ||
  7450. (codepoint >= 0x2F800 && codepoint <= 0x2FA1F) ||
  7451. (codepoint >= 0x3000 && codepoint <= 0x303F) ||
  7452. (codepoint >= 0xFF00 && codepoint <= 0xFFEF)) {
  7453. return true; // NOLINT
  7454. }
  7455. return false;
  7456. }
  7457. const llama_vocab & vocab;
  7458. };
  7459. typedef enum FRAGMENT_BUFFER_VARIANT_TYPE {
  7460. FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN,
  7461. FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT
  7462. } FRAGMENT_BUFFER_VARIANT_TYPE;
  7463. struct fragment_buffer_variant {
  7464. fragment_buffer_variant(llama_vocab::id _token)
  7465. :
  7466. type(FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN),
  7467. token(_token),
  7468. raw_text(_dummy),
  7469. offset(0),
  7470. length(0) {}
  7471. fragment_buffer_variant(const std::string & _raw_text, int64_t _offset, int64_t _length)
  7472. :
  7473. type(FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT),
  7474. token((llama_vocab::id) - 1),
  7475. raw_text(_raw_text),
  7476. offset(_offset),
  7477. length(_length){
  7478. GGML_ASSERT(_offset >= 0);
  7479. GGML_ASSERT(_length >= 1);
  7480. GGML_ASSERT(offset + length <= raw_text.length());
  7481. }
  7482. const FRAGMENT_BUFFER_VARIANT_TYPE type;
  7483. const llama_vocab::id token;
  7484. const std::string _dummy;
  7485. const std::string & raw_text;
  7486. const uint64_t offset;
  7487. const uint64_t length;
  7488. };
  7489. // #define PRETOKENIZERDEBUG
  7490. static void tokenizer_st_partition(const llama_vocab & vocab, std::forward_list<fragment_buffer_variant> & buffer) {
  7491. // for each special token
  7492. for (const auto & st: vocab.special_tokens_cache) {
  7493. const auto & special_token = st.first;
  7494. const auto & special_id = st.second;
  7495. // for each text fragment
  7496. std::forward_list<fragment_buffer_variant>::iterator it = buffer.begin();
  7497. while (it != buffer.end()) {
  7498. auto & fragment = (*it);
  7499. // if a fragment is text ( not yet processed )
  7500. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  7501. auto * raw_text = &(fragment.raw_text);
  7502. auto raw_text_base_offset = fragment.offset;
  7503. auto raw_text_base_length = fragment.length;
  7504. // loop over the text
  7505. while (true) {
  7506. // find the first occurrence of a given special token in this fragment
  7507. // passing offset argument only limit the "search area" but match coordinates
  7508. // are still relative to the source full raw_text
  7509. auto match = raw_text->find(special_token, raw_text_base_offset);
  7510. // no occurrences found, stop processing this fragment for a given special token
  7511. if (match == std::string::npos) break;
  7512. // check if match is within bounds of offset <-> length
  7513. if (match + special_token.length() > raw_text_base_offset + raw_text_base_length) break;
  7514. #ifdef PRETOKENIZERDEBUG
  7515. 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());
  7516. #endif
  7517. auto source = std::distance(buffer.begin(), it);
  7518. // if match is further than base offset
  7519. // then we have some text to the left of it
  7520. if (match > raw_text_base_offset) {
  7521. // left
  7522. const int64_t left_reminder_offset = raw_text_base_offset + 0;
  7523. const int64_t left_reminder_length = match - raw_text_base_offset;
  7524. buffer.emplace_after(it, (*raw_text), left_reminder_offset, left_reminder_length);
  7525. #ifdef PRETOKENIZERDEBUG
  7526. 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());
  7527. #endif
  7528. it++;
  7529. }
  7530. // special token
  7531. buffer.emplace_after(it, special_id);
  7532. it++;
  7533. // right
  7534. if (match + special_token.length() < raw_text_base_offset + raw_text_base_length) {
  7535. const int64_t right_reminder_offset = match + special_token.length();
  7536. const int64_t right_reminder_length = raw_text_base_length - ((match - raw_text_base_offset) + special_token.length());
  7537. buffer.emplace_after(it, (*raw_text), right_reminder_offset, right_reminder_length);
  7538. #ifdef PRETOKENIZERDEBUG
  7539. 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());
  7540. #endif
  7541. it++;
  7542. if (source == 0) {
  7543. buffer.erase_after(buffer.before_begin());
  7544. } else {
  7545. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  7546. }
  7547. // repeat for the right side
  7548. raw_text_base_offset = right_reminder_offset;
  7549. raw_text_base_length = right_reminder_length;
  7550. #ifdef PRETOKENIZERDEBUG
  7551. 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());
  7552. #endif
  7553. } else {
  7554. if (source == 0) {
  7555. buffer.erase_after(buffer.before_begin());
  7556. } else {
  7557. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  7558. }
  7559. break;
  7560. }
  7561. }
  7562. }
  7563. it++;
  7564. }
  7565. }
  7566. }
  7567. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special) {
  7568. std::vector<llama_vocab::id> output;
  7569. // OG tokenizer behavior:
  7570. //
  7571. // tokenizer.encode('', add_bos=True) returns [1]
  7572. // tokenizer.encode('', add_bos=False) returns []
  7573. if (bos && vocab.special_bos_id != -1) {
  7574. output.push_back(vocab.special_bos_id);
  7575. }
  7576. if (raw_text.empty()) {
  7577. return output;
  7578. }
  7579. std::forward_list<fragment_buffer_variant> fragment_buffer;
  7580. fragment_buffer.emplace_front(raw_text, 0, raw_text.length());
  7581. if (special) tokenizer_st_partition(vocab, fragment_buffer);
  7582. switch (vocab.type) {
  7583. case LLAMA_VOCAB_TYPE_SPM:
  7584. {
  7585. for (const auto & fragment : fragment_buffer) {
  7586. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  7587. // without adding this leading whitespace, we do not get the same results as the original tokenizer
  7588. // TODO: It's likely possible to get rid of this string copy entirely
  7589. // by modifying llm_tokenizer_x to operate with string offsets like pre-tokenizer
  7590. // and passing 'add space prefix' as bool argument
  7591. //
  7592. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  7593. if (&fragment == &fragment_buffer.front()) {
  7594. if (vocab.add_space_prefix) {
  7595. raw_text = " " + raw_text; // prefix with space if the first token is not special
  7596. }
  7597. }
  7598. #ifdef PRETOKENIZERDEBUG
  7599. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  7600. #endif
  7601. llm_tokenizer_spm tokenizer(vocab);
  7602. llama_escape_whitespace(raw_text);
  7603. tokenizer.tokenize(raw_text, output);
  7604. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  7605. output.push_back(fragment.token);
  7606. }
  7607. }
  7608. } break;
  7609. case LLAMA_VOCAB_TYPE_BPE:
  7610. {
  7611. for (const auto & fragment : fragment_buffer) {
  7612. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  7613. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  7614. #ifdef PRETOKENIZERDEBUG
  7615. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  7616. #endif
  7617. llm_tokenizer_bpe tokenizer(vocab);
  7618. tokenizer.tokenize(raw_text, output);
  7619. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  7620. output.push_back(fragment.token);
  7621. }
  7622. }
  7623. } break;
  7624. case LLAMA_VOCAB_TYPE_WPM:
  7625. {
  7626. for (const auto & fragment : fragment_buffer) {
  7627. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  7628. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  7629. #ifdef PRETOKENIZERDEBUG
  7630. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  7631. #endif
  7632. llm_tokenizer_wpm tokenizer(vocab);
  7633. tokenizer.tokenize(raw_text, output);
  7634. } else { // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  7635. output.push_back(fragment.token);
  7636. }
  7637. }
  7638. } break;
  7639. }
  7640. return output;
  7641. }
  7642. //
  7643. // grammar - internal
  7644. //
  7645. struct llama_partial_utf8 {
  7646. uint32_t value; // bit value so far (unshifted)
  7647. int n_remain; // num bytes remaining; -1 indicates invalid sequence
  7648. };
  7649. struct llama_grammar {
  7650. const std::vector<std::vector<llama_grammar_element>> rules;
  7651. std::vector<std::vector<const llama_grammar_element *>> stacks;
  7652. // buffer for partially generated UTF-8 sequence from accepted tokens
  7653. llama_partial_utf8 partial_utf8;
  7654. };
  7655. struct llama_grammar_candidate {
  7656. size_t index;
  7657. const uint32_t * code_points;
  7658. llama_partial_utf8 partial_utf8;
  7659. };
  7660. // Decodes a UTF-8 string which may end in an incomplete sequence. Adds a terminating 0 for use as
  7661. // pointer. If an invalid sequence is encountered, returns `llama_partial_utf8.n_remain == -1`.
  7662. static std::pair<std::vector<uint32_t>, llama_partial_utf8> decode_utf8(
  7663. const std::string & src,
  7664. llama_partial_utf8 partial_start) {
  7665. static const int lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 3, 4 };
  7666. const char * pos = src.c_str();
  7667. std::vector<uint32_t> code_points;
  7668. // common english strings have the same number of codepoints and bytes. `+ 1` for the terminating 0.
  7669. code_points.reserve(src.size() + 1);
  7670. uint32_t value = partial_start.value;
  7671. int n_remain = partial_start.n_remain;
  7672. // continue previous decode, if applicable
  7673. while (*pos != 0 && n_remain > 0) {
  7674. uint8_t next_byte = static_cast<uint8_t>(*pos);
  7675. if ((next_byte >> 6) != 2) {
  7676. // invalid sequence, abort
  7677. code_points.push_back(0);
  7678. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, -1 });
  7679. }
  7680. value = (value << 6) + (next_byte & 0x3F);
  7681. ++pos;
  7682. --n_remain;
  7683. }
  7684. if (partial_start.n_remain > 0 && n_remain == 0) {
  7685. code_points.push_back(value);
  7686. }
  7687. // decode any subsequent utf-8 sequences, which may end in an incomplete one
  7688. while (*pos != 0) {
  7689. uint8_t first_byte = static_cast<uint8_t>(*pos);
  7690. uint8_t highbits = first_byte >> 4;
  7691. n_remain = lookup[highbits] - 1;
  7692. if (n_remain < 0) {
  7693. // invalid sequence, abort
  7694. code_points.clear();
  7695. code_points.push_back(0);
  7696. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, n_remain });
  7697. }
  7698. uint8_t mask = (1 << (7 - n_remain)) - 1;
  7699. value = first_byte & mask;
  7700. ++pos;
  7701. while (*pos != 0 && n_remain > 0) {
  7702. value = (value << 6) + (static_cast<uint8_t>(*pos) & 0x3F);
  7703. ++pos;
  7704. --n_remain;
  7705. }
  7706. if (n_remain == 0) {
  7707. code_points.push_back(value);
  7708. }
  7709. }
  7710. code_points.push_back(0);
  7711. return std::make_pair(std::move(code_points), llama_partial_utf8{ value, n_remain });
  7712. }
  7713. // returns true iff pos points to the end of one of the definitions of a rule
  7714. static bool llama_grammar_is_end_of_sequence(const llama_grammar_element * pos) {
  7715. switch (pos->type) {
  7716. case LLAMA_GRETYPE_END: return true; // NOLINT
  7717. case LLAMA_GRETYPE_ALT: return true; // NOLINT
  7718. default: return false;
  7719. }
  7720. }
  7721. // returns true iff chr satisfies the char range at pos (regular or inverse range)
  7722. // asserts that pos is pointing to a char range element
  7723. static std::pair<bool, const llama_grammar_element *> llama_grammar_match_char(
  7724. const llama_grammar_element * pos,
  7725. const uint32_t chr) {
  7726. bool found = false;
  7727. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  7728. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT); // NOLINT
  7729. do {
  7730. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  7731. // inclusive range, e.g. [a-z]
  7732. found = found || (pos->value <= chr && chr <= pos[1].value);
  7733. pos += 2;
  7734. } else {
  7735. // exact char match, e.g. [a] or "a"
  7736. found = found || pos->value == chr;
  7737. pos += 1;
  7738. }
  7739. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  7740. return std::make_pair(found == is_positive_char, pos);
  7741. }
  7742. // returns true iff some continuation of the given partial UTF-8 sequence could satisfy the char
  7743. // range at pos (regular or inverse range)
  7744. // asserts that pos is pointing to a char range element
  7745. static bool llama_grammar_match_partial_char(
  7746. const llama_grammar_element * pos,
  7747. const llama_partial_utf8 partial_utf8) {
  7748. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  7749. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT);
  7750. uint32_t partial_value = partial_utf8.value;
  7751. int n_remain = partial_utf8.n_remain;
  7752. // invalid sequence or 7-bit char split across 2 bytes (overlong)
  7753. if (n_remain < 0 || (n_remain == 1 && partial_value < 2)) {
  7754. return false;
  7755. }
  7756. // range of possible code points this partial UTF-8 sequence could complete to
  7757. uint32_t low = partial_value << (n_remain * 6);
  7758. uint32_t high = low | ((1 << (n_remain * 6)) - 1);
  7759. if (low == 0) {
  7760. if (n_remain == 2) {
  7761. low = 1 << 11;
  7762. } else if (n_remain == 3) {
  7763. low = 1 << 16;
  7764. }
  7765. }
  7766. do {
  7767. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  7768. // inclusive range, e.g. [a-z]
  7769. if (pos->value <= high && low <= pos[1].value) {
  7770. return is_positive_char;
  7771. }
  7772. pos += 2;
  7773. } else {
  7774. // exact char match, e.g. [a] or "a"
  7775. if (low <= pos->value && pos->value <= high) {
  7776. return is_positive_char;
  7777. }
  7778. pos += 1;
  7779. }
  7780. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  7781. return !is_positive_char;
  7782. }
  7783. // transforms a grammar pushdown stack into N possible stacks, all ending
  7784. // at a character range (terminal element)
  7785. static void llama_grammar_advance_stack(
  7786. const std::vector<std::vector<llama_grammar_element>> & rules,
  7787. const std::vector<const llama_grammar_element *> & stack,
  7788. std::vector<std::vector<const llama_grammar_element *>> & new_stacks) {
  7789. if (stack.empty()) {
  7790. new_stacks.emplace_back(stack);
  7791. return;
  7792. }
  7793. const llama_grammar_element * pos = stack.back();
  7794. switch (pos->type) {
  7795. case LLAMA_GRETYPE_RULE_REF: {
  7796. const size_t rule_id = static_cast<size_t>(pos->value);
  7797. const llama_grammar_element * subpos = rules[rule_id].data();
  7798. do {
  7799. // init new stack without the top (pos)
  7800. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  7801. if (!llama_grammar_is_end_of_sequence(pos + 1)) {
  7802. // if this rule ref is followed by another element, add that to stack
  7803. new_stack.push_back(pos + 1);
  7804. }
  7805. if (!llama_grammar_is_end_of_sequence(subpos)) {
  7806. // if alternate is nonempty, add to stack
  7807. new_stack.push_back(subpos);
  7808. }
  7809. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  7810. while (!llama_grammar_is_end_of_sequence(subpos)) {
  7811. // scan to end of alternate def
  7812. subpos++;
  7813. }
  7814. if (subpos->type == LLAMA_GRETYPE_ALT) {
  7815. // there's another alternate def of this rule to process
  7816. subpos++;
  7817. } else {
  7818. break;
  7819. }
  7820. } while (true);
  7821. break;
  7822. }
  7823. case LLAMA_GRETYPE_CHAR:
  7824. case LLAMA_GRETYPE_CHAR_NOT:
  7825. new_stacks.emplace_back(stack);
  7826. break;
  7827. default:
  7828. // end of alternate (LLAMA_GRETYPE_END, LLAMA_GRETYPE_ALT) or middle of char range
  7829. // (LLAMA_GRETYPE_CHAR_ALT, LLAMA_GRETYPE_CHAR_RNG_UPPER); stack should never be left on
  7830. // those
  7831. GGML_ASSERT(false);
  7832. }
  7833. }
  7834. // takes a set of possible pushdown stacks on a grammar, which are required to
  7835. // be positioned at a character range (see `llama_grammar_advance_stack`), and
  7836. // produces the N possible stacks if the given char is accepted at those
  7837. // positions
  7838. static std::vector<std::vector<const llama_grammar_element *>> llama_grammar_accept(
  7839. const std::vector<std::vector<llama_grammar_element>> & rules,
  7840. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  7841. const uint32_t chr) {
  7842. std::vector<std::vector<const llama_grammar_element *>> new_stacks;
  7843. for (const auto & stack : stacks) {
  7844. if (stack.empty()) {
  7845. continue;
  7846. }
  7847. auto match = llama_grammar_match_char(stack.back(), chr);
  7848. if (match.first) {
  7849. const llama_grammar_element * pos = match.second;
  7850. // update top of stack to next element, if any
  7851. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  7852. if (!llama_grammar_is_end_of_sequence(pos)) {
  7853. new_stack.push_back(pos);
  7854. }
  7855. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  7856. }
  7857. }
  7858. return new_stacks;
  7859. }
  7860. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  7861. const std::vector<std::vector<llama_grammar_element>> & rules,
  7862. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  7863. const std::vector<llama_grammar_candidate> & candidates);
  7864. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates_for_stack(
  7865. const std::vector<std::vector<llama_grammar_element>> & rules,
  7866. const std::vector<const llama_grammar_element *> & stack,
  7867. const std::vector<llama_grammar_candidate> & candidates) {
  7868. std::vector<llama_grammar_candidate> rejects;
  7869. if (stack.empty()) {
  7870. for (const auto & tok : candidates) {
  7871. if (*tok.code_points != 0 || tok.partial_utf8.n_remain != 0) {
  7872. rejects.push_back(tok);
  7873. }
  7874. }
  7875. return rejects;
  7876. }
  7877. const llama_grammar_element * stack_pos = stack.back();
  7878. std::vector<llama_grammar_candidate> next_candidates;
  7879. for (const auto & tok : candidates) {
  7880. if (*tok.code_points == 0) {
  7881. // reached end of full codepoints in token, reject iff it ended in a partial sequence
  7882. // that cannot satisfy this position in grammar
  7883. if (tok.partial_utf8.n_remain != 0 &&
  7884. !llama_grammar_match_partial_char(stack_pos, tok.partial_utf8)) {
  7885. rejects.push_back(tok);
  7886. }
  7887. } else if (llama_grammar_match_char(stack_pos, *tok.code_points).first) {
  7888. next_candidates.push_back({ tok.index, tok.code_points + 1, tok.partial_utf8 });
  7889. } else {
  7890. rejects.push_back(tok);
  7891. }
  7892. }
  7893. const auto * stack_pos_after = llama_grammar_match_char(stack_pos, 0).second;
  7894. // update top of stack to next element, if any
  7895. std::vector<const llama_grammar_element *> stack_after(stack.begin(), stack.end() - 1);
  7896. if (!llama_grammar_is_end_of_sequence(stack_pos_after)) {
  7897. stack_after.push_back(stack_pos_after);
  7898. }
  7899. std::vector<std::vector<const llama_grammar_element *>> next_stacks;
  7900. llama_grammar_advance_stack(rules, stack_after, next_stacks);
  7901. auto next_rejects = llama_grammar_reject_candidates(rules, next_stacks, next_candidates);
  7902. for (const auto & tok : next_rejects) {
  7903. rejects.push_back({ tok.index, tok.code_points - 1, tok.partial_utf8 });
  7904. }
  7905. return rejects;
  7906. }
  7907. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  7908. const std::vector<std::vector<llama_grammar_element>> & rules,
  7909. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  7910. const std::vector<llama_grammar_candidate> & candidates) {
  7911. GGML_ASSERT(!stacks.empty()); // REVIEW
  7912. if (candidates.empty()) {
  7913. return std::vector<llama_grammar_candidate>();
  7914. }
  7915. auto rejects = llama_grammar_reject_candidates_for_stack(rules, stacks.front(), candidates);
  7916. for (size_t i = 1, size = stacks.size(); i < size; ++i) {
  7917. rejects = llama_grammar_reject_candidates_for_stack(rules, stacks[i], rejects);
  7918. }
  7919. return rejects;
  7920. }
  7921. //
  7922. // grammar - external
  7923. //
  7924. struct llama_grammar * llama_grammar_init(
  7925. const llama_grammar_element ** rules,
  7926. size_t n_rules,
  7927. size_t start_rule_index) {
  7928. const llama_grammar_element * pos;
  7929. // copy rule definitions into vectors
  7930. std::vector<std::vector<llama_grammar_element>> vec_rules(n_rules);
  7931. for (size_t i = 0; i < n_rules; i++) {
  7932. for (pos = rules[i]; pos->type != LLAMA_GRETYPE_END; pos++) {
  7933. vec_rules[i].push_back(*pos);
  7934. }
  7935. vec_rules[i].push_back({LLAMA_GRETYPE_END, 0});
  7936. }
  7937. // loop over alternates of start rule to build initial stacks
  7938. std::vector<std::vector<const llama_grammar_element *>> stacks;
  7939. pos = rules[start_rule_index];
  7940. do {
  7941. std::vector<const llama_grammar_element *> stack;
  7942. if (!llama_grammar_is_end_of_sequence(pos)) {
  7943. // if alternate is nonempty, add to stack
  7944. stack.push_back(pos);
  7945. }
  7946. llama_grammar_advance_stack(vec_rules, stack, stacks);
  7947. while (!llama_grammar_is_end_of_sequence(pos)) {
  7948. // scan to end of alternate def
  7949. pos++;
  7950. }
  7951. if (pos->type == LLAMA_GRETYPE_ALT) {
  7952. // there's another alternate def of this rule to process
  7953. pos++;
  7954. } else {
  7955. break;
  7956. }
  7957. } while (true);
  7958. return new llama_grammar{ std::move(vec_rules), std::move(stacks), {} };
  7959. }
  7960. void llama_grammar_free(struct llama_grammar * grammar) {
  7961. delete grammar;
  7962. }
  7963. struct llama_grammar * llama_grammar_copy(const struct llama_grammar * grammar) {
  7964. llama_grammar * result = new llama_grammar{ grammar->rules, grammar->stacks, grammar->partial_utf8 };
  7965. // redirect elements in stacks to point to new rules
  7966. for (size_t is = 0; is < result->stacks.size(); is++) {
  7967. for (size_t ie = 0; ie < result->stacks[is].size(); ie++) {
  7968. for (size_t ir0 = 0; ir0 < grammar->rules.size(); ir0++) {
  7969. for (size_t ir1 = 0; ir1 < grammar->rules[ir0].size(); ir1++) {
  7970. if (grammar->stacks[is][ie] == &grammar->rules[ir0][ir1]) {
  7971. result->stacks[is][ie] = &result->rules[ir0][ir1];
  7972. }
  7973. }
  7974. }
  7975. }
  7976. }
  7977. return result;
  7978. }
  7979. //
  7980. // sampling
  7981. //
  7982. void llama_set_rng_seed(struct llama_context * ctx, uint32_t seed) {
  7983. if (seed == LLAMA_DEFAULT_SEED) {
  7984. seed = time(NULL);
  7985. }
  7986. ctx->rng.seed(seed);
  7987. }
  7988. void llama_sample_softmax(struct llama_context * ctx, llama_token_data_array * candidates) {
  7989. GGML_ASSERT(candidates->size > 0);
  7990. const int64_t t_start_sample_us = ggml_time_us();
  7991. // Sort the logits in descending order
  7992. if (!candidates->sorted) {
  7993. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  7994. return a.logit > b.logit;
  7995. });
  7996. candidates->sorted = true;
  7997. }
  7998. float max_l = candidates->data[0].logit;
  7999. float cum_sum = 0.0f;
  8000. for (size_t i = 0; i < candidates->size; ++i) {
  8001. float p = expf(candidates->data[i].logit - max_l);
  8002. candidates->data[i].p = p;
  8003. cum_sum += p;
  8004. }
  8005. for (size_t i = 0; i < candidates->size; ++i) {
  8006. candidates->data[i].p /= cum_sum;
  8007. }
  8008. if (ctx) {
  8009. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8010. }
  8011. }
  8012. void llama_sample_top_k(struct llama_context * ctx, llama_token_data_array * candidates, int32_t k, size_t min_keep) {
  8013. // TODO: move bucket sort to separate function so that top_p/tail_free/typical/softmax first is equally fast
  8014. // if (k >= (int32_t)candidates->size) {
  8015. // return;
  8016. // }
  8017. const int64_t t_start_sample_us = ggml_time_us();
  8018. if (k <= 0) {
  8019. k = candidates->size;
  8020. }
  8021. k = std::max(k, (int) min_keep);
  8022. k = std::min(k, (int) candidates->size);
  8023. // Sort scores in descending order
  8024. if (!candidates->sorted) {
  8025. auto comp = [](const llama_token_data & a, const llama_token_data & b) {
  8026. return a.logit > b.logit;
  8027. };
  8028. if (k <= 128) {
  8029. std::partial_sort(candidates->data, candidates->data + k, candidates->data + candidates->size, comp);
  8030. } else {
  8031. constexpr int nbuckets = 128;
  8032. constexpr float bucket_low = -10.0f;
  8033. constexpr float bucket_high = 10.0f;
  8034. constexpr float bucket_scale = nbuckets/(bucket_high - bucket_low);
  8035. constexpr float bucker_inter = -bucket_low * bucket_scale;
  8036. std::vector<int> bucket_idx(candidates->size);
  8037. std::vector<int> histo(nbuckets, 0);
  8038. for (int i = 0; i < (int)candidates->size; ++i) {
  8039. const float val = candidates->data[i].logit;
  8040. int ib = int(bucket_scale * val + bucker_inter); //nbuckets * (val - bucket_low) / (bucket_high - bucket_low);
  8041. ib = std::max(0, std::min(nbuckets-1, ib));
  8042. bucket_idx[i] = ib;
  8043. ++histo[ib];
  8044. }
  8045. int nhave = 0;
  8046. int ib = nbuckets - 1;
  8047. for ( ; ib >= 0; --ib) {
  8048. nhave += histo[ib];
  8049. if (nhave >= k) break;
  8050. }
  8051. std::vector<llama_token_data> tmp_tokens(nhave);
  8052. auto ptr = tmp_tokens.data();
  8053. std::vector<llama_token_data*> bucket_ptrs;
  8054. bucket_ptrs.reserve(nbuckets - ib);
  8055. for (int j = nbuckets - 1; j >= ib; --j) {
  8056. bucket_ptrs.push_back(ptr);
  8057. ptr += histo[j];
  8058. }
  8059. for (int i = 0; i < (int)candidates->size; ++i) {
  8060. int j = bucket_idx[i];
  8061. if (j >= ib) {
  8062. *bucket_ptrs[nbuckets-1-j]++ = candidates->data[i];
  8063. }
  8064. }
  8065. ptr = tmp_tokens.data();
  8066. int ndone = 0;
  8067. for (int j = nbuckets-1; j > ib; --j) {
  8068. std::sort(ptr, ptr + histo[j], comp);
  8069. ptr += histo[j];
  8070. ndone += histo[j];
  8071. }
  8072. std::partial_sort(ptr, ptr + k - ndone, ptr + histo[ib], comp);
  8073. std::memcpy(candidates->data, tmp_tokens.data(), k*sizeof(llama_token_data));
  8074. }
  8075. candidates->sorted = true;
  8076. }
  8077. candidates->size = k;
  8078. if (ctx) {
  8079. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8080. }
  8081. }
  8082. void llama_sample_top_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  8083. if (p >= 1.0f) {
  8084. return;
  8085. }
  8086. llama_sample_softmax(ctx, candidates);
  8087. const int64_t t_start_sample_us = ggml_time_us();
  8088. // Compute the cumulative probabilities
  8089. float cum_sum = 0.0f;
  8090. size_t last_idx = candidates->size;
  8091. for (size_t i = 0; i < candidates->size; ++i) {
  8092. cum_sum += candidates->data[i].p;
  8093. // Check if the running sum is at least p or if we have kept at least min_keep tokens
  8094. // we set the last index to i+1 to indicate that the current iterate should be included in the set
  8095. if (cum_sum >= p && i + 1 >= min_keep) {
  8096. last_idx = i + 1;
  8097. break;
  8098. }
  8099. }
  8100. // Resize the output vector to keep only the top-p tokens
  8101. candidates->size = last_idx;
  8102. if (ctx) {
  8103. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8104. }
  8105. }
  8106. void llama_sample_min_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  8107. if (p <= 0.0f || !candidates->size) {
  8108. return;
  8109. }
  8110. const int64_t t_start_sample_us = ggml_time_us();
  8111. bool min_p_applied = false;
  8112. // if the candidates aren't sorted, try the unsorted implementation first
  8113. if (!candidates->sorted) {
  8114. std::vector<llama_token_data> filtered_tokens;
  8115. float max_logit = -FLT_MAX;
  8116. for (size_t i = 0; i < candidates->size; ++i) {
  8117. max_logit = std::max(max_logit, candidates->data[i].logit);
  8118. }
  8119. const float min_logit = max_logit + logf(p); // min logit for p_i >= p * p_max
  8120. for (size_t i = 0; i < candidates->size; ++i) {
  8121. if (candidates->data[i].logit >= min_logit) {
  8122. filtered_tokens.push_back(candidates->data[i]);
  8123. }
  8124. }
  8125. // if we have enough values the operation was a success
  8126. if (filtered_tokens.size() >= min_keep) {
  8127. memcpy(candidates->data, filtered_tokens.data(), filtered_tokens.size()*sizeof(llama_token_data));
  8128. candidates->size = filtered_tokens.size();
  8129. min_p_applied = true;
  8130. }
  8131. }
  8132. // if the candidates are sorted or the unsorted implementation failed, use this implementation
  8133. if (!min_p_applied) {
  8134. // Sort the logits in descending order
  8135. if (!candidates->sorted) {
  8136. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  8137. return a.logit > b.logit;
  8138. });
  8139. candidates->sorted = true;
  8140. }
  8141. const float min_logit = candidates->data[0].logit + logf(p); // min logit for p_i >= p * p_max
  8142. size_t i = 1; // first token always matches
  8143. for (; i < candidates->size; ++i) {
  8144. if (candidates->data[i].logit < min_logit && i >= min_keep) {
  8145. break; // prob too small
  8146. }
  8147. }
  8148. // Resize the output vector to keep only the matching tokens
  8149. candidates->size = i;
  8150. }
  8151. if (ctx) {
  8152. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8153. }
  8154. }
  8155. void llama_sample_tail_free(struct llama_context * ctx, llama_token_data_array * candidates, float z, size_t min_keep) {
  8156. if (z >= 1.0f || candidates->size <= 2) {
  8157. return;
  8158. }
  8159. llama_sample_softmax(nullptr, candidates);
  8160. const int64_t t_start_sample_us = ggml_time_us();
  8161. // Compute the first and second derivatives
  8162. std::vector<float> first_derivatives(candidates->size - 1);
  8163. std::vector<float> second_derivatives(candidates->size - 2);
  8164. for (size_t i = 0; i < first_derivatives.size(); ++i) {
  8165. first_derivatives[i] = candidates->data[i].p - candidates->data[i + 1].p;
  8166. }
  8167. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  8168. second_derivatives[i] = first_derivatives[i] - first_derivatives[i + 1];
  8169. }
  8170. // Calculate absolute value of second derivatives
  8171. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  8172. second_derivatives[i] = std::abs(second_derivatives[i]);
  8173. }
  8174. // Normalize the second derivatives
  8175. {
  8176. const float second_derivatives_sum = std::accumulate(second_derivatives.begin(), second_derivatives.end(), 0.0f);
  8177. if (second_derivatives_sum > 1e-6f) {
  8178. for (float & value : second_derivatives) {
  8179. value /= second_derivatives_sum;
  8180. }
  8181. } else {
  8182. for (float & value : second_derivatives) {
  8183. value = 1.0f / second_derivatives.size();
  8184. }
  8185. }
  8186. }
  8187. float cum_sum = 0.0f;
  8188. size_t last_idx = candidates->size;
  8189. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  8190. cum_sum += second_derivatives[i];
  8191. // Check if the running sum is greater than z or if we have kept at least min_keep tokens
  8192. if (cum_sum > z && i >= min_keep) {
  8193. last_idx = i;
  8194. break;
  8195. }
  8196. }
  8197. // Resize the output vector to keep only the tokens above the tail location
  8198. candidates->size = last_idx;
  8199. if (ctx) {
  8200. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8201. }
  8202. }
  8203. void llama_sample_typical(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  8204. // Reference implementation:
  8205. // https://github.com/huggingface/transformers/compare/main...cimeister:typical-sampling:typical-pr
  8206. if (p >= 1.0f) {
  8207. return;
  8208. }
  8209. // Compute the softmax of logits and calculate entropy
  8210. llama_sample_softmax(nullptr, candidates);
  8211. const int64_t t_start_sample_us = ggml_time_us();
  8212. float entropy = 0.0f;
  8213. for (size_t i = 0; i < candidates->size; ++i) {
  8214. entropy += -candidates->data[i].p * logf(candidates->data[i].p);
  8215. }
  8216. // Compute the absolute difference between negative log probability and entropy for each candidate
  8217. std::vector<float> shifted_scores;
  8218. for (size_t i = 0; i < candidates->size; ++i) {
  8219. float shifted_score = fabsf(-logf(candidates->data[i].p) - entropy);
  8220. shifted_scores.push_back(shifted_score);
  8221. }
  8222. // Sort tokens based on the shifted_scores and their corresponding indices
  8223. std::vector<size_t> indices(candidates->size);
  8224. std::iota(indices.begin(), indices.end(), 0);
  8225. std::sort(indices.begin(), indices.end(), [&](size_t a, size_t b) {
  8226. return shifted_scores[a] < shifted_scores[b];
  8227. });
  8228. // Compute the cumulative probabilities
  8229. float cum_sum = 0.0f;
  8230. size_t last_idx = indices.size();
  8231. for (size_t i = 0; i < indices.size(); ++i) {
  8232. size_t idx = indices[i];
  8233. cum_sum += candidates->data[idx].p;
  8234. // Check if the running sum is greater than typical or if we have kept at least min_keep tokens
  8235. if (cum_sum > p && i >= min_keep - 1) {
  8236. last_idx = i + 1;
  8237. break;
  8238. }
  8239. }
  8240. // Resize the output vector to keep only the locally typical tokens
  8241. std::vector<llama_token_data> new_candidates;
  8242. for (size_t i = 0; i < last_idx; ++i) {
  8243. size_t idx = indices[i];
  8244. new_candidates.push_back(candidates->data[idx]);
  8245. }
  8246. // Replace the data in candidates with the new_candidates data
  8247. std::copy(new_candidates.begin(), new_candidates.end(), candidates->data);
  8248. candidates->size = new_candidates.size();
  8249. candidates->sorted = false;
  8250. if (ctx) {
  8251. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8252. }
  8253. }
  8254. void llama_sample_entropy(struct llama_context * ctx, llama_token_data_array * candidates_p, float min_temp, float max_temp, float exponent_val) {
  8255. const int64_t t_start_sample_us = ggml_time_us();
  8256. // no need to do anything if there is only one (or zero) candidates
  8257. if(candidates_p->size <= 1) {
  8258. return;
  8259. }
  8260. // Calculate maximum possible entropy
  8261. float max_entropy = -logf(1.0f / candidates_p->size);
  8262. llama_sample_softmax(nullptr, candidates_p);
  8263. // Calculate entropy of the softmax probabilities
  8264. float entropy = 0.0f;
  8265. for (size_t i = 0; i < candidates_p->size; ++i) {
  8266. float prob = candidates_p->data[i].p;
  8267. if (prob > 0.0f) { // Ensure no log(0)
  8268. entropy -= prob * logf(prob);
  8269. }
  8270. }
  8271. // Normalize the entropy (max_entropy cannot be 0 here because we checked candidates_p->size != 1 above)
  8272. float normalized_entropy = entropy / max_entropy;
  8273. // Map the normalized entropy to the desired temperature range using the power function
  8274. float dyn_temp = min_temp + (max_temp - min_temp) * powf(normalized_entropy, exponent_val);
  8275. #ifdef DEBUG
  8276. LLAMA_LOG_INFO("Your text maxtemp value is: %f\n", max_temp);
  8277. LLAMA_LOG_INFO("Entropy: %f\n", entropy);
  8278. LLAMA_LOG_INFO("Max Possible Entropy: %f\n", max_entropy);
  8279. LLAMA_LOG_INFO("Normalized Entropy: %f\n", normalized_entropy);
  8280. LLAMA_LOG_INFO("Exponent: %f\n", exponent_val);
  8281. LLAMA_LOG_INFO("Dynamic Temperature (dyn_temp): %f\n", dyn_temp);
  8282. #endif
  8283. // Apply the dynamically calculated temperature scaling
  8284. for (size_t i = 0; i < candidates_p->size; ++i) {
  8285. candidates_p->data[i].logit /= dyn_temp;
  8286. }
  8287. // Re-compute softmax probabilities after scaling logits with dynamic temperature
  8288. double max_l_double = candidates_p->data[0].logit;
  8289. double cum_sum_double = 0.0;
  8290. for (size_t i = 0; i < candidates_p->size; ++i) {
  8291. double p = exp(candidates_p->data[i].logit - max_l_double);
  8292. candidates_p->data[i].p = p; // Store the scaled probability
  8293. cum_sum_double += p;
  8294. }
  8295. for (size_t i = 0; i < candidates_p->size; ++i) {
  8296. candidates_p->data[i].p /= cum_sum_double; // Re-normalize the probabilities
  8297. }
  8298. #ifdef DEBUG
  8299. // Print the updated top 25 probabilities after temperature scaling
  8300. LLAMA_LOG_INFO("\nUpdated Top 25 Probabilities After Dynamic Temperature Scaling (in percentages):\n");
  8301. for (size_t i = 0; i < 25 && i < candidates_p->size; ++i) {
  8302. LLAMA_LOG_INFO("Token %zu: %f%%\n", i + 1, candidates_p->data[i].p * 100.0f);
  8303. }
  8304. #endif
  8305. if (ctx) {
  8306. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8307. }
  8308. }
  8309. void llama_sample_temp(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  8310. const int64_t t_start_sample_us = ggml_time_us();
  8311. for (size_t i = 0; i < candidates_p->size; ++i) {
  8312. candidates_p->data[i].logit /= temp;
  8313. }
  8314. if (ctx) {
  8315. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8316. }
  8317. }
  8318. void llama_sample_temperature(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  8319. llama_sample_temp(ctx, candidates_p, temp);
  8320. }
  8321. void llama_sample_repetition_penalties(
  8322. struct llama_context * ctx,
  8323. llama_token_data_array * candidates,
  8324. const llama_token * last_tokens,
  8325. size_t penalty_last_n,
  8326. float penalty_repeat,
  8327. float penalty_freq,
  8328. float penalty_present) {
  8329. if (penalty_last_n == 0 || (penalty_repeat == 1.0f && penalty_freq == 0.0f && penalty_present == 0.0f)) {
  8330. return;
  8331. }
  8332. const int64_t t_start_sample_us = ggml_time_us();
  8333. // Create a frequency map to count occurrences of each token in last_tokens
  8334. std::unordered_map<llama_token, int> token_count;
  8335. for (size_t i = 0; i < penalty_last_n; ++i) {
  8336. token_count[last_tokens[i]]++;
  8337. }
  8338. // Apply frequency and presence penalties to the candidates
  8339. for (size_t i = 0; i < candidates->size; ++i) {
  8340. const auto token_iter = token_count.find(candidates->data[i].id);
  8341. if (token_iter == token_count.end()) {
  8342. continue;
  8343. }
  8344. const int count = token_iter->second;
  8345. // 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.
  8346. // This is common fix for this problem, which is to multiply by the penalty instead of dividing.
  8347. if (candidates->data[i].logit <= 0) {
  8348. candidates->data[i].logit *= penalty_repeat;
  8349. } else {
  8350. candidates->data[i].logit /= penalty_repeat;
  8351. }
  8352. candidates->data[i].logit -= float(count) * penalty_freq + float(count > 0) * penalty_present;
  8353. }
  8354. candidates->sorted = false;
  8355. if (ctx) {
  8356. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8357. }
  8358. }
  8359. void llama_sample_grammar(struct llama_context * ctx, llama_token_data_array * candidates, const struct llama_grammar * grammar) {
  8360. GGML_ASSERT(ctx);
  8361. const int64_t t_start_sample_us = ggml_time_us();
  8362. bool allow_eos = false;
  8363. for (const auto & stack : grammar->stacks) {
  8364. if (stack.empty()) {
  8365. allow_eos = true;
  8366. break;
  8367. }
  8368. }
  8369. const llama_token eos = llama_token_eos(&ctx->model);
  8370. std::vector<std::pair<std::vector<uint32_t>, llama_partial_utf8>> candidates_decoded;
  8371. candidates_decoded.reserve(candidates->size);
  8372. std::vector<llama_grammar_candidate> candidates_grammar;
  8373. candidates_grammar.reserve(candidates->size);
  8374. for (size_t i = 0; i < candidates->size; ++i) {
  8375. const llama_token id = candidates->data[i].id;
  8376. const std::string piece = llama_token_to_piece(ctx, id);
  8377. if (id == eos) {
  8378. if (!allow_eos) {
  8379. candidates->data[i].logit = -INFINITY;
  8380. }
  8381. } else if (piece.empty() || piece[0] == 0) {
  8382. candidates->data[i].logit = -INFINITY;
  8383. } else {
  8384. candidates_decoded.push_back(decode_utf8(piece, grammar->partial_utf8));
  8385. candidates_grammar.push_back({ i, candidates_decoded.back().first.data(), candidates_decoded.back().second });
  8386. }
  8387. }
  8388. const auto rejects = llama_grammar_reject_candidates(grammar->rules, grammar->stacks, candidates_grammar);
  8389. for (const auto & reject : rejects) {
  8390. candidates->data[reject.index].logit = -INFINITY;
  8391. }
  8392. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8393. }
  8394. static void llama_log_softmax(float * array, size_t size) {
  8395. float max_l = *std::max_element(array, array + size);
  8396. float sum = 0.f;
  8397. for (size_t i = 0; i < size; ++i) {
  8398. float p = expf(array[i] - max_l);
  8399. sum += p;
  8400. array[i] = p;
  8401. }
  8402. for (size_t i = 0; i < size; ++i) {
  8403. array[i] = logf(array[i] / sum);
  8404. }
  8405. }
  8406. void llama_sample_apply_guidance(
  8407. struct llama_context * ctx,
  8408. float * logits,
  8409. float * logits_guidance,
  8410. float scale) {
  8411. GGML_ASSERT(ctx);
  8412. const auto t_start_sample_us = ggml_time_us();
  8413. const auto n_vocab = llama_n_vocab(llama_get_model(ctx));
  8414. llama_log_softmax(logits, n_vocab);
  8415. llama_log_softmax(logits_guidance, n_vocab);
  8416. for (int i = 0; i < n_vocab; ++i) {
  8417. auto & l = logits[i];
  8418. const auto & g = logits_guidance[i];
  8419. l = scale * (l - g) + g;
  8420. }
  8421. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8422. }
  8423. void llama_sample_classifier_free_guidance(
  8424. struct llama_context * ctx,
  8425. llama_token_data_array * candidates,
  8426. struct llama_context * guidance_ctx,
  8427. float scale) {
  8428. GGML_ASSERT(ctx);
  8429. int64_t t_start_sample_us;
  8430. t_start_sample_us = ggml_time_us();
  8431. const size_t n_vocab = llama_n_vocab(llama_get_model(ctx));
  8432. GGML_ASSERT(n_vocab == candidates->size);
  8433. GGML_ASSERT(!candidates->sorted);
  8434. std::vector<float> logits_base(n_vocab);
  8435. for (size_t i = 0; i < n_vocab; ++i) {
  8436. logits_base[i] = candidates->data[i].logit;
  8437. }
  8438. float * logits_guidance = llama_get_logits(guidance_ctx);
  8439. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8440. llama_sample_apply_guidance(ctx, logits_base.data(), logits_guidance, scale);
  8441. t_start_sample_us = ggml_time_us();
  8442. for (size_t i = 0; i < n_vocab; ++i) {
  8443. candidates->data[i].logit = logits_base[i];
  8444. }
  8445. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8446. }
  8447. llama_token llama_sample_token_mirostat(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, int32_t m, float * mu) {
  8448. GGML_ASSERT(ctx);
  8449. auto N = float(llama_n_vocab(llama_get_model(ctx)));
  8450. int64_t t_start_sample_us;
  8451. t_start_sample_us = ggml_time_us();
  8452. llama_sample_softmax(nullptr, candidates);
  8453. // Estimate s_hat using the most probable m tokens
  8454. float s_hat = 0.0;
  8455. float sum_ti_bi = 0.0;
  8456. float sum_ti_sq = 0.0;
  8457. for (size_t i = 0; i < size_t(m - 1) && i < candidates->size - 1; ++i) {
  8458. float t_i = logf(float(i + 2) / float(i + 1));
  8459. float b_i = logf(candidates->data[i].p / candidates->data[i + 1].p);
  8460. sum_ti_bi += t_i * b_i;
  8461. sum_ti_sq += t_i * t_i;
  8462. }
  8463. s_hat = sum_ti_bi / sum_ti_sq;
  8464. // Compute k from the estimated s_hat and target surprise value
  8465. float epsilon_hat = s_hat - 1;
  8466. float k = powf((epsilon_hat * powf(2, *mu)) / (1 - powf(N, -epsilon_hat)), 1 / s_hat);
  8467. // Sample the next word X using top-k sampling
  8468. llama_sample_top_k(nullptr, candidates, int(k), 1);
  8469. if (ctx) {
  8470. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8471. }
  8472. llama_token X = llama_sample_token(ctx, candidates);
  8473. t_start_sample_us = ggml_time_us();
  8474. // Compute error as the difference between observed surprise and target surprise value
  8475. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  8476. return candidate.id == X;
  8477. }));
  8478. float observed_surprise = -log2f(candidates->data[X_idx].p);
  8479. float e = observed_surprise - tau;
  8480. // Update mu using the learning rate and error
  8481. *mu = *mu - eta * e;
  8482. if (ctx) {
  8483. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8484. }
  8485. return X;
  8486. }
  8487. llama_token llama_sample_token_mirostat_v2(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, float * mu) {
  8488. int64_t t_start_sample_us;
  8489. t_start_sample_us = ggml_time_us();
  8490. llama_sample_softmax(ctx, candidates);
  8491. // Truncate the words with surprise values greater than mu
  8492. candidates->size = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  8493. return -log2f(candidate.p) > *mu;
  8494. }));
  8495. if (candidates->size == 0) {
  8496. candidates->size = 1;
  8497. }
  8498. if (ctx) {
  8499. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8500. }
  8501. // Normalize the probabilities of the remaining words
  8502. llama_sample_softmax(ctx, candidates);
  8503. // Sample the next word X from the remaining words
  8504. llama_token X = llama_sample_token(ctx, candidates);
  8505. t_start_sample_us = ggml_time_us();
  8506. // Compute error as the difference between observed surprise and target surprise value
  8507. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  8508. return candidate.id == X;
  8509. }));
  8510. float observed_surprise = -log2f(candidates->data[X_idx].p);
  8511. float e = observed_surprise - tau;
  8512. // Update mu using the learning rate and error
  8513. *mu = *mu - eta * e;
  8514. if (ctx) {
  8515. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8516. }
  8517. return X;
  8518. }
  8519. llama_token llama_sample_token_greedy(struct llama_context * ctx, llama_token_data_array * candidates) {
  8520. const int64_t t_start_sample_us = ggml_time_us();
  8521. // Find max element
  8522. auto * max_iter = std::max_element(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  8523. return a.logit < b.logit;
  8524. });
  8525. llama_token result = max_iter->id;
  8526. if (ctx) {
  8527. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8528. ctx->n_sample++;
  8529. }
  8530. return result;
  8531. }
  8532. llama_token llama_sample_token(struct llama_context * ctx, llama_token_data_array * candidates) {
  8533. GGML_ASSERT(ctx);
  8534. const int64_t t_start_sample_us = ggml_time_us();
  8535. llama_sample_softmax(nullptr, candidates);
  8536. std::vector<float> probs;
  8537. probs.reserve(candidates->size);
  8538. for (size_t i = 0; i < candidates->size; ++i) {
  8539. probs.push_back(candidates->data[i].p);
  8540. }
  8541. std::discrete_distribution<> dist(probs.begin(), probs.end());
  8542. auto & rng = ctx->rng;
  8543. int idx = dist(rng);
  8544. llama_token result = candidates->data[idx].id;
  8545. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8546. ctx->n_sample++;
  8547. return result;
  8548. }
  8549. void llama_grammar_accept_token(struct llama_context * ctx, struct llama_grammar * grammar, llama_token token) {
  8550. const int64_t t_start_sample_us = ggml_time_us();
  8551. if (token == llama_token_eos(&ctx->model)) {
  8552. for (const auto & stack : grammar->stacks) {
  8553. if (stack.empty()) {
  8554. return;
  8555. }
  8556. }
  8557. GGML_ASSERT(false);
  8558. }
  8559. const std::string piece = llama_token_to_piece(ctx, token);
  8560. // Note terminating 0 in decoded string
  8561. const auto decoded = decode_utf8(piece, grammar->partial_utf8);
  8562. const auto & code_points = decoded.first;
  8563. for (auto it = code_points.begin(), end = code_points.end() - 1; it != end; ++it) {
  8564. grammar->stacks = llama_grammar_accept(grammar->rules, grammar->stacks, *it);
  8565. }
  8566. grammar->partial_utf8 = decoded.second;
  8567. GGML_ASSERT(!grammar->stacks.empty());
  8568. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8569. }
  8570. //
  8571. // Beam search
  8572. //
  8573. struct llama_beam {
  8574. std::vector<llama_token> tokens;
  8575. float p; // Cumulative beam probability (renormalized relative to all beams)
  8576. bool eob; // Initialize end-of-beam to false. Callback sets this to true.
  8577. // Sort beams by probability. In case of ties, prefer beams at eob.
  8578. bool operator<(const llama_beam & rhs) const {
  8579. return std::make_pair(p, eob) < std::make_pair(rhs.p, rhs.eob);
  8580. }
  8581. // Shift off first n tokens and discard them.
  8582. void shift_tokens(const size_t n) {
  8583. if (n) {
  8584. std::copy(tokens.begin() + n, tokens.end(), tokens.begin());
  8585. tokens.resize(tokens.size() - n);
  8586. }
  8587. }
  8588. llama_beam_view view() const { return {tokens.data(), tokens.size(), p, eob}; }
  8589. };
  8590. // A struct for calculating logit-related info.
  8591. struct llama_logit_info {
  8592. const float * const logits;
  8593. const int n_vocab;
  8594. const float max_l;
  8595. const float normalizer;
  8596. struct sum_exp {
  8597. float max_l;
  8598. float operator()(float sum, float l) const { return sum + std::exp(l - max_l); }
  8599. };
  8600. llama_logit_info(llama_context * ctx)
  8601. : logits(llama_get_logits(ctx))
  8602. , n_vocab(llama_n_vocab(llama_get_model(ctx)))
  8603. , max_l(*std::max_element(logits, logits + n_vocab))
  8604. , normalizer(1.0f / std::accumulate(logits, logits + n_vocab, 0.0f, sum_exp{max_l}))
  8605. { }
  8606. llama_token_data get_token_data(const llama_token token_id) const {
  8607. constexpr auto p = std::numeric_limits<float>::quiet_NaN(); // never used
  8608. return {token_id, logits[token_id], p};
  8609. }
  8610. // Return top k token_data by logit.
  8611. std::vector<llama_token_data> top_k(size_t k) {
  8612. std::vector<llama_token_data> min_heap; // min-heap by logit
  8613. const llama_token k_min = std::min(static_cast<llama_token>(k), n_vocab);
  8614. min_heap.reserve(k_min);
  8615. for (llama_token token_id = 0 ; token_id < k_min ; ++token_id) {
  8616. min_heap.push_back(get_token_data(token_id));
  8617. }
  8618. auto comp = [](const llama_token_data & a, const llama_token_data & b) { return a.logit > b.logit; };
  8619. std::make_heap(min_heap.begin(), min_heap.end(), comp);
  8620. for (llama_token token_id = k_min ; token_id < n_vocab ; ++token_id) {
  8621. if (min_heap.front().logit < logits[token_id]) {
  8622. std::pop_heap(min_heap.begin(), min_heap.end(), comp);
  8623. min_heap.back().id = token_id;
  8624. min_heap.back().logit = logits[token_id];
  8625. std::push_heap(min_heap.begin(), min_heap.end(), comp);
  8626. }
  8627. }
  8628. return min_heap;
  8629. }
  8630. float probability_from_logit(float logit) const {
  8631. return normalizer * std::exp(logit - max_l);
  8632. }
  8633. };
  8634. struct llama_beam_search_data {
  8635. llama_context * ctx;
  8636. size_t n_beams;
  8637. int n_past;
  8638. int n_predict;
  8639. std::vector<llama_beam> beams;
  8640. std::vector<llama_beam> next_beams;
  8641. // Re-calculated on each loop iteration
  8642. size_t common_prefix_length;
  8643. // Used to communicate to/from callback on beams state.
  8644. std::vector<llama_beam_view> beam_views;
  8645. llama_beam_search_data(llama_context * ctx, size_t n_beams, int n_past, int n_predict)
  8646. : ctx(ctx)
  8647. , n_beams(n_beams)
  8648. , n_past(n_past)
  8649. , n_predict(n_predict)
  8650. , beam_views(n_beams) {
  8651. beams.reserve(n_beams);
  8652. next_beams.reserve(n_beams);
  8653. }
  8654. // Collapse beams to a single beam given by index.
  8655. void collapse_beams(const size_t beam_idx) {
  8656. if (0u < beam_idx) {
  8657. std::swap(beams[0], beams[beam_idx]);
  8658. }
  8659. beams.resize(1);
  8660. }
  8661. // Min-heaps are used to efficiently collect the top-k elements (k=n_beams).
  8662. // The repetitive patterns below reflect the 2 stages of heaps:
  8663. // * Gather elements until the vector is full, then call std::make_heap() on it.
  8664. // * If the heap is full and a new element is found that should be included, pop the
  8665. // least element to the back(), replace it with the new, then push it into the heap.
  8666. void fill_next_beams_by_top_probabilities(llama_beam & beam) {
  8667. // Min-heaps use a greater-than comparator.
  8668. const auto comp = [](const llama_beam & a, const llama_beam & b) { return a.p > b.p; };
  8669. if (beam.eob) {
  8670. // beam is at end-of-sentence, so just copy it to next_beams if its probability is high enough.
  8671. if (next_beams.size() < n_beams) {
  8672. next_beams.push_back(std::move(beam));
  8673. if (next_beams.size() == n_beams) {
  8674. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  8675. }
  8676. } else if (next_beams.front().p < beam.p) {
  8677. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  8678. next_beams.back() = std::move(beam);
  8679. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  8680. }
  8681. } else {
  8682. // beam is not at end-of-sentence, so branch with next top_k tokens.
  8683. if (!beam.tokens.empty()) {
  8684. llama_decode(ctx, llama_batch_get_one(beam.tokens.data(), beam.tokens.size(), n_past, 0));
  8685. }
  8686. llama_logit_info logit_info(ctx);
  8687. std::vector<llama_token_data> next_tokens = logit_info.top_k(n_beams);
  8688. size_t i=0;
  8689. if (next_beams.size() < n_beams) {
  8690. for (; next_beams.size() < n_beams ; ++i) {
  8691. llama_beam next_beam = beam;
  8692. next_beam.tokens.push_back(next_tokens[i].id);
  8693. next_beam.p *= logit_info.probability_from_logit(next_tokens[i].logit);
  8694. next_beams.push_back(std::move(next_beam));
  8695. }
  8696. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  8697. } else {
  8698. for (; next_beams.front().p == 0.0f ; ++i) {
  8699. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  8700. next_beams.back() = beam;
  8701. next_beams.back().tokens.push_back(next_tokens[i].id);
  8702. next_beams.back().p *= logit_info.probability_from_logit(next_tokens[i].logit);
  8703. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  8704. }
  8705. }
  8706. for (; i < n_beams ; ++i) {
  8707. const float next_p = beam.p * logit_info.probability_from_logit(next_tokens[i].logit);
  8708. if (next_beams.front().p < next_p) {
  8709. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  8710. next_beams.back() = beam;
  8711. next_beams.back().tokens.push_back(next_tokens[i].id);
  8712. next_beams.back().p = next_p;
  8713. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  8714. }
  8715. }
  8716. }
  8717. }
  8718. // Find common_prefix_length based on beams.
  8719. // Requires beams is not empty.
  8720. size_t find_common_prefix_length() {
  8721. size_t common_prefix_length = beams[0].tokens.size();
  8722. for (size_t i = 1 ; i < beams.size() ; ++i) {
  8723. common_prefix_length = std::min(common_prefix_length, beams[i].tokens.size());
  8724. for (size_t j = 0 ; j < common_prefix_length ; ++j) {
  8725. if (beams[0].tokens[j] != beams[i].tokens[j]) {
  8726. common_prefix_length = j;
  8727. break;
  8728. }
  8729. }
  8730. }
  8731. return common_prefix_length;
  8732. }
  8733. // Construct beams_state to send back to caller via the callback function.
  8734. // Side effect: set common_prefix_length = find_common_prefix_length();
  8735. llama_beams_state get_beams_state(const bool last_call) {
  8736. for (size_t i = 0 ; i < beams.size() ; ++i) {
  8737. beam_views[i] = beams[i].view();
  8738. }
  8739. common_prefix_length = find_common_prefix_length();
  8740. return {beam_views.data(), beams.size(), common_prefix_length, last_call};
  8741. }
  8742. // Loop:
  8743. // * while i < n_predict, AND
  8744. // * any of the beams have not yet reached end-of-beam (eob), AND
  8745. // * the highest probability beam(s) (plural in case of ties) are not at end-of-sentence
  8746. // (since all other beam probabilities can only decrease)
  8747. void loop(const llama_beam_search_callback_fn_t callback, void * const callback_data) {
  8748. beams.push_back({{}, 1.0f, false}); // Start with one empty beam w/ probability = 1.0 and !eob.
  8749. const auto not_eob = [](const llama_beam & beam) { return !beam.eob; };
  8750. for (int i = 0 ; i < n_predict && std::any_of(beams.begin(),beams.end(),not_eob) &&
  8751. !beams[top_beam_index()].eob ; ++i) {
  8752. callback(callback_data, get_beams_state(false)); // Sets common_prefix_length
  8753. update_beams_from_beam_views(); // Update values (p,eob) that callback may have changed.
  8754. if (common_prefix_length) {
  8755. llama_decode(ctx, llama_batch_get_one(beams[0].tokens.data(), common_prefix_length, n_past, 0));
  8756. n_past += common_prefix_length;
  8757. }
  8758. // Zero-out next_beam probabilities to place them last in following min-heap.
  8759. std::for_each(next_beams.begin(), next_beams.end(), [](llama_beam & beam) { beam.p = 0.0f; });
  8760. for (llama_beam & beam : beams) {
  8761. beam.shift_tokens(common_prefix_length);
  8762. fill_next_beams_by_top_probabilities(beam);
  8763. }
  8764. // next_beams become the beams of next/final iteration. Swap them to re-use memory.
  8765. beams.swap(next_beams);
  8766. renormalize_beam_probabilities(beams);
  8767. }
  8768. collapse_beams(top_beam_index());
  8769. callback(callback_data, get_beams_state(true));
  8770. }
  8771. // As beams grow, the cumulative probabilities decrease.
  8772. // Renormalize them to avoid floating point underflow.
  8773. static void renormalize_beam_probabilities(std::vector<llama_beam> & beams) {
  8774. const auto sum_p = [](float sum, llama_beam & beam) { return sum + beam.p; };
  8775. const float inv_sum = 1.0f / std::accumulate(beams.begin(), beams.end(), 0.0f, sum_p);
  8776. std::for_each(beams.begin(), beams.end(), [=](llama_beam & beam) { beam.p *= inv_sum; });
  8777. }
  8778. // Assumes beams is non-empty. Uses llama_beam::operator<() for ordering.
  8779. size_t top_beam_index() {
  8780. return std::max_element(beams.begin(), beams.end()) - beams.begin();
  8781. }
  8782. // Copy (p,eob) for each beam which may have been changed by the callback.
  8783. void update_beams_from_beam_views() {
  8784. for (size_t i = 0 ; i < beams.size() ; ++i) {
  8785. beams[i].p = beam_views[i].p;
  8786. beams[i].eob = beam_views[i].eob;
  8787. }
  8788. }
  8789. };
  8790. void llama_beam_search(llama_context * ctx,
  8791. llama_beam_search_callback_fn_t callback, void * callback_data,
  8792. size_t n_beams, int n_past, int n_predict) {
  8793. assert(ctx);
  8794. const int64_t t_start_sample_us = ggml_time_us();
  8795. llama_beam_search_data beam_search_data(ctx, n_beams, n_past, n_predict);
  8796. beam_search_data.loop(callback, callback_data);
  8797. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  8798. ctx->n_sample++;
  8799. }
  8800. //
  8801. // quantization
  8802. //
  8803. struct quantize_state_internal {
  8804. const llama_model & model;
  8805. const llama_model_quantize_params * params;
  8806. int n_attention_wv = 0;
  8807. int n_ffn_down = 0;
  8808. int n_ffn_gate = 0;
  8809. int n_ffn_up = 0;
  8810. int i_attention_wv = 0;
  8811. int i_ffn_down = 0;
  8812. int i_ffn_gate = 0;
  8813. int i_ffn_up = 0;
  8814. int n_k_quantized = 0;
  8815. int n_fallback = 0;
  8816. bool has_imatrix = false;
  8817. quantize_state_internal(const llama_model & model, const llama_model_quantize_params * params)
  8818. : model(model)
  8819. , params(params)
  8820. {}
  8821. };
  8822. static void llama_convert_tensor_internal(
  8823. struct ggml_tensor * tensor, std::vector<no_init<float>> & output, std::vector<std::thread> & workers,
  8824. const size_t nelements, const int nthread
  8825. ) {
  8826. if (output.size() < nelements) {
  8827. output.resize(nelements);
  8828. }
  8829. float * f32_output = (float *) output.data();
  8830. ggml_type_traits_t qtype;
  8831. if (ggml_is_quantized(tensor->type)) {
  8832. qtype = ggml_internal_get_type_traits(tensor->type);
  8833. if (qtype.to_float == NULL) {
  8834. throw std::runtime_error(format("type %s unsupported for integer quantization: no dequantization available", ggml_type_name(tensor->type)));
  8835. }
  8836. } else if (tensor->type != GGML_TYPE_F16) {
  8837. throw std::runtime_error(format("cannot dequantize/convert tensor type %s", ggml_type_name(tensor->type)));
  8838. }
  8839. if (nthread < 2) {
  8840. if (tensor->type == GGML_TYPE_F16) {
  8841. ggml_fp16_to_fp32_row((ggml_fp16_t *)tensor->data, f32_output, nelements);
  8842. } else if (ggml_is_quantized(tensor->type)) {
  8843. qtype.to_float(tensor->data, f32_output, nelements);
  8844. } else {
  8845. GGML_ASSERT(false); // unreachable
  8846. }
  8847. return;
  8848. }
  8849. size_t block_size = tensor->type == GGML_TYPE_F16 ? 1 : (size_t)ggml_blck_size(tensor->type);
  8850. size_t block_size_bytes = ggml_type_size(tensor->type);
  8851. GGML_ASSERT(nelements % block_size == 0);
  8852. size_t nblocks = nelements / block_size;
  8853. size_t blocks_per_thread = nblocks / nthread;
  8854. size_t spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count
  8855. size_t in_buff_offs = 0;
  8856. size_t out_buff_offs = 0;
  8857. for (int tnum = 0; tnum < nthread; tnum++) {
  8858. size_t thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread
  8859. size_t thr_elems = thr_blocks * block_size; // number of elements for this thread
  8860. size_t thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread
  8861. auto compute = [qtype] (ggml_type typ, uint8_t * inbuf, float * outbuf, int nels) {
  8862. if (typ == GGML_TYPE_F16) {
  8863. ggml_fp16_to_fp32_row((ggml_fp16_t *)inbuf, outbuf, nels);
  8864. } else {
  8865. qtype.to_float(inbuf, outbuf, nels);
  8866. }
  8867. };
  8868. workers.emplace_back(compute, tensor->type, (uint8_t *) tensor->data + in_buff_offs, f32_output + out_buff_offs, thr_elems);
  8869. in_buff_offs += thr_block_bytes;
  8870. out_buff_offs += thr_elems;
  8871. }
  8872. for (auto & w : workers) { w.join(); }
  8873. workers.clear();
  8874. }
  8875. static ggml_type get_k_quant_type(quantize_state_internal & qs, ggml_type new_type, const ggml_tensor * tensor, llama_ftype ftype) {
  8876. const std::string name = ggml_get_name(tensor);
  8877. // TODO: avoid hardcoded tensor names - use the TN_* constants
  8878. const llm_arch arch = qs.model.arch;
  8879. const auto tn = LLM_TN(arch);
  8880. auto use_more_bits = [](int i_layer, int num_layers) -> bool {
  8881. return i_layer < num_layers/8 || i_layer >= 7*num_layers/8 || (i_layer - num_layers/8)%3 == 2;
  8882. };
  8883. const int n_expert = std::max(1, (int)qs.model.hparams.n_expert);
  8884. auto layer_info = [n_expert] (int i_layer, int n_layer, const char * name) {
  8885. if (n_expert > 1) {
  8886. // Believe it or not, "experts" in the FFN of Mixtral-8x7B are not consecutive, but iccasionally randomly
  8887. // sprinkled in the model. Hence, simply dividing i_ffn_down by n_expert does not work
  8888. // for getting the current layer as I initially thought, and we need to resort to parsing the
  8889. // tensor name.
  8890. n_layer /= n_expert;
  8891. if (sscanf(name, "blk.%d.", &i_layer) != 1) {
  8892. throw std::runtime_error(format("Failed to determine layer for tensor %s", name));
  8893. }
  8894. if (i_layer < 0 || i_layer >= n_layer) {
  8895. throw std::runtime_error(format("Bad layer %d for tensor %s. Must be in [0, %d)", i_layer, name, n_layer));
  8896. }
  8897. }
  8898. return std::make_pair(i_layer, n_layer);
  8899. };
  8900. // for arches that share the same tensor between the token embeddings and the output, we quantize the token embeddings
  8901. // with the quantization of the output tensor
  8902. if (name == tn(LLM_TENSOR_OUTPUT, "weight") ||
  8903. (LLM_TENSOR_NAMES.at(arch).find(LLM_TENSOR_OUTPUT) == LLM_TENSOR_NAMES.at(arch).end() && name == "token_embd.weight")) {
  8904. int nx = tensor->ne[0];
  8905. if (arch == LLM_ARCH_FALCON || nx % QK_K != 0) {
  8906. new_type = GGML_TYPE_Q8_0;
  8907. }
  8908. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  8909. ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) {
  8910. new_type = GGML_TYPE_Q5_K;
  8911. }
  8912. else if (new_type != GGML_TYPE_Q8_0) {
  8913. new_type = GGML_TYPE_Q6_K;
  8914. }
  8915. } else if (name == "token_embd.weight") {
  8916. if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS ||
  8917. ftype == LLAMA_FTYPE_MOSTLY_IQ1_S) {
  8918. new_type = GGML_TYPE_Q2_K;
  8919. }
  8920. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) {
  8921. new_type = GGML_TYPE_IQ3_S;
  8922. }
  8923. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  8924. new_type = GGML_TYPE_IQ3_S;
  8925. }
  8926. } else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S ||
  8927. ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) {
  8928. if (name.find("attn_v.weight") != std::string::npos) {
  8929. if (qs.model.hparams.n_gqa() >= 4 || qs.model.hparams.n_expert >= 4) new_type = GGML_TYPE_Q4_K;
  8930. else new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  8931. ++qs.i_attention_wv;
  8932. }
  8933. else if (qs.model.hparams.n_expert == 8 && name.find("attn_k.weight") != std::string::npos) {
  8934. new_type = GGML_TYPE_Q4_K;
  8935. }
  8936. else if (name.find("ffn_down") != std::string::npos) {
  8937. if (qs.i_ffn_down < qs.n_ffn_down/8) {
  8938. new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K;
  8939. }
  8940. ++qs.i_ffn_down;
  8941. }
  8942. else if (name.find("attn_output.weight") != std::string::npos) {
  8943. if (qs.model.hparams.n_expert == 8) {
  8944. new_type = GGML_TYPE_Q5_K;
  8945. } else {
  8946. if (ftype == LLAMA_FTYPE_MOSTLY_IQ1_S) new_type = GGML_TYPE_IQ2_XXS;
  8947. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) new_type = GGML_TYPE_IQ3_S;
  8948. }
  8949. }
  8950. } else if (name.find("attn_v.weight") != std::string::npos) {
  8951. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) {
  8952. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  8953. }
  8954. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && qs.model.hparams.n_gqa() >= 4) {
  8955. new_type = GGML_TYPE_Q4_K;
  8956. }
  8957. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  8958. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : !qs.has_imatrix ? GGML_TYPE_IQ3_S : GGML_TYPE_IQ3_XXS;
  8959. }
  8960. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_S && qs.model.hparams.n_gqa() >= 4) {
  8961. new_type = GGML_TYPE_Q4_K;
  8962. }
  8963. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  8964. new_type = GGML_TYPE_Q4_K;
  8965. }
  8966. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_S && qs.model.hparams.n_gqa() >= 4) {
  8967. new_type = GGML_TYPE_Q4_K;
  8968. }
  8969. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  8970. new_type = GGML_TYPE_Q4_K;
  8971. }
  8972. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  8973. new_type = qs.i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  8974. }
  8975. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  8976. else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && qs.model.hparams.n_gqa() >= 4) {
  8977. new_type = GGML_TYPE_Q5_K;
  8978. }
  8979. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
  8980. use_more_bits(qs.i_attention_wv, qs.n_attention_wv)) new_type = GGML_TYPE_Q6_K;
  8981. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && qs.i_attention_wv < 4) new_type = GGML_TYPE_Q5_K;
  8982. else if (QK_K == 64 && (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S) &&
  8983. (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;
  8984. if (qs.model.type == MODEL_70B) {
  8985. // In the 70B model we have 8 heads sharing the same attn_v weights. As a result, the attn_v.weight tensor is
  8986. // 8x smaller compared to attn_q.weight. Hence, we can get a nice boost in quantization accuracy with
  8987. // nearly negligible increase in model size by quantizing this tensor with more bits:
  8988. if (new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K) new_type = GGML_TYPE_Q5_K;
  8989. }
  8990. if (qs.model.hparams.n_expert == 8) {
  8991. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  8992. // TODO: explore better strategies
  8993. new_type = GGML_TYPE_Q8_0;
  8994. }
  8995. ++qs.i_attention_wv;
  8996. } else if (name.find("attn_k.weight") != std::string::npos) {
  8997. if (qs.model.hparams.n_expert == 8) {
  8998. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  8999. // TODO: explore better strategies
  9000. new_type = GGML_TYPE_Q8_0;
  9001. }
  9002. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  9003. new_type = GGML_TYPE_IQ3_XXS;
  9004. }
  9005. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  9006. new_type = GGML_TYPE_IQ2_S;
  9007. }
  9008. } else if (name.find("attn_q.weight") != std::string::npos) {
  9009. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) {
  9010. new_type = GGML_TYPE_IQ3_XXS;
  9011. }
  9012. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) {
  9013. new_type = GGML_TYPE_IQ2_S;
  9014. }
  9015. } else if (name.find("ffn_down") != std::string::npos) {
  9016. auto info = layer_info(qs.i_ffn_down, qs.n_ffn_down, name.c_str());
  9017. int i_layer = info.first, n_layer = info.second;
  9018. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  9019. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S) {
  9020. if (i_layer < n_layer/8) new_type = GGML_TYPE_Q4_K;
  9021. }
  9022. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS && !qs.has_imatrix) {
  9023. new_type = i_layer < n_layer/8 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  9024. }
  9025. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  9026. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q5_K
  9027. : arch != LLM_ARCH_FALCON || use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q4_K
  9028. : GGML_TYPE_Q3_K;
  9029. }
  9030. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M && (i_layer < n_layer/8 ||
  9031. (qs.model.hparams.n_expert == 8 && use_more_bits(i_layer, n_layer)))) {
  9032. new_type = GGML_TYPE_Q4_K;
  9033. }
  9034. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) {
  9035. new_type = arch == LLM_ARCH_FALCON ? GGML_TYPE_Q4_K : GGML_TYPE_Q5_K;
  9036. }
  9037. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  9038. if (arch == LLM_ARCH_FALCON) {
  9039. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q6_K :
  9040. use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  9041. } else {
  9042. if (use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  9043. }
  9044. }
  9045. else if (i_layer < n_layer/8 && (ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && !qs.has_imatrix) {
  9046. new_type = GGML_TYPE_Q5_K;
  9047. }
  9048. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M && use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  9049. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && arch != LLM_ARCH_FALCON && i_layer < n_layer/8) {
  9050. new_type = GGML_TYPE_Q5_K;
  9051. }
  9052. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_0 || ftype == LLAMA_FTYPE_MOSTLY_Q5_0)
  9053. && qs.has_imatrix && i_layer < n_layer/8) {
  9054. // Guard against craziness in the first few ffn_down layers that can happen even with imatrix for Q4_0/Q5_0.
  9055. // We only do it when an imatrix is provided because a) we want to make sure that one can always get the
  9056. // same quantization as before imatrix stuff, and b) Q4_1/Q5_1 do go crazy on ffn_down without an imatrix.
  9057. new_type = ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ? GGML_TYPE_Q4_1 : GGML_TYPE_Q5_1;
  9058. }
  9059. ++qs.i_ffn_down;
  9060. } else if (name.find("attn_output.weight") != std::string::npos) {
  9061. if (arch != LLM_ARCH_FALCON) {
  9062. if (qs.model.hparams.n_expert == 8) {
  9063. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS ||
  9064. ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL ||
  9065. ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S ||
  9066. ftype == LLAMA_FTYPE_MOSTLY_IQ3_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) {
  9067. new_type = GGML_TYPE_Q5_K;
  9068. }
  9069. } else {
  9070. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K ) new_type = GGML_TYPE_Q3_K;
  9071. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) new_type = GGML_TYPE_IQ3_S;
  9072. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M ) new_type = GGML_TYPE_Q4_K;
  9073. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L ) new_type = GGML_TYPE_Q5_K;
  9074. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M ) new_type = GGML_TYPE_Q4_K;
  9075. }
  9076. } else {
  9077. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  9078. }
  9079. }
  9080. else if (name.find("attn_qkv.weight") != std::string::npos) {
  9081. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L || ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) {
  9082. new_type = GGML_TYPE_Q4_K;
  9083. }
  9084. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) new_type = GGML_TYPE_Q5_K;
  9085. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) new_type = GGML_TYPE_Q6_K;
  9086. }
  9087. else if (name.find("ffn_gate") != std::string::npos) {
  9088. auto info = layer_info(qs.i_ffn_gate, qs.n_ffn_gate, name.c_str());
  9089. int i_layer = info.first, n_layer = info.second;
  9090. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  9091. new_type = GGML_TYPE_IQ3_XXS;
  9092. }
  9093. ++qs.i_ffn_gate;
  9094. }
  9095. else if (name.find("ffn_up") != std::string::npos) {
  9096. auto info = layer_info(qs.i_ffn_up, qs.n_ffn_up, name.c_str());
  9097. int i_layer = info.first, n_layer = info.second;
  9098. if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) {
  9099. new_type = GGML_TYPE_IQ3_XXS;
  9100. }
  9101. ++qs.i_ffn_up;
  9102. }
  9103. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  9104. //}
  9105. // IK: let's remove this, else Q2_K is almost the same as Q3_K_S
  9106. //else if (name.find("ffn_gate") != std::string::npos || name.find("ffn_up") != std::string::npos) {
  9107. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  9108. //}
  9109. // This can be used to reduce the size of the Q5_K_S model.
  9110. // The associated PPL increase is fully in line with the size reduction
  9111. //else {
  9112. // if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_S) new_type = GGML_TYPE_Q4_K;
  9113. //}
  9114. bool convert_incompatible_tensor = false;
  9115. if (new_type == GGML_TYPE_Q2_K || new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K ||
  9116. new_type == GGML_TYPE_Q5_K || new_type == GGML_TYPE_Q6_K || new_type == GGML_TYPE_IQ4_XS ||
  9117. new_type == GGML_TYPE_IQ2_XS || new_type == GGML_TYPE_IQ2_XXS || new_type == GGML_TYPE_IQ2_S ||
  9118. new_type == GGML_TYPE_IQ3_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || new_type == GGML_TYPE_IQ3_S) {
  9119. int nx = tensor->ne[0];
  9120. int ny = tensor->ne[1];
  9121. if (nx % QK_K != 0) {
  9122. 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));
  9123. convert_incompatible_tensor = true;
  9124. } else {
  9125. ++qs.n_k_quantized;
  9126. }
  9127. }
  9128. if (convert_incompatible_tensor) {
  9129. switch (new_type) {
  9130. case GGML_TYPE_IQ2_XXS:
  9131. case GGML_TYPE_IQ2_XS:
  9132. case GGML_TYPE_IQ2_S:
  9133. case GGML_TYPE_IQ3_XXS:
  9134. case GGML_TYPE_IQ3_S:
  9135. case GGML_TYPE_IQ1_S:
  9136. case GGML_TYPE_Q2_K:
  9137. case GGML_TYPE_Q3_K:
  9138. case GGML_TYPE_IQ4_XS: new_type = GGML_TYPE_IQ4_NL; break;
  9139. case GGML_TYPE_Q4_K: new_type = GGML_TYPE_Q5_0; break;
  9140. case GGML_TYPE_Q5_K: new_type = GGML_TYPE_Q5_1; break;
  9141. case GGML_TYPE_Q6_K: new_type = GGML_TYPE_Q8_0; break;
  9142. default: throw std::runtime_error("\nUnsupported tensor size encountered\n");
  9143. }
  9144. LLAMA_LOG_WARN(" - using fallback quantization %s\n", ggml_type_name(new_type));
  9145. ++qs.n_fallback;
  9146. }
  9147. return new_type;
  9148. }
  9149. static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) {
  9150. ggml_type quantized_type;
  9151. llama_ftype ftype = params->ftype;
  9152. switch (params->ftype) {
  9153. case LLAMA_FTYPE_MOSTLY_Q4_0: quantized_type = GGML_TYPE_Q4_0; break;
  9154. case LLAMA_FTYPE_MOSTLY_Q4_1: quantized_type = GGML_TYPE_Q4_1; break;
  9155. case LLAMA_FTYPE_MOSTLY_Q5_0: quantized_type = GGML_TYPE_Q5_0; break;
  9156. case LLAMA_FTYPE_MOSTLY_Q5_1: quantized_type = GGML_TYPE_Q5_1; break;
  9157. case LLAMA_FTYPE_MOSTLY_Q8_0: quantized_type = GGML_TYPE_Q8_0; break;
  9158. case LLAMA_FTYPE_MOSTLY_F16: quantized_type = GGML_TYPE_F16; break;
  9159. case LLAMA_FTYPE_ALL_F32: quantized_type = GGML_TYPE_F32; break;
  9160. // K-quants
  9161. case LLAMA_FTYPE_MOSTLY_Q2_K_S:
  9162. case LLAMA_FTYPE_MOSTLY_Q2_K: quantized_type = GGML_TYPE_Q2_K; break;
  9163. case LLAMA_FTYPE_MOSTLY_IQ3_XS: quantized_type = GGML_TYPE_IQ3_S; break;
  9164. case LLAMA_FTYPE_MOSTLY_Q3_K_S:
  9165. case LLAMA_FTYPE_MOSTLY_Q3_K_M:
  9166. case LLAMA_FTYPE_MOSTLY_Q3_K_L: quantized_type = GGML_TYPE_Q3_K; break;
  9167. case LLAMA_FTYPE_MOSTLY_Q4_K_S:
  9168. case LLAMA_FTYPE_MOSTLY_Q4_K_M: quantized_type = GGML_TYPE_Q4_K; break;
  9169. case LLAMA_FTYPE_MOSTLY_Q5_K_S:
  9170. case LLAMA_FTYPE_MOSTLY_Q5_K_M: quantized_type = GGML_TYPE_Q5_K; break;
  9171. case LLAMA_FTYPE_MOSTLY_Q6_K: quantized_type = GGML_TYPE_Q6_K; break;
  9172. case LLAMA_FTYPE_MOSTLY_IQ2_XXS: quantized_type = GGML_TYPE_IQ2_XXS; break;
  9173. case LLAMA_FTYPE_MOSTLY_IQ2_XS: quantized_type = GGML_TYPE_IQ2_XS; break;
  9174. case LLAMA_FTYPE_MOSTLY_IQ2_S: quantized_type = GGML_TYPE_IQ2_XS; break;
  9175. case LLAMA_FTYPE_MOSTLY_IQ2_M: quantized_type = GGML_TYPE_IQ2_S; break;
  9176. case LLAMA_FTYPE_MOSTLY_IQ3_XXS: quantized_type = GGML_TYPE_IQ3_XXS; break;
  9177. case LLAMA_FTYPE_MOSTLY_IQ1_S: quantized_type = GGML_TYPE_IQ1_S; break;
  9178. case LLAMA_FTYPE_MOSTLY_IQ4_NL: quantized_type = GGML_TYPE_IQ4_NL; break;
  9179. case LLAMA_FTYPE_MOSTLY_IQ4_XS: quantized_type = GGML_TYPE_IQ4_XS; break;
  9180. case LLAMA_FTYPE_MOSTLY_IQ3_S: quantized_type = GGML_TYPE_IQ3_S; break;
  9181. case LLAMA_FTYPE_MOSTLY_IQ3_M: quantized_type = GGML_TYPE_IQ3_S; break;
  9182. default: throw std::runtime_error(format("invalid output file type %d\n", ftype));
  9183. }
  9184. int nthread = params->nthread;
  9185. if (nthread <= 0) {
  9186. nthread = std::thread::hardware_concurrency();
  9187. }
  9188. // mmap consistently increases speed Linux, and also increases speed on Windows with
  9189. // hot cache. It may cause a slowdown on macOS, possibly related to free memory.
  9190. #if defined(__linux__) || defined(_WIN32)
  9191. constexpr bool use_mmap = true;
  9192. #else
  9193. constexpr bool use_mmap = false;
  9194. #endif
  9195. llama_model_loader ml(fname_inp, use_mmap, NULL);
  9196. ml.init_mapping(false); // no prefetching?
  9197. llama_model model;
  9198. llm_load_arch(ml, model);
  9199. llm_load_hparams(ml, model);
  9200. struct quantize_state_internal qs(model, params);
  9201. if (params->only_copy) {
  9202. ftype = model.ftype;
  9203. }
  9204. const std::unordered_map<std::string, std::vector<float>> * imatrix_data = nullptr;
  9205. if (params->imatrix) {
  9206. imatrix_data = static_cast<const std::unordered_map<std::string, std::vector<float>>*>(params->imatrix);
  9207. if (imatrix_data) {
  9208. LLAMA_LOG_INFO("================================ Have weights data with %d entries\n",int(imatrix_data->size()));
  9209. qs.has_imatrix = true;
  9210. }
  9211. }
  9212. const size_t align = GGUF_DEFAULT_ALIGNMENT;
  9213. struct gguf_context * ctx_out = gguf_init_empty();
  9214. // copy the KV pairs from the input file
  9215. gguf_set_kv (ctx_out, ml.ctx_gguf);
  9216. gguf_set_val_u32(ctx_out, "general.quantization_version", GGML_QNT_VERSION);
  9217. gguf_set_val_u32(ctx_out, "general.file_type", ftype);
  9218. for (int i = 0; i < ml.n_tensors; ++i) {
  9219. struct ggml_tensor * meta = ml.get_tensor_meta(i);
  9220. const std::string name = ggml_get_name(meta);
  9221. // TODO: avoid hardcoded tensor names - use the TN_* constants
  9222. if (name.find("attn_v.weight") != std::string::npos || name.find("attn_qkv.weight") != std::string::npos) {
  9223. ++qs.n_attention_wv;
  9224. }
  9225. else if (name.find("ffn_down") != std::string::npos) {
  9226. ++qs.n_ffn_down;
  9227. }
  9228. else if (name.find("ffn_gate") != std::string::npos) {
  9229. ++qs.n_ffn_gate;
  9230. }
  9231. else if (name.find("ffn_up") != std::string::npos) {
  9232. ++qs.n_ffn_up;
  9233. }
  9234. }
  9235. if (qs.n_attention_wv != qs.n_ffn_down || (uint32_t)qs.n_attention_wv != model.hparams.n_layer) {
  9236. LLAMA_LOG_WARN("%s ============ Strange model: n_attention_wv = %d, n_ffn_down = %d, hparams.n_layer = %d\n",
  9237. __func__, qs.n_attention_wv, qs.n_ffn_down, model.hparams.n_layer);
  9238. }
  9239. size_t total_size_org = 0;
  9240. size_t total_size_new = 0;
  9241. std::vector<int64_t> hist_all(1 << 4, 0);
  9242. std::vector<std::thread> workers;
  9243. workers.reserve(nthread);
  9244. std::mutex mutex;
  9245. int idx = 0;
  9246. std::vector<no_init<uint8_t>> read_data;
  9247. std::vector<no_init<uint8_t>> work;
  9248. std::vector<no_init<float>> f32_conv_buf;
  9249. // populate the original tensors so we get an initial meta data
  9250. for (int i = 0; i < ml.n_tensors; ++i) {
  9251. struct ggml_tensor * meta = ml.get_tensor_meta(i);
  9252. gguf_add_tensor(ctx_out, meta);
  9253. }
  9254. std::ofstream fout(fname_out, std::ios::binary);
  9255. fout.exceptions(std::ofstream::failbit); // fail fast on write errors
  9256. const size_t meta_size = gguf_get_meta_size(ctx_out);
  9257. LLAMA_LOG_INFO("%s: meta size = %zu bytes\n", __func__, meta_size);
  9258. // placeholder for the meta data
  9259. ::zeros(fout, meta_size);
  9260. for (int i = 0; i < ml.n_tensors; ++i) {
  9261. struct ggml_tensor * tensor = ml.get_tensor_meta(i);
  9262. const std::string name = ggml_get_name(tensor);
  9263. if (!ml.use_mmap) {
  9264. if (read_data.size() < ggml_nbytes(tensor)) {
  9265. read_data.resize(ggml_nbytes(tensor));
  9266. }
  9267. tensor->data = read_data.data();
  9268. }
  9269. ml.load_data_for(tensor);
  9270. LLAMA_LOG_INFO("[%4d/%4d] %36s - [%s], type = %6s, ",
  9271. ++idx, ml.n_tensors,
  9272. ggml_get_name(tensor),
  9273. llama_format_tensor_shape(tensor).c_str(),
  9274. ggml_type_name(tensor->type));
  9275. // This used to be a regex, but <regex> has an extreme cost to compile times.
  9276. bool quantize = name.rfind("weight") == name.size() - 6; // ends with 'weight'?
  9277. // quantize only 2D tensors
  9278. quantize &= (ggml_n_dims(tensor) == 2);
  9279. quantize &= params->quantize_output_tensor || name != "output.weight";
  9280. quantize &= !params->only_copy;
  9281. // do not quantize expert gating tensors
  9282. // NOTE: can't use LLM_TN here because the layer number is not known
  9283. quantize &= name.find("ffn_gate_inp.weight") == std::string::npos;
  9284. // do not quantize positional embeddings and token types (BERT)
  9285. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_POS_EMBD, "weight");
  9286. quantize &= name != LLM_TN(model.arch)(LLM_TENSOR_TOKEN_TYPES, "weight");
  9287. enum ggml_type new_type;
  9288. void * new_data;
  9289. size_t new_size;
  9290. if (quantize) {
  9291. new_type = quantized_type;
  9292. if (!params->pure) {
  9293. new_type = get_k_quant_type(qs, new_type, tensor, ftype);
  9294. }
  9295. // If we've decided to quantize to the same type the tensor is already
  9296. // in then there's nothing to do.
  9297. quantize = tensor->type != new_type;
  9298. }
  9299. if (!quantize) {
  9300. new_type = tensor->type;
  9301. new_data = tensor->data;
  9302. new_size = ggml_nbytes(tensor);
  9303. LLAMA_LOG_INFO("size = %8.3f MB\n", ggml_nbytes(tensor)/1024.0/1024.0);
  9304. } else {
  9305. const size_t nelements = ggml_nelements(tensor);
  9306. const float * imatrix = nullptr;
  9307. if (imatrix_data) {
  9308. auto it = imatrix_data->find(tensor->name);
  9309. if (it == imatrix_data->end()) {
  9310. LLAMA_LOG_INFO("\n====== %s: did not find weights for %s\n", __func__, tensor->name);
  9311. } else {
  9312. if (it->second.size() == (size_t)tensor->ne[0]) {
  9313. imatrix = it->second.data();
  9314. } else {
  9315. LLAMA_LOG_INFO("\n====== %s: imatrix size %d is different from tensor size %d for %s\n", __func__,
  9316. int(it->second.size()), int(tensor->ne[0]), tensor->name);
  9317. }
  9318. }
  9319. }
  9320. if ((new_type == GGML_TYPE_IQ2_XXS ||
  9321. new_type == GGML_TYPE_IQ2_XS ||
  9322. new_type == GGML_TYPE_IQ2_S ||
  9323. new_type == GGML_TYPE_IQ1_S ||
  9324. (new_type == GGML_TYPE_Q2_K && params->ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && strcmp(tensor->name, "token_embd.weight") != 0)) && !imatrix) {
  9325. LLAMA_LOG_ERROR("\n\n============================================================\n");
  9326. LLAMA_LOG_ERROR("Missing importance matrix for tensor %s in a very low-bit quantization\n", tensor->name);
  9327. LLAMA_LOG_ERROR("The result will be garbage, so bailing out\n");
  9328. LLAMA_LOG_ERROR("============================================================\n\n");
  9329. throw std::runtime_error(format("Missing importance matrix for tensor %s in a very low-bit quantization", tensor->name));
  9330. }
  9331. float * f32_data;
  9332. if (tensor->type == GGML_TYPE_F32) {
  9333. f32_data = (float *) tensor->data;
  9334. } else if (ggml_is_quantized(tensor->type) && !params->allow_requantize) {
  9335. throw std::runtime_error(format("requantizing from type %s is disabled", ggml_type_name(tensor->type)));
  9336. } else {
  9337. llama_convert_tensor_internal(tensor, f32_conv_buf, workers, nelements, nthread);
  9338. f32_data = (float *) f32_conv_buf.data();
  9339. }
  9340. LLAMA_LOG_INFO("quantizing to %s .. ", ggml_type_name(new_type));
  9341. fflush(stdout);
  9342. if (work.size() < nelements * 4) {
  9343. work.resize(nelements * 4); // upper bound on size
  9344. }
  9345. new_data = work.data();
  9346. std::array<int64_t, 1 << 4> hist_cur = {};
  9347. const int n_per_row = tensor->ne[0];
  9348. const int nrows = nelements / n_per_row;
  9349. static const int min_chunk_size = 32 * 512;
  9350. 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);
  9351. const int nchunk = (nelements + chunk_size - 1)/chunk_size;
  9352. const int nthread_use = nthread > 1 ? std::max(1, std::min(nthread, nchunk)) : 1;
  9353. if (nthread_use < 2) {
  9354. new_size = ggml_quantize_chunk(new_type, f32_data, new_data, 0, nrows, n_per_row, hist_cur.data(), imatrix);
  9355. } else {
  9356. int counter = 0;
  9357. new_size = 0;
  9358. auto compute = [&mutex, &counter, &hist_cur, &new_size, new_type, f32_data, new_data, chunk_size,
  9359. nrows, n_per_row, imatrix]() {
  9360. std::array<int64_t, 1 << 4> local_hist = {};
  9361. const int nrows_per_chunk = chunk_size / n_per_row;
  9362. size_t local_size = 0;
  9363. while (true) {
  9364. std::unique_lock<std::mutex> lock(mutex);
  9365. int first_row = counter; counter += nrows_per_chunk;
  9366. if (first_row >= nrows) {
  9367. if (local_size > 0) {
  9368. for (int j=0; j<int(local_hist.size()); ++j) {
  9369. hist_cur[j] += local_hist[j];
  9370. }
  9371. new_size += local_size;
  9372. }
  9373. break;
  9374. }
  9375. lock.unlock();
  9376. const int this_nrow = std::min(nrows - first_row, nrows_per_chunk);
  9377. local_size += ggml_quantize_chunk(new_type, f32_data, new_data,
  9378. first_row * n_per_row, this_nrow, n_per_row, local_hist.data(), imatrix);
  9379. }
  9380. };
  9381. for (int it = 0; it < nthread_use - 1; ++it) {
  9382. workers.emplace_back(compute);
  9383. }
  9384. compute();
  9385. for (auto & w : workers) { w.join(); }
  9386. workers.clear();
  9387. }
  9388. LLAMA_LOG_INFO("size = %8.2f MiB -> %8.2f MiB", ggml_nbytes(tensor)/1024.0/1024.0, new_size/1024.0/1024.0);
  9389. int64_t tot_count = 0;
  9390. for (size_t i = 0; i < hist_cur.size(); i++) {
  9391. hist_all[i] += hist_cur[i];
  9392. tot_count += hist_cur[i];
  9393. }
  9394. if (tot_count > 0) {
  9395. LLAMA_LOG_INFO(" | hist: ");
  9396. for (size_t i = 0; i < hist_cur.size(); i++) {
  9397. LLAMA_LOG_INFO("%5.3f ", hist_cur[i] / float(nelements));
  9398. }
  9399. }
  9400. LLAMA_LOG_INFO("\n");
  9401. }
  9402. total_size_org += ggml_nbytes(tensor);
  9403. total_size_new += new_size;
  9404. // update the gguf meta data as we go
  9405. gguf_set_tensor_type(ctx_out, name.c_str(), new_type);
  9406. gguf_set_tensor_data(ctx_out, name.c_str(), new_data, new_size);
  9407. // write tensor data + padding
  9408. fout.write((const char *) new_data, new_size);
  9409. zeros(fout, GGML_PAD(new_size, align) - new_size);
  9410. }
  9411. // go back to beginning of file and write the updated meta data
  9412. {
  9413. fout.seekp(0);
  9414. std::vector<uint8_t> data(gguf_get_meta_size(ctx_out));
  9415. gguf_get_meta_data(ctx_out, data.data());
  9416. fout.write((const char *) data.data(), data.size());
  9417. }
  9418. fout.close();
  9419. gguf_free(ctx_out);
  9420. LLAMA_LOG_INFO("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  9421. LLAMA_LOG_INFO("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  9422. // print histogram for all tensors
  9423. {
  9424. int64_t sum_all = 0;
  9425. for (size_t i = 0; i < hist_all.size(); i++) {
  9426. sum_all += hist_all[i];
  9427. }
  9428. if (sum_all > 0) {
  9429. LLAMA_LOG_INFO("%s: hist: ", __func__);
  9430. for (size_t i = 0; i < hist_all.size(); i++) {
  9431. LLAMA_LOG_INFO("%5.3f ", hist_all[i] / float(sum_all));
  9432. }
  9433. LLAMA_LOG_INFO("\n");
  9434. }
  9435. }
  9436. if (qs.n_fallback > 0) {
  9437. LLAMA_LOG_WARN("%s: WARNING: %d of %d tensor(s) incompatible with k-quants and required fallback quantization\n",
  9438. __func__, qs.n_fallback, qs.n_k_quantized + qs.n_fallback);
  9439. }
  9440. }
  9441. static int llama_apply_lora_from_file_internal(
  9442. const struct llama_model & model, const char * path_lora, float scale, const char * path_base_model, int n_threads
  9443. ) {
  9444. LLAMA_LOG_INFO("%s: applying lora adapter from '%s' - please wait ...\n", __func__, path_lora);
  9445. const int64_t t_start_lora_us = ggml_time_us();
  9446. llama_file fin(path_lora, "rb");
  9447. // verify magic and version
  9448. {
  9449. uint32_t magic = fin.read_u32();
  9450. if (magic != LLAMA_FILE_MAGIC_GGLA) {
  9451. LLAMA_LOG_ERROR("%s: bad file magic\n", __func__);
  9452. return 1;
  9453. }
  9454. uint32_t format_version = fin.read_u32();
  9455. if (format_version != 1) {
  9456. LLAMA_LOG_ERROR("%s: unsupported file version\n", __func__ );
  9457. return 1;
  9458. }
  9459. }
  9460. int32_t lora_r = fin.read_u32();
  9461. int32_t lora_alpha = fin.read_u32();
  9462. float scaling = scale * (float)lora_alpha / (float)lora_r;
  9463. LLAMA_LOG_INFO("%s: r = %d, alpha = %d, scaling = %.2f\n", __func__, lora_r, lora_alpha, scaling);
  9464. // load base model
  9465. std::unique_ptr<llama_model_loader> ml;
  9466. if (path_base_model) {
  9467. LLAMA_LOG_INFO("%s: loading base model from '%s'\n", __func__, path_base_model);
  9468. ml.reset(new llama_model_loader(path_base_model, /*use_mmap*/ true, /*kv_overrides*/ nullptr));
  9469. ml->init_mapping(/*prefetch*/ false); // no prefetching
  9470. }
  9471. struct tensor_meta {
  9472. std::string name;
  9473. ggml_type type;
  9474. int32_t ne[2];
  9475. size_t offset;
  9476. };
  9477. std::map<std::string, tensor_meta> tensor_meta_map;
  9478. // load all tensor meta
  9479. while (true) {
  9480. if (fin.tell() == fin.size) {
  9481. // eof
  9482. break;
  9483. }
  9484. int32_t n_dims;
  9485. int32_t name_len;
  9486. int32_t ftype;
  9487. fin.read_raw(&n_dims, sizeof(n_dims));
  9488. fin.read_raw(&name_len, sizeof(name_len));
  9489. fin.read_raw(&ftype, sizeof(ftype));
  9490. if (n_dims != 1 && n_dims != 2) {
  9491. LLAMA_LOG_ERROR("%s: unsupported tensor dimension %d\n", __func__, n_dims);
  9492. return 1;
  9493. }
  9494. int32_t ne[2] = { 1, 1 };
  9495. for (int i = 0; i < n_dims; ++i) {
  9496. fin.read_raw(&ne[i], sizeof(ne[i]));
  9497. }
  9498. std::string name;
  9499. {
  9500. GGML_ASSERT(name_len < GGML_MAX_NAME);
  9501. char buf[GGML_MAX_NAME];
  9502. fin.read_raw(buf, name_len);
  9503. name = std::string(buf, name_len);
  9504. }
  9505. // check for lora suffix
  9506. std::string lora_suffix;
  9507. if (name.length() > 6) {
  9508. lora_suffix = name.substr(name.length() - 6);
  9509. }
  9510. if (lora_suffix != ".loraA" && lora_suffix != ".loraB") {
  9511. LLAMA_LOG_ERROR("%s: error: '%s' is not a lora tensor\n", __func__, name.c_str());
  9512. return 1;
  9513. }
  9514. // tensor type
  9515. ggml_type wtype;
  9516. switch (ftype) {
  9517. case 0: wtype = GGML_TYPE_F32; break;
  9518. case 1: wtype = GGML_TYPE_F16; break;
  9519. default:
  9520. {
  9521. LLAMA_LOG_ERROR("%s: invalid tensor data type '%d'\n",
  9522. __func__, ftype);
  9523. return 1;
  9524. }
  9525. }
  9526. // data offset
  9527. size_t offset = fin.tell();
  9528. offset = (offset + 31) & -32;
  9529. // skip tensor data
  9530. fin.seek(offset + ggml_row_size(wtype, ne[0]) * ne[1], SEEK_SET);
  9531. tensor_meta_map.emplace(name, tensor_meta{ name, wtype, { ne[0], ne[1] }, offset });
  9532. }
  9533. bool warned = false;
  9534. int n_tensors = 0;
  9535. // apply
  9536. ggml_backend_t backend_cpu = ggml_backend_cpu_init();
  9537. if (backend_cpu == nullptr) {
  9538. LLAMA_LOG_ERROR("%s: error: failed to initialize cpu backend\n", __func__);
  9539. return 1;
  9540. }
  9541. ggml_backend_cpu_set_n_threads(backend_cpu, n_threads);
  9542. std::vector<no_init<uint8_t>> read_buf;
  9543. for (const auto & it : model.tensors_by_name) {
  9544. const std::string & base_name = it.first;
  9545. ggml_tensor * model_t = it.second;
  9546. if (tensor_meta_map.find(base_name + ".loraA") == tensor_meta_map.end() ||
  9547. tensor_meta_map.find(base_name + ".loraB") == tensor_meta_map.end()) {
  9548. continue;
  9549. }
  9550. tensor_meta & metaA = tensor_meta_map.at(base_name + ".loraA");
  9551. tensor_meta & metaB = tensor_meta_map.at(base_name + ".loraB");
  9552. ggml_init_params lora_init_params = {
  9553. /* .mem_size */ ggml_tensor_overhead()*128 + ggml_graph_overhead(),
  9554. /* .mem_buffer */ nullptr,
  9555. /* .no_alloc */ true,
  9556. };
  9557. ggml_context * lora_ctx = ggml_init(lora_init_params);
  9558. if (lora_ctx == nullptr) {
  9559. LLAMA_LOG_ERROR("%s: error: failed to initialize lora context\n", __func__);
  9560. ggml_backend_free(backend_cpu);
  9561. return 1;
  9562. }
  9563. // create tensors
  9564. ggml_tensor * loraA = ggml_new_tensor_2d(lora_ctx, metaA.type, metaA.ne[0], metaA.ne[1]);
  9565. ggml_tensor * loraB = ggml_new_tensor_2d(lora_ctx, metaB.type, metaB.ne[0], metaB.ne[1]);
  9566. ggml_set_name(loraA, metaA.name.c_str());
  9567. ggml_set_name(loraB, metaB.name.c_str());
  9568. ggml_tensor * base_t;
  9569. if (ml) {
  9570. if (gguf_find_tensor(ml->ctx_gguf, base_name.c_str()) < 0) {
  9571. LLAMA_LOG_ERROR("%s: error: tensor '%s' not found in base model\n", __func__, base_name.c_str());
  9572. return 1;
  9573. }
  9574. base_t = ggml_dup_tensor(lora_ctx, ml->get_tensor_meta(base_name.c_str()));
  9575. } else {
  9576. base_t = ggml_dup_tensor(lora_ctx, model_t);
  9577. }
  9578. ggml_set_name(base_t, base_name.c_str());
  9579. // allocate in backend buffer
  9580. ggml_backend_buffer_t lora_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  9581. if (lora_buf == nullptr) {
  9582. LLAMA_LOG_ERROR("%s: error: failed to allocate lora tensors\n", __func__);
  9583. return 1;
  9584. }
  9585. // load tensor data
  9586. auto load_tensor = [&read_buf, &fin](const tensor_meta & tensor_meta, ggml_tensor * tensor) {
  9587. read_buf.resize(ggml_nbytes(tensor));
  9588. fin.seek(tensor_meta.offset, SEEK_SET);
  9589. fin.read_raw(read_buf.data(), ggml_nbytes(tensor));
  9590. ggml_backend_tensor_set(tensor, read_buf.data(), 0, read_buf.size());
  9591. };
  9592. load_tensor(metaA, loraA);
  9593. load_tensor(metaB, loraB);
  9594. // load base model tensor data
  9595. if (ml) {
  9596. ml->load_data_for(base_t);
  9597. } else {
  9598. ggml_backend_tensor_copy(model_t, base_t);
  9599. }
  9600. if (ggml_is_quantized(base_t->type) && !warned) {
  9601. LLAMA_LOG_WARN("%s: warning: using a lora adapter with a quantized model may result in poor quality, "
  9602. "use a f16 or f32 base model with --lora-base\n", __func__);
  9603. warned = true;
  9604. }
  9605. if (base_t->ne[0] != loraA->ne[1] || base_t->ne[1] != loraB->ne[1]) {
  9606. LLAMA_LOG_ERROR("%s: incompatible tensor dimensions (%" PRId64 " and %" PRId64 ");"
  9607. " are you sure that this adapter is for this model?\n", __func__, base_t->ne[0], loraA->ne[1]);
  9608. ggml_free(lora_ctx);
  9609. ggml_backend_buffer_free(lora_buf);
  9610. ggml_backend_free(backend_cpu);
  9611. return 1;
  9612. }
  9613. auto build_lora_graph = [&]() {
  9614. // w = w + BA*s
  9615. ggml_tensor * BA = ggml_mul_mat(lora_ctx, loraA, loraB);
  9616. ggml_set_name(BA, "BA");
  9617. if (scaling != 1.0f) {
  9618. BA = ggml_scale(lora_ctx, BA, scaling);
  9619. ggml_set_name(BA, "BA_scaled");
  9620. }
  9621. ggml_tensor * r;
  9622. r = ggml_add_inplace(lora_ctx, base_t, BA);
  9623. ggml_set_name(r, "r_add");
  9624. if (base_t->type != model_t->type) {
  9625. // convert the result to the model type
  9626. r = ggml_cast(lora_ctx, r, model_t->type);
  9627. ggml_set_name(r, "r_cast");
  9628. }
  9629. return r;
  9630. };
  9631. ggml_cgraph * gf = ggml_new_graph(lora_ctx);
  9632. ggml_tensor * r = build_lora_graph();
  9633. ggml_build_forward_expand(gf, r);
  9634. ggml_backend_buffer_t graph_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  9635. if (graph_buf == nullptr) {
  9636. LLAMA_LOG_ERROR("%s: error: failed to allocate graph tensors\n", __func__);
  9637. ggml_free(lora_ctx);
  9638. ggml_backend_buffer_free(lora_buf);
  9639. ggml_backend_free(backend_cpu);
  9640. return 1;
  9641. }
  9642. ggml_backend_graph_compute(backend_cpu, gf);
  9643. ggml_backend_tensor_set(model_t, r->data, 0, ggml_nbytes(r));
  9644. #if 0
  9645. // TODO: use scheduler with fallback to CPU for less copies between CPU and GPU
  9646. //ggml_backend_sched_t sched = ggml_backend_sched_new(backends.data(), backends.size(), GGML_DEFAULT_GRAPH_SIZE);
  9647. // sched compute
  9648. ggml_build_forward_expand(gf, build_graph());
  9649. ggml_backend_sched_init_measure(sched, gf);
  9650. // create the graph again, since the previous one was destroyed by the measure
  9651. ggml_graph_clear(gf);
  9652. ggml_build_forward_expand(gf, build_graph());
  9653. ggml_backend_sched_graph_compute(sched, gf);
  9654. ggml_backend_sched_free(sched);
  9655. #endif
  9656. ggml_backend_buffer_free(lora_buf);
  9657. ggml_backend_buffer_free(graph_buf);
  9658. ggml_free(lora_ctx);
  9659. n_tensors++;
  9660. if (n_tensors % 4 == 0) {
  9661. LLAMA_LOG_INFO(".");
  9662. }
  9663. }
  9664. ggml_backend_free(backend_cpu);
  9665. const int64_t t_lora_us = ggml_time_us() - t_start_lora_us;
  9666. LLAMA_LOG_INFO(" done (%.2f ms)\n", t_lora_us / 1000.0);
  9667. return 0;
  9668. }
  9669. //
  9670. // interface implementation
  9671. //
  9672. struct llama_model_params llama_model_default_params() {
  9673. struct llama_model_params result = {
  9674. /*.n_gpu_layers =*/ 0,
  9675. /*.split_mode =*/ LLAMA_SPLIT_MODE_LAYER,
  9676. /*.main_gpu =*/ 0,
  9677. /*.tensor_split =*/ nullptr,
  9678. /*.progress_callback =*/ nullptr,
  9679. /*.progress_callback_user_data =*/ nullptr,
  9680. /*.kv_overrides =*/ nullptr,
  9681. /*.vocab_only =*/ false,
  9682. /*.use_mmap =*/ true,
  9683. /*.use_mlock =*/ false,
  9684. };
  9685. #ifdef GGML_USE_METAL
  9686. // note: we usually have plenty of VRAM, so by default offload all layers to the GPU
  9687. result.n_gpu_layers = 999;
  9688. #endif
  9689. return result;
  9690. }
  9691. struct llama_context_params llama_context_default_params() {
  9692. struct llama_context_params result = {
  9693. /*.seed =*/ LLAMA_DEFAULT_SEED,
  9694. /*.n_ctx =*/ 512,
  9695. /*.n_batch =*/ 512,
  9696. /*.n_threads =*/ GGML_DEFAULT_N_THREADS, // TODO: better default
  9697. /*.n_threads_batch =*/ GGML_DEFAULT_N_THREADS,
  9698. /*.rope_scaling_type =*/ LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED,
  9699. /*.rope_freq_base =*/ 0.0f,
  9700. /*.rope_freq_scale =*/ 0.0f,
  9701. /*.yarn_ext_factor =*/ -1.0f,
  9702. /*.yarn_attn_factor =*/ 1.0f,
  9703. /*.yarn_beta_fast =*/ 32.0f,
  9704. /*.yarn_beta_slow =*/ 1.0f,
  9705. /*.yarn_orig_ctx =*/ 0,
  9706. /*.defrag_thold =*/ -1.0f,
  9707. /*.cb_eval =*/ nullptr,
  9708. /*.cb_eval_user_data =*/ nullptr,
  9709. /*.type_k =*/ GGML_TYPE_F16,
  9710. /*.type_v =*/ GGML_TYPE_F16,
  9711. /*.mul_mat_q =*/ true,
  9712. /*.logits_all =*/ false,
  9713. /*.embedding =*/ false,
  9714. /*.offload_kqv =*/ true,
  9715. /*.do_pooling =*/ true,
  9716. };
  9717. return result;
  9718. }
  9719. struct llama_model_quantize_params llama_model_quantize_default_params() {
  9720. struct llama_model_quantize_params result = {
  9721. /*.nthread =*/ 0,
  9722. /*.ftype =*/ LLAMA_FTYPE_MOSTLY_Q5_1,
  9723. /*.allow_requantize =*/ false,
  9724. /*.quantize_output_tensor =*/ true,
  9725. /*.only_copy =*/ false,
  9726. /*.pure =*/ false,
  9727. /*.imatrix =*/ nullptr,
  9728. };
  9729. return result;
  9730. }
  9731. size_t llama_max_devices(void) {
  9732. #if defined(GGML_USE_METAL)
  9733. return 1;
  9734. #elif defined(GGML_USE_CUBLAS)
  9735. return GGML_CUDA_MAX_DEVICES;
  9736. #elif defined(GGML_USE_SYCL)
  9737. return GGML_SYCL_MAX_DEVICES;
  9738. #elif defined(GGML_USE_VULKAN)
  9739. return GGML_VK_MAX_DEVICES;
  9740. #else
  9741. return 1;
  9742. #endif
  9743. }
  9744. bool llama_supports_mmap(void) {
  9745. return llama_mmap::SUPPORTED;
  9746. }
  9747. bool llama_supports_mlock(void) {
  9748. return llama_mlock::SUPPORTED;
  9749. }
  9750. bool llama_supports_gpu_offload(void) {
  9751. #if defined(GGML_USE_CUBLAS) || defined(GGML_USE_CLBLAST) || defined(GGML_USE_METAL) || defined(GGML_USE_VULKAN) || \
  9752. defined(GGML_USE_SYCL) || defined(GGML_USE_KOMPUTE)
  9753. // Defined when llama.cpp is compiled with support for offloading model layers to GPU.
  9754. return true;
  9755. #else
  9756. return false;
  9757. #endif
  9758. }
  9759. // deprecated:
  9760. bool llama_mmap_supported(void) {
  9761. return llama_supports_mmap();
  9762. }
  9763. bool llama_mlock_supported(void) {
  9764. return llama_supports_mlock();
  9765. }
  9766. void llama_backend_init(void) {
  9767. ggml_time_init();
  9768. // needed to initialize f16 tables
  9769. {
  9770. struct ggml_init_params params = { 0, NULL, false };
  9771. struct ggml_context * ctx = ggml_init(params);
  9772. ggml_free(ctx);
  9773. }
  9774. #ifdef GGML_USE_MPI
  9775. ggml_mpi_backend_init();
  9776. #endif
  9777. }
  9778. void llama_numa_init(enum ggml_numa_strategy numa) {
  9779. if (numa != GGML_NUMA_STRATEGY_DISABLED) {
  9780. ggml_numa_init(numa);
  9781. }
  9782. }
  9783. void llama_backend_free(void) {
  9784. #ifdef GGML_USE_MPI
  9785. ggml_mpi_backend_free();
  9786. #endif
  9787. ggml_quantize_free();
  9788. }
  9789. int64_t llama_time_us(void) {
  9790. return ggml_time_us();
  9791. }
  9792. struct llama_model * llama_load_model_from_file(
  9793. const char * path_model,
  9794. struct llama_model_params params) {
  9795. ggml_time_init();
  9796. llama_model * model = new llama_model;
  9797. unsigned cur_percentage = 0;
  9798. if (params.progress_callback == NULL) {
  9799. params.progress_callback_user_data = &cur_percentage;
  9800. params.progress_callback = [](float progress, void * ctx) {
  9801. unsigned * cur_percentage_p = (unsigned *) ctx;
  9802. unsigned percentage = (unsigned) (100 * progress);
  9803. while (percentage > *cur_percentage_p) {
  9804. *cur_percentage_p = percentage;
  9805. LLAMA_LOG_INFO(".");
  9806. if (percentage >= 100) {
  9807. LLAMA_LOG_INFO("\n");
  9808. }
  9809. }
  9810. return true;
  9811. };
  9812. }
  9813. int status = llama_model_load(path_model, *model, params);
  9814. GGML_ASSERT(status <= 0);
  9815. if (status < 0) {
  9816. if (status == -1) {
  9817. LLAMA_LOG_ERROR("%s: failed to load model\n", __func__);
  9818. } else if (status == -2) {
  9819. LLAMA_LOG_INFO("%s: cancelled model load\n", __func__);
  9820. }
  9821. delete model;
  9822. return nullptr;
  9823. }
  9824. return model;
  9825. }
  9826. void llama_free_model(struct llama_model * model) {
  9827. delete model;
  9828. }
  9829. struct llama_context * llama_new_context_with_model(
  9830. struct llama_model * model,
  9831. struct llama_context_params params) {
  9832. if (!model) {
  9833. return nullptr;
  9834. }
  9835. llama_context * ctx = new llama_context(*model);
  9836. const auto & hparams = model->hparams;
  9837. auto & cparams = ctx->cparams;
  9838. cparams.n_batch = params.n_batch;
  9839. cparams.n_threads = params.n_threads;
  9840. cparams.n_threads_batch = params.n_threads_batch;
  9841. cparams.yarn_ext_factor = params.yarn_ext_factor;
  9842. cparams.yarn_attn_factor = params.yarn_attn_factor;
  9843. cparams.yarn_beta_fast = params.yarn_beta_fast;
  9844. cparams.yarn_beta_slow = params.yarn_beta_slow;
  9845. cparams.defrag_thold = params.defrag_thold;
  9846. cparams.mul_mat_q = params.mul_mat_q;
  9847. cparams.offload_kqv = params.offload_kqv;
  9848. cparams.do_pooling = params.do_pooling;
  9849. cparams.n_ctx = params.n_ctx == 0 ? hparams.n_ctx_train : params.n_ctx;
  9850. cparams.rope_freq_base = params.rope_freq_base == 0.0f ? hparams.rope_freq_base_train : params.rope_freq_base;
  9851. cparams.rope_freq_scale = params.rope_freq_scale == 0.0f ? hparams.rope_freq_scale_train : params.rope_freq_scale;
  9852. cparams.n_yarn_orig_ctx = params.yarn_orig_ctx != 0 ? params.yarn_orig_ctx :
  9853. hparams.n_yarn_orig_ctx != 0 ? hparams.n_yarn_orig_ctx :
  9854. hparams.n_ctx_train;
  9855. cparams.cb_eval = params.cb_eval;
  9856. cparams.cb_eval_user_data = params.cb_eval_user_data;
  9857. auto rope_scaling_type = params.rope_scaling_type;
  9858. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED) {
  9859. rope_scaling_type = hparams.rope_scaling_type_train;
  9860. }
  9861. if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_NONE) {
  9862. cparams.rope_freq_scale = 1.0f; // never scale if scaling type is none
  9863. }
  9864. if (cparams.yarn_ext_factor < 0.0f) { // negative indicates 'not set'
  9865. cparams.yarn_ext_factor = rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_YARN ? 1.0f : 0.0f;
  9866. }
  9867. if (params.seed == LLAMA_DEFAULT_SEED) {
  9868. params.seed = time(NULL);
  9869. }
  9870. LLAMA_LOG_INFO("%s: n_ctx = %u\n", __func__, cparams.n_ctx);
  9871. LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, cparams.rope_freq_base);
  9872. LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, cparams.rope_freq_scale);
  9873. ctx->rng = std::mt19937(params.seed);
  9874. ctx->logits_all = params.logits_all;
  9875. const ggml_type type_k = params.type_k;
  9876. const ggml_type type_v = params.type_v;
  9877. GGML_ASSERT(hparams.n_embd_head_k % ggml_blck_size(type_k) == 0);
  9878. GGML_ASSERT(hparams.n_embd_head_v % ggml_blck_size(type_v) == 0);
  9879. if (!hparams.vocab_only) {
  9880. // initialize backends
  9881. #ifdef GGML_USE_METAL
  9882. if (model->n_gpu_layers > 0) {
  9883. ctx->backend_metal = ggml_backend_metal_init();
  9884. if (ctx->backend_metal == nullptr) {
  9885. LLAMA_LOG_ERROR("%s: failed to initialize Metal backend\n", __func__);
  9886. llama_free(ctx);
  9887. return nullptr;
  9888. }
  9889. ctx->backends.push_back(ctx->backend_metal);
  9890. }
  9891. #elif defined(GGML_USE_CUBLAS)
  9892. if (model->n_gpu_layers > 0) {
  9893. // with split_mode LLAMA_SPLIT_MODE_NONE or LLAMA_SPLIT_MODE_ROW, only the main GPU backend is used
  9894. if (model->split_mode == LLAMA_SPLIT_MODE_NONE || model->split_mode == LLAMA_SPLIT_MODE_ROW) {
  9895. ggml_backend_t backend = ggml_backend_cuda_init(model->main_gpu);
  9896. if (backend == nullptr) {
  9897. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, model->main_gpu);
  9898. llama_free(ctx);
  9899. return nullptr;
  9900. }
  9901. ctx->backends.push_back(backend);
  9902. } else {
  9903. // LLAMA_SPLIT_MODE_LAYER requires a backend for each GPU
  9904. for (int device = 0; device < ggml_backend_cuda_get_device_count(); ++device) {
  9905. ggml_backend_t backend = ggml_backend_cuda_init(device);
  9906. if (backend == nullptr) {
  9907. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, device);
  9908. llama_free(ctx);
  9909. return nullptr;
  9910. }
  9911. ctx->backends.push_back(backend);
  9912. }
  9913. }
  9914. }
  9915. #elif defined(GGML_USE_VULKAN)
  9916. if (model->n_gpu_layers > 0) {
  9917. for (int device = 0; device < ggml_backend_vk_get_device_count(); ++device) {
  9918. ggml_backend_t backend = ggml_backend_vk_init(device);
  9919. if (backend == nullptr) {
  9920. LLAMA_LOG_ERROR("%s: failed to initialize Vulkan%d backend\n", __func__, device);
  9921. llama_free(ctx);
  9922. return nullptr;
  9923. }
  9924. ctx->backends.push_back(backend);
  9925. }
  9926. }
  9927. #elif defined(GGML_USE_SYCL)
  9928. if (model->n_gpu_layers > 0) {
  9929. ggml_backend_t backend = ggml_backend_sycl_init(model->main_gpu);
  9930. if (backend == nullptr) {
  9931. LLAMA_LOG_ERROR("%s: failed to initialize SYCL%d backend\n", __func__, model->main_gpu);
  9932. llama_free(ctx);
  9933. return nullptr;
  9934. }
  9935. ctx->backends.push_back(backend);
  9936. }
  9937. #elif defined(GGML_USE_KOMPUTE)
  9938. if (model->n_gpu_layers > 0) {
  9939. auto * backend = ggml_backend_kompute_init(model->main_gpu);
  9940. if (backend == nullptr) {
  9941. LLAMA_LOG_ERROR("%s: failed to initialize Kompute backend\n", __func__);
  9942. llama_free(ctx);
  9943. return nullptr;
  9944. }
  9945. ctx->backends.push_back(backend);
  9946. }
  9947. #endif
  9948. ctx->backend_cpu = ggml_backend_cpu_init();
  9949. if (ctx->backend_cpu == nullptr) {
  9950. LLAMA_LOG_ERROR("%s: failed to initialize CPU backend\n", __func__);
  9951. llama_free(ctx);
  9952. return nullptr;
  9953. }
  9954. ctx->backends.push_back(ctx->backend_cpu);
  9955. if (!llama_kv_cache_init(ctx->kv_self, ctx->model, type_k, type_v, cparams.n_ctx, cparams.offload_kqv)) {
  9956. LLAMA_LOG_ERROR("%s: llama_kv_cache_init() failed for self-attention cache\n", __func__);
  9957. llama_free(ctx);
  9958. return nullptr;
  9959. }
  9960. {
  9961. size_t memory_size_k = 0;
  9962. size_t memory_size_v = 0;
  9963. for (auto & k : ctx->kv_self.k_l) {
  9964. memory_size_k += ggml_nbytes(k);
  9965. }
  9966. for (auto & v : ctx->kv_self.v_l) {
  9967. memory_size_v += ggml_nbytes(v);
  9968. }
  9969. LLAMA_LOG_INFO("%s: KV self size = %7.2f MiB, K (%s): %7.2f MiB, V (%s): %7.2f MiB\n", __func__,
  9970. (float)(memory_size_k + memory_size_v) / (1024.0f * 1024.0f),
  9971. ggml_type_name(type_k), (float)memory_size_k / (1024.0f * 1024.0f),
  9972. ggml_type_name(type_v), (float)memory_size_v / (1024.0f * 1024.0f));
  9973. }
  9974. // resized during inference, reserve maximum
  9975. ctx->logits.reserve(hparams.n_vocab*cparams.n_batch);
  9976. if (params.embedding) {
  9977. ctx->embedding.resize(hparams.n_embd);
  9978. }
  9979. // graph inputs
  9980. {
  9981. ggml_init_params init_params = {
  9982. /* .mem_size */ ggml_tensor_overhead()*8,
  9983. /* .mem_buffer */ nullptr,
  9984. /* .no_alloc */ true,
  9985. };
  9986. ctx->ctx_input = ggml_init(init_params);
  9987. ctx->inp_tokens = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_I32, cparams.n_batch);
  9988. ctx->inp_embd = ggml_new_tensor_2d(ctx->ctx_input, GGML_TYPE_F32, hparams.n_embd, cparams.n_batch);
  9989. ctx->inp_pos = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_I32, cparams.n_batch);
  9990. ctx->inp_KQ_mask = ggml_new_tensor_2d(ctx->ctx_input, GGML_TYPE_F32, cparams.n_ctx, cparams.n_batch);
  9991. ctx->inp_KQ_pos = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_F32, cparams.n_ctx);
  9992. ctx->inp_K_shift = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_I32, cparams.n_ctx);
  9993. ctx->inp_mean = ggml_new_tensor_2d(ctx->ctx_input, GGML_TYPE_F32, cparams.n_batch, cparams.n_batch);
  9994. ctx->inp_cls = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_I32, cparams.n_batch);
  9995. ggml_set_name(ctx->inp_tokens, "inp_tokens");
  9996. ggml_set_name(ctx->inp_embd, "inp_embd");
  9997. ggml_set_name(ctx->inp_pos, "inp_pos");
  9998. ggml_set_name(ctx->inp_KQ_mask, "inp_KQ_mask");
  9999. ggml_set_name(ctx->inp_KQ_pos, "inp_KQ_pos");
  10000. ggml_set_name(ctx->inp_K_shift, "inp_K_shift");
  10001. ggml_set_name(ctx->inp_mean, "inp_mean");
  10002. ggml_set_name(ctx->inp_cls, "inp_cls");
  10003. ctx->buf_input = ggml_backend_alloc_ctx_tensors_from_buft(ctx->ctx_input, llama_default_buffer_type_cpu(true));
  10004. LLAMA_LOG_INFO("%s: %10s input buffer size = %8.2f MiB\n", __func__,
  10005. ggml_backend_buffer_name(ctx->buf_input),
  10006. ggml_backend_buffer_get_size(ctx->buf_input) / 1024.0 / 1024.0);
  10007. }
  10008. // scheduler and compute buffers
  10009. {
  10010. // buffer types used for the compute buffer of each backend
  10011. std::vector<ggml_backend_buffer_type_t> backend_buft;
  10012. for (auto * backend : ctx->backends) {
  10013. if (ggml_backend_is_cpu(backend)) {
  10014. // use host buffers for the CPU backend compute buffer
  10015. backend_buft.push_back(llama_default_buffer_type_cpu(true));
  10016. } else {
  10017. backend_buft.push_back(ggml_backend_get_default_buffer_type(backend));
  10018. }
  10019. }
  10020. // buffer used to store the computation graph and the tensor meta data
  10021. ctx->buf_compute_meta.resize(ggml_tensor_overhead()*LLAMA_MAX_NODES + ggml_graph_overhead_custom(LLAMA_MAX_NODES, false));
  10022. ctx->sched = ggml_backend_sched_new(ctx->backends.data(), backend_buft.data(), ctx->backends.size(), LLAMA_MAX_NODES);
  10023. // build worst-case graph
  10024. int n_tokens = (int)std::min(cparams.n_ctx, cparams.n_batch);
  10025. int n_past = cparams.n_ctx - n_tokens;
  10026. 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
  10027. ggml_cgraph * gf = llama_build_graph(*ctx, llama_batch_get_one(&token, n_tokens, n_past, 0), true);
  10028. // initialize scheduler with the worst-case graph
  10029. if (!ggml_backend_sched_reserve(ctx->sched, gf)) {
  10030. LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
  10031. llama_free(ctx);
  10032. return nullptr;
  10033. }
  10034. for (size_t i = 0; i < ctx->backends.size(); i++) {
  10035. ggml_backend_t backend = ctx->backends[i];
  10036. ggml_backend_buffer_type_t buft = backend_buft[i];
  10037. size_t size = ggml_backend_sched_get_buffer_size(ctx->sched, backend);
  10038. LLAMA_LOG_INFO("%s: %10s compute buffer size = %8.2f MiB\n", __func__,
  10039. ggml_backend_buft_name(buft),
  10040. size / 1024.0 / 1024.0);
  10041. }
  10042. // note: the number of splits during measure is higher than during inference due to the kv shift
  10043. int n_splits = ggml_backend_sched_get_n_splits(ctx->sched);
  10044. LLAMA_LOG_INFO("%s: graph splits (measure): %d\n", __func__, n_splits);
  10045. }
  10046. }
  10047. #ifdef GGML_USE_MPI
  10048. ctx->ctx_mpi = ggml_mpi_init();
  10049. if (ggml_mpi_rank(ctx->ctx_mpi) > 0) {
  10050. // Enter a blocking eval loop with dummy input, letting rank=0 drive the process
  10051. // TODO: needs fix after #3228
  10052. GGML_ASSERT(false && "not implemented");
  10053. //const std::vector<llama_token> tmp(ctx->model.hparams.n_ctx, llama_token_bos(ctx));
  10054. //while (!llama_eval(ctx, tmp.data(), tmp.size(), 0, 0)) {};
  10055. llama_backend_free();
  10056. exit(1);
  10057. }
  10058. #endif
  10059. return ctx;
  10060. }
  10061. void llama_free(struct llama_context * ctx) {
  10062. delete ctx;
  10063. }
  10064. const llama_model * llama_get_model(const struct llama_context * ctx) {
  10065. return &ctx->model;
  10066. }
  10067. uint32_t llama_n_ctx(const struct llama_context * ctx) {
  10068. return ctx->cparams.n_ctx;
  10069. }
  10070. uint32_t llama_n_batch(const struct llama_context * ctx) {
  10071. return ctx->cparams.n_batch;
  10072. }
  10073. enum llama_vocab_type llama_vocab_type(const struct llama_model * model) {
  10074. return model->vocab.type;
  10075. }
  10076. enum llama_rope_type llama_rope_type(const struct llama_model * model) {
  10077. switch (model->arch) {
  10078. // these models do not use RoPE
  10079. case LLM_ARCH_GPT2:
  10080. case LLM_ARCH_GPTJ:
  10081. case LLM_ARCH_GPTNEOX:
  10082. case LLM_ARCH_MPT:
  10083. case LLM_ARCH_REFACT:
  10084. case LLM_ARCH_BLOOM:
  10085. return LLAMA_ROPE_TYPE_NONE;
  10086. // use what we call a normal RoPE, operating on pairs of consecutive head values
  10087. case LLM_ARCH_LLAMA:
  10088. case LLM_ARCH_BAICHUAN:
  10089. case LLM_ARCH_STARCODER:
  10090. case LLM_ARCH_PLAMO:
  10091. case LLM_ARCH_CODESHELL:
  10092. case LLM_ARCH_ORION:
  10093. case LLM_ARCH_INTERNLM2:
  10094. case LLM_ARCH_MINICPM:
  10095. return LLAMA_ROPE_TYPE_NORM;
  10096. // the pairs of head values are offset by n_rot/2
  10097. case LLM_ARCH_FALCON:
  10098. case LLM_ARCH_PERSIMMON:
  10099. case LLM_ARCH_BERT:
  10100. case LLM_ARCH_NOMIC_BERT:
  10101. case LLM_ARCH_STABLELM:
  10102. case LLM_ARCH_QWEN:
  10103. case LLM_ARCH_QWEN2:
  10104. case LLM_ARCH_PHI2:
  10105. case LLM_ARCH_GEMMA:
  10106. return LLAMA_ROPE_TYPE_NEOX;
  10107. // all model arches should be listed explicitly here
  10108. case LLM_ARCH_UNKNOWN:
  10109. GGML_ASSERT(false && "unknown architecture");
  10110. break;
  10111. }
  10112. return LLAMA_ROPE_TYPE_NONE;
  10113. }
  10114. int32_t llama_n_vocab(const struct llama_model * model) {
  10115. return model->vocab.id_to_token.size();
  10116. }
  10117. int32_t llama_n_ctx_train(const struct llama_model * model) {
  10118. return model->hparams.n_ctx_train;
  10119. }
  10120. int32_t llama_n_embd(const struct llama_model * model) {
  10121. return model->hparams.n_embd;
  10122. }
  10123. float llama_rope_freq_scale_train(const struct llama_model * model) {
  10124. return model->hparams.rope_freq_scale_train;
  10125. }
  10126. int32_t llama_model_meta_val_str(const struct llama_model * model, const char * key, char * buf, size_t buf_size) {
  10127. const auto & it = model->gguf_kv.find(key);
  10128. if (it == model->gguf_kv.end()) {
  10129. if (buf_size > 0) {
  10130. buf[0] = '\0';
  10131. }
  10132. return -1;
  10133. }
  10134. return snprintf(buf, buf_size, "%s", it->second.c_str());
  10135. }
  10136. int32_t llama_model_meta_count(const struct llama_model * model) {
  10137. return (int)model->gguf_kv.size();
  10138. }
  10139. int32_t llama_model_meta_key_by_index(const struct llama_model * model, int i, char * buf, size_t buf_size) {
  10140. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  10141. if (buf_size > 0) {
  10142. buf[0] = '\0';
  10143. }
  10144. return -1;
  10145. }
  10146. auto it = model->gguf_kv.begin();
  10147. std::advance(it, i);
  10148. return snprintf(buf, buf_size, "%s", it->first.c_str());
  10149. }
  10150. int32_t llama_model_meta_val_str_by_index(const struct llama_model * model, int32_t i, char * buf, size_t buf_size) {
  10151. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  10152. if (buf_size > 0) {
  10153. buf[0] = '\0';
  10154. }
  10155. return -1;
  10156. }
  10157. auto it = model->gguf_kv.begin();
  10158. std::advance(it, i);
  10159. return snprintf(buf, buf_size, "%s", it->second.c_str());
  10160. }
  10161. int32_t llama_model_desc(const struct llama_model * model, char * buf, size_t buf_size) {
  10162. return snprintf(buf, buf_size, "%s %s %s",
  10163. llama_model_arch_name(model->arch),
  10164. llama_model_type_name(model->type),
  10165. llama_model_ftype_name(model->ftype).c_str());
  10166. }
  10167. uint64_t llama_model_size(const struct llama_model * model) {
  10168. uint64_t size = 0;
  10169. for (const auto & it : model->tensors_by_name) {
  10170. size += ggml_nbytes(it.second);
  10171. }
  10172. return size;
  10173. }
  10174. uint64_t llama_model_n_params(const struct llama_model * model) {
  10175. uint64_t nparams = 0;
  10176. for (const auto & it : model->tensors_by_name) {
  10177. nparams += ggml_nelements(it.second);
  10178. }
  10179. return nparams;
  10180. }
  10181. struct ggml_tensor * llama_get_model_tensor(struct llama_model * model, const char * name) {
  10182. auto it = std::find_if(model->tensors_by_name.begin(), model->tensors_by_name.end(),
  10183. [name](const std::pair<std::string, struct ggml_tensor *> & it) {
  10184. return it.first == name;
  10185. });
  10186. if (it == model->tensors_by_name.end()) {
  10187. return nullptr;
  10188. }
  10189. return it->second;
  10190. }
  10191. uint32_t llama_model_quantize(
  10192. const char * fname_inp,
  10193. const char * fname_out,
  10194. const llama_model_quantize_params * params) {
  10195. try {
  10196. llama_model_quantize_internal(fname_inp, fname_out, params);
  10197. return 0;
  10198. } catch (const std::exception & err) {
  10199. LLAMA_LOG_ERROR("%s: failed to quantize: %s\n", __func__, err.what());
  10200. return 1;
  10201. }
  10202. }
  10203. 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) {
  10204. try {
  10205. return llama_apply_lora_from_file_internal(ctx->model, path_lora, scale, path_base_model, n_threads);
  10206. } catch (const std::exception & err) {
  10207. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  10208. return 1;
  10209. }
  10210. }
  10211. 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) {
  10212. try {
  10213. return llama_apply_lora_from_file_internal(*model, path_lora, scale, path_base_model, n_threads);
  10214. } catch (const std::exception & err) {
  10215. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  10216. return 1;
  10217. }
  10218. }
  10219. struct llama_kv_cache_view llama_kv_cache_view_init(const struct llama_context * ctx, int32_t n_max_seq) {
  10220. struct llama_kv_cache_view result = {
  10221. /*.n_cells = */ 0,
  10222. /*.n_max_seq = */ n_max_seq,
  10223. /*.token_count = */ 0,
  10224. /*.used_cells = */ llama_get_kv_cache_used_cells(ctx),
  10225. /*.max_contiguous = */ 0,
  10226. /*.max_contiguous_idx = */ -1,
  10227. /*.cells = */ nullptr,
  10228. /*.cells_sequences = */ nullptr,
  10229. };
  10230. return result;
  10231. }
  10232. void llama_kv_cache_view_free(struct llama_kv_cache_view * view) {
  10233. if (view->cells != nullptr) {
  10234. free(view->cells);
  10235. view->cells = nullptr;
  10236. }
  10237. if (view->cells_sequences != nullptr) {
  10238. free(view->cells_sequences);
  10239. view->cells_sequences = nullptr;
  10240. }
  10241. }
  10242. void llama_kv_cache_view_update(const struct llama_context * ctx, struct llama_kv_cache_view * view) {
  10243. if (uint32_t(view->n_cells) < ctx->kv_self.size || view->cells == nullptr) {
  10244. view->n_cells = int32_t(ctx->kv_self.size);
  10245. void * p = realloc(view->cells, sizeof(struct llama_kv_cache_view_cell) * view->n_cells);
  10246. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells");
  10247. view->cells = (struct llama_kv_cache_view_cell *)p;
  10248. p = realloc(view->cells_sequences, sizeof(llama_seq_id) * view->n_max_seq * view->n_cells);
  10249. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells sequences");
  10250. view->cells_sequences = (llama_seq_id *)p;
  10251. }
  10252. const std::vector<llama_kv_cell> & kv_cells = ctx->kv_self.cells;
  10253. llama_kv_cache_view_cell * c_curr = view->cells;
  10254. llama_seq_id * cs_curr = view->cells_sequences;
  10255. int32_t used_cells = 0;
  10256. int32_t token_count = 0;
  10257. int32_t curr_contig_idx = -1;
  10258. uint32_t max_contig = 0;
  10259. int32_t max_contig_idx = -1;
  10260. for (int32_t i = 0; i < int32_t(ctx->kv_self.size); i++, c_curr++, cs_curr += view->n_max_seq) {
  10261. const size_t curr_size = kv_cells[i].seq_id.size();
  10262. token_count += curr_size;
  10263. c_curr->pos = kv_cells[i].pos + kv_cells[i].delta;
  10264. if (curr_size > 0) {
  10265. if (curr_contig_idx >= 0 && uint32_t(i - curr_contig_idx) > max_contig) {
  10266. max_contig = i - curr_contig_idx;
  10267. max_contig_idx = curr_contig_idx;
  10268. }
  10269. curr_contig_idx = -1;
  10270. } else if (curr_contig_idx < 0) {
  10271. curr_contig_idx = i;
  10272. }
  10273. int seq_idx = 0;
  10274. for (const llama_seq_id it : kv_cells[i].seq_id) {
  10275. if (seq_idx >= view->n_max_seq) {
  10276. break;
  10277. }
  10278. cs_curr[seq_idx] = it;
  10279. seq_idx++;
  10280. }
  10281. if (seq_idx != 0) {
  10282. used_cells++;
  10283. }
  10284. for (; seq_idx < view->n_max_seq; seq_idx++) {
  10285. cs_curr[seq_idx] = -1;
  10286. }
  10287. }
  10288. if (curr_contig_idx >= 0 && kv_cells.size() - curr_contig_idx > max_contig) {
  10289. max_contig_idx = curr_contig_idx;
  10290. max_contig = kv_cells.size() - curr_contig_idx;
  10291. }
  10292. view->max_contiguous = max_contig;
  10293. view->max_contiguous_idx = max_contig_idx;
  10294. view->token_count = token_count;
  10295. view->used_cells = used_cells;
  10296. if (uint32_t(used_cells) != ctx->kv_self.used) {
  10297. LLAMA_LOG_ERROR("%s: used cells mismatch. kv_cache says %d but we calculated %d\n",
  10298. __func__, ctx->kv_self.used, used_cells);
  10299. }
  10300. }
  10301. int32_t llama_get_kv_cache_token_count(const struct llama_context * ctx) {
  10302. int result = 0;
  10303. for (uint32_t i = 0; i < ctx->kv_self.size; i++) {
  10304. result += ctx->kv_self.cells[i].seq_id.size();
  10305. }
  10306. return result;
  10307. }
  10308. int32_t llama_get_kv_cache_used_cells(const struct llama_context * ctx) {
  10309. return ctx->kv_self.used;
  10310. }
  10311. void llama_kv_cache_clear(struct llama_context * ctx) {
  10312. llama_kv_cache_clear(ctx->kv_self);
  10313. }
  10314. void llama_kv_cache_seq_rm(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
  10315. llama_kv_cache_seq_rm(ctx->kv_self, seq_id, p0, p1);
  10316. }
  10317. 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) {
  10318. if (seq_id_src == seq_id_dst) {
  10319. return;
  10320. }
  10321. llama_kv_cache_seq_cp(ctx->kv_self, seq_id_src, seq_id_dst, p0, p1);
  10322. }
  10323. void llama_kv_cache_seq_keep(struct llama_context * ctx, llama_seq_id seq_id) {
  10324. llama_kv_cache_seq_keep(ctx->kv_self, seq_id);
  10325. }
  10326. void llama_kv_cache_seq_add(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos delta) {
  10327. if (delta == 0) {
  10328. return;
  10329. }
  10330. llama_kv_cache_seq_add(ctx->kv_self, seq_id, p0, p1, delta);
  10331. }
  10332. void llama_kv_cache_seq_div(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) {
  10333. if (d == 1) {
  10334. return;
  10335. }
  10336. llama_kv_cache_seq_div(ctx->kv_self, seq_id, p0, p1, d);
  10337. }
  10338. llama_pos llama_kv_cache_seq_pos_max(struct llama_context * ctx, llama_seq_id seq_id) {
  10339. return llama_kv_cache_seq_pos_max(ctx->kv_self, seq_id);
  10340. }
  10341. void llama_kv_cache_defrag(struct llama_context * ctx) {
  10342. llama_kv_cache_defrag(ctx->kv_self);
  10343. }
  10344. void llama_kv_cache_update(struct llama_context * ctx) {
  10345. llama_kv_cache_update_internal(*ctx);
  10346. }
  10347. // Returns the *maximum* size of the state
  10348. size_t llama_get_state_size(const struct llama_context * ctx) {
  10349. // we don't know size of rng until we actually serialize it. so reserve more than enough memory for its serialized state.
  10350. // for reference, std::mt19937(1337) serializes to 6701 bytes.
  10351. const size_t s_rng_size = sizeof(size_t);
  10352. const size_t s_rng = LLAMA_MAX_RNG_STATE;
  10353. const size_t s_logits_size = sizeof(size_t);
  10354. // assume worst case for logits although only currently set ones are serialized
  10355. const size_t s_logits = ctx->logits.capacity() * sizeof(float);
  10356. const size_t s_embedding_size = sizeof(size_t);
  10357. const size_t s_embedding = ctx->embedding.size() * sizeof(float);
  10358. const size_t s_kv_size = sizeof(size_t);
  10359. const size_t s_kv_ntok = sizeof(int);
  10360. const size_t s_kv = ctx->kv_self.total_size();
  10361. const size_t s_total = (
  10362. + s_rng_size
  10363. + s_rng
  10364. + s_logits_size
  10365. + s_logits
  10366. + s_embedding_size
  10367. + s_embedding
  10368. + s_kv_size
  10369. + s_kv_ntok
  10370. + s_kv
  10371. );
  10372. return s_total;
  10373. }
  10374. // llama_context_data
  10375. struct llama_data_context {
  10376. virtual void write(const void * src, size_t size) = 0;
  10377. virtual size_t get_size_written() = 0;
  10378. virtual ~llama_data_context() = default;
  10379. };
  10380. struct llama_data_buffer_context : llama_data_context {
  10381. uint8_t * ptr;
  10382. size_t size_written = 0;
  10383. llama_data_buffer_context(uint8_t * p) : ptr(p) {}
  10384. void write(const void * src, size_t size) override {
  10385. memcpy(ptr, src, size);
  10386. ptr += size;
  10387. size_written += size;
  10388. }
  10389. size_t get_size_written() override {
  10390. return size_written;
  10391. }
  10392. };
  10393. struct llama_data_file_context : llama_data_context {
  10394. llama_file * file;
  10395. size_t size_written = 0;
  10396. llama_data_file_context(llama_file * f) : file(f) {}
  10397. void write(const void * src, size_t size) override {
  10398. file->write_raw(src, size);
  10399. size_written += size;
  10400. }
  10401. size_t get_size_written() override {
  10402. return size_written;
  10403. }
  10404. };
  10405. /** copy state data into either a buffer or file depending on the passed in context
  10406. *
  10407. * file context:
  10408. * llama_file file("/path", "wb");
  10409. * llama_data_file_context data_ctx(&file);
  10410. * llama_copy_state_data(ctx, &data_ctx);
  10411. *
  10412. * buffer context:
  10413. * std::vector<uint8_t> buf(max_size, 0);
  10414. * llama_data_buffer_context data_ctx(&buf.data());
  10415. * llama_copy_state_data(ctx, &data_ctx);
  10416. *
  10417. */
  10418. static void llama_copy_state_data_internal(struct llama_context * ctx, llama_data_context * data_ctx) {
  10419. // copy rng
  10420. {
  10421. std::ostringstream rng_ss;
  10422. rng_ss << ctx->rng;
  10423. const std::string & rng_str = rng_ss.str();
  10424. const size_t rng_size = rng_str.size();
  10425. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  10426. data_ctx->write(&rng_size, sizeof(rng_size));
  10427. data_ctx->write(rng_str.data(), rng_size);
  10428. }
  10429. // copy logits
  10430. {
  10431. const size_t logits_size = ctx->logits.size();
  10432. data_ctx->write(&logits_size, sizeof(logits_size));
  10433. if (logits_size) {
  10434. data_ctx->write(ctx->logits.data(), logits_size * sizeof(float));
  10435. }
  10436. }
  10437. // copy embeddings
  10438. {
  10439. const size_t embedding_size = ctx->embedding.size();
  10440. data_ctx->write(&embedding_size, sizeof(embedding_size));
  10441. if (embedding_size) {
  10442. data_ctx->write(ctx->embedding.data(), embedding_size * sizeof(float));
  10443. }
  10444. }
  10445. // copy kv cache
  10446. {
  10447. const auto & kv_self = ctx->kv_self;
  10448. const auto & hparams = ctx->model.hparams;
  10449. const auto & cparams = ctx->cparams;
  10450. const uint32_t n_layer = hparams.n_layer;
  10451. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  10452. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  10453. const uint32_t n_ctx = cparams.n_ctx;
  10454. const size_t kv_buf_size = kv_self.total_size();
  10455. const uint32_t kv_head = kv_self.head;
  10456. const uint32_t kv_size = kv_self.size;
  10457. const uint32_t kv_used = kv_self.used;
  10458. data_ctx->write(&kv_buf_size, sizeof(kv_buf_size));
  10459. data_ctx->write(&kv_head, sizeof(kv_head));
  10460. data_ctx->write(&kv_size, sizeof(kv_size));
  10461. data_ctx->write(&kv_used, sizeof(kv_used));
  10462. if (kv_buf_size) {
  10463. std::vector<uint8_t> tmp_buf;
  10464. for (int il = 0; il < (int) n_layer; ++il) {
  10465. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_head);
  10466. tmp_buf.resize(k_size);
  10467. ggml_backend_tensor_get(kv_self.k_l[il], tmp_buf.data(), 0, tmp_buf.size());
  10468. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  10469. // v is not contiguous, copy row by row
  10470. const size_t v_row_size = ggml_row_size(kv_self.v_l[il]->type, kv_head);
  10471. const size_t v_row_stride = ggml_row_size(kv_self.v_l[il]->type, n_ctx);
  10472. tmp_buf.resize(v_row_size);
  10473. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  10474. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), ir*v_row_stride, tmp_buf.size());
  10475. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  10476. }
  10477. }
  10478. }
  10479. for (uint32_t i = 0; i < kv_size; ++i) {
  10480. const auto & cell = kv_self.cells[i];
  10481. const llama_pos pos = cell.pos;
  10482. const size_t seq_id_size = cell.seq_id.size();
  10483. data_ctx->write(&pos, sizeof(pos));
  10484. data_ctx->write(&seq_id_size, sizeof(seq_id_size));
  10485. for (auto seq_id : cell.seq_id) {
  10486. data_ctx->write(&seq_id, sizeof(seq_id));
  10487. }
  10488. }
  10489. }
  10490. }
  10491. size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dst) {
  10492. llama_data_buffer_context data_ctx(dst);
  10493. llama_copy_state_data_internal(ctx, &data_ctx);
  10494. return data_ctx.get_size_written();
  10495. }
  10496. // Sets the state reading from the specified source address
  10497. size_t llama_set_state_data(struct llama_context * ctx, uint8_t * src) {
  10498. uint8_t * inp = src;
  10499. // set rng
  10500. {
  10501. size_t rng_size;
  10502. memcpy(&rng_size, inp, sizeof(rng_size)); inp += sizeof(rng_size);
  10503. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  10504. std::string rng_str((char *)inp, rng_size); inp += rng_size;
  10505. std::istringstream rng_ss(rng_str);
  10506. rng_ss >> ctx->rng;
  10507. GGML_ASSERT(!rng_ss.fail());
  10508. }
  10509. // set logits
  10510. {
  10511. size_t logits_size;
  10512. memcpy(&logits_size, inp, sizeof(logits_size)); inp += sizeof(logits_size);
  10513. GGML_ASSERT(ctx->logits.capacity() >= logits_size);
  10514. if (logits_size) {
  10515. ctx->logits.resize(logits_size);
  10516. memcpy(ctx->logits.data(), inp, logits_size * sizeof(float));
  10517. inp += logits_size * sizeof(float);
  10518. }
  10519. }
  10520. // set embeddings
  10521. {
  10522. size_t embedding_size;
  10523. memcpy(&embedding_size, inp, sizeof(embedding_size)); inp += sizeof(embedding_size);
  10524. GGML_ASSERT(ctx->embedding.capacity() == embedding_size);
  10525. if (embedding_size) {
  10526. memcpy(ctx->embedding.data(), inp, embedding_size * sizeof(float));
  10527. inp += embedding_size * sizeof(float);
  10528. }
  10529. }
  10530. // set kv cache
  10531. {
  10532. const auto & kv_self = ctx->kv_self;
  10533. const auto & hparams = ctx->model.hparams;
  10534. const auto & cparams = ctx->cparams;
  10535. const uint32_t n_layer = hparams.n_layer;
  10536. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  10537. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  10538. const uint32_t n_ctx = cparams.n_ctx;
  10539. size_t kv_buf_size;
  10540. uint32_t kv_head;
  10541. uint32_t kv_size;
  10542. uint32_t kv_used;
  10543. memcpy(&kv_buf_size, inp, sizeof(kv_buf_size)); inp += sizeof(kv_buf_size);
  10544. memcpy(&kv_head, inp, sizeof(kv_head)); inp += sizeof(kv_head);
  10545. memcpy(&kv_size, inp, sizeof(kv_size)); inp += sizeof(kv_size);
  10546. memcpy(&kv_used, inp, sizeof(kv_used)); inp += sizeof(kv_used);
  10547. if (kv_buf_size) {
  10548. GGML_ASSERT(kv_self.total_size() == kv_buf_size);
  10549. for (int il = 0; il < (int) n_layer; ++il) {
  10550. const size_t k_size = ggml_row_size(kv_self.k_l[il]->type, n_embd_k_gqa*kv_head);
  10551. ggml_backend_tensor_set(kv_self.k_l[il], inp, 0, k_size);
  10552. inp += k_size;
  10553. // v is not contiguous, copy row by row
  10554. const size_t v_row_size = ggml_row_size(kv_self.v_l[il]->type, kv_head);
  10555. const size_t v_row_stride = ggml_row_size(kv_self.v_l[il]->type, n_ctx);
  10556. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  10557. ggml_backend_tensor_set(kv_self.v_l[il], inp, ir*v_row_stride, v_row_size);
  10558. inp += v_row_size;
  10559. }
  10560. }
  10561. }
  10562. ctx->kv_self.head = kv_head;
  10563. ctx->kv_self.size = kv_size;
  10564. ctx->kv_self.used = kv_used;
  10565. ctx->kv_self.cells.resize(kv_size);
  10566. for (uint32_t i = 0; i < kv_size; ++i) {
  10567. llama_pos pos;
  10568. size_t seq_id_size;
  10569. memcpy(&pos, inp, sizeof(pos)); inp += sizeof(pos);
  10570. memcpy(&seq_id_size, inp, sizeof(seq_id_size)); inp += sizeof(seq_id_size);
  10571. ctx->kv_self.cells[i].pos = pos;
  10572. llama_seq_id seq_id;
  10573. for (size_t j = 0; j < seq_id_size; ++j) {
  10574. memcpy(&seq_id, inp, sizeof(seq_id)); inp += sizeof(seq_id);
  10575. ctx->kv_self.cells[i].seq_id.insert(seq_id);
  10576. }
  10577. }
  10578. }
  10579. const size_t nread = inp - src;
  10580. const size_t max_size = llama_get_state_size(ctx);
  10581. GGML_ASSERT(nread <= max_size);
  10582. return nread;
  10583. }
  10584. 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) {
  10585. llama_file file(path_session, "rb");
  10586. // sanity checks
  10587. {
  10588. const uint32_t magic = file.read_u32();
  10589. const uint32_t version = file.read_u32();
  10590. if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
  10591. LLAMA_LOG_ERROR("%s : unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
  10592. return false;
  10593. }
  10594. llama_hparams session_hparams;
  10595. file.read_raw(&session_hparams, sizeof(llama_hparams));
  10596. if (session_hparams != ctx->model.hparams) {
  10597. LLAMA_LOG_INFO("%s : model hparams didn't match from session file!\n", __func__);
  10598. return false;
  10599. }
  10600. }
  10601. // load the prompt
  10602. {
  10603. const uint32_t n_token_count = file.read_u32();
  10604. if (n_token_count > n_token_capacity) {
  10605. LLAMA_LOG_ERROR("%s : token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  10606. return false;
  10607. }
  10608. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  10609. *n_token_count_out = n_token_count;
  10610. }
  10611. // restore the context state
  10612. {
  10613. const size_t n_state_size_cur = file.size - file.tell();
  10614. const size_t n_state_size_max = llama_get_state_size(ctx);
  10615. if (n_state_size_cur > n_state_size_max) {
  10616. 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);
  10617. return false;
  10618. }
  10619. std::vector<uint8_t> state_data(n_state_size_max);
  10620. file.read_raw(state_data.data(), n_state_size_cur);
  10621. llama_set_state_data(ctx, state_data.data());
  10622. }
  10623. return true;
  10624. }
  10625. 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) {
  10626. try {
  10627. return llama_load_session_file_internal(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  10628. } catch (const std::exception & err) {
  10629. LLAMA_LOG_ERROR("error loading session file: %s\n", err.what());
  10630. return false;
  10631. }
  10632. }
  10633. bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  10634. llama_file file(path_session, "wb");
  10635. file.write_u32(LLAMA_SESSION_MAGIC);
  10636. file.write_u32(LLAMA_SESSION_VERSION);
  10637. file.write_raw(&ctx->model.hparams, sizeof(llama_hparams));
  10638. // save the prompt
  10639. file.write_u32((uint32_t) n_token_count);
  10640. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  10641. // save the context state using stream saving
  10642. llama_data_file_context data_ctx(&file);
  10643. llama_copy_state_data_internal(ctx, &data_ctx);
  10644. return true;
  10645. }
  10646. int llama_eval(
  10647. struct llama_context * ctx,
  10648. llama_token * tokens,
  10649. int32_t n_tokens,
  10650. int32_t n_past) {
  10651. llama_kv_cache_seq_rm(ctx->kv_self, -1, n_past, -1);
  10652. const int ret = llama_decode_internal(*ctx, llama_batch_get_one(tokens, n_tokens, n_past, 0));
  10653. if (ret < 0) {
  10654. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  10655. }
  10656. return ret;
  10657. }
  10658. int llama_eval_embd(
  10659. struct llama_context * ctx,
  10660. float * embd,
  10661. int32_t n_tokens,
  10662. int32_t n_past) {
  10663. llama_kv_cache_seq_rm(ctx->kv_self, -1, n_past, -1);
  10664. llama_batch batch = { n_tokens, nullptr, embd, nullptr, nullptr, nullptr, nullptr, n_past, 1, 0, };
  10665. const int ret = llama_decode_internal(*ctx, batch);
  10666. if (ret < 0) {
  10667. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  10668. }
  10669. return ret;
  10670. }
  10671. void llama_set_n_threads(struct llama_context * ctx, uint32_t n_threads, uint32_t n_threads_batch) {
  10672. ctx->cparams.n_threads = n_threads;
  10673. ctx->cparams.n_threads_batch = n_threads_batch;
  10674. }
  10675. struct llama_batch llama_batch_get_one(
  10676. llama_token * tokens,
  10677. int32_t n_tokens,
  10678. llama_pos pos_0,
  10679. llama_seq_id seq_id) {
  10680. return {
  10681. /*n_tokens =*/ n_tokens,
  10682. /*tokens =*/ tokens,
  10683. /*embd =*/ nullptr,
  10684. /*pos =*/ nullptr,
  10685. /*n_seq_id =*/ nullptr,
  10686. /*seq_id =*/ nullptr,
  10687. /*logits =*/ nullptr,
  10688. /*all_pos_0 =*/ pos_0,
  10689. /*all_pos_1 =*/ 1,
  10690. /*all_seq_id =*/ seq_id,
  10691. };
  10692. }
  10693. struct llama_batch llama_batch_init(int32_t n_tokens_alloc, int32_t embd, int32_t n_seq_max) {
  10694. llama_batch batch = { 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, 0, 0, 0, };
  10695. if (embd) {
  10696. batch.embd = (float *) malloc(sizeof(float) * n_tokens_alloc * embd);
  10697. } else {
  10698. batch.token = (llama_token *) malloc(sizeof(llama_token) * n_tokens_alloc);
  10699. }
  10700. batch.pos = (llama_pos *) malloc(sizeof(llama_pos) * n_tokens_alloc);
  10701. batch.n_seq_id = (int32_t *) malloc(sizeof(int32_t) * n_tokens_alloc);
  10702. batch.seq_id = (llama_seq_id **) malloc(sizeof(llama_seq_id *) * (n_tokens_alloc + 1));
  10703. for (int i = 0; i < n_tokens_alloc; ++i) {
  10704. batch.seq_id[i] = (llama_seq_id *) malloc(sizeof(llama_seq_id) * n_seq_max);
  10705. }
  10706. batch.seq_id[n_tokens_alloc] = nullptr;
  10707. batch.logits = (int8_t *) malloc(sizeof(int8_t) * n_tokens_alloc);
  10708. return batch;
  10709. }
  10710. void llama_batch_free(struct llama_batch batch) {
  10711. if (batch.token) free(batch.token);
  10712. if (batch.embd) free(batch.embd);
  10713. if (batch.pos) free(batch.pos);
  10714. if (batch.n_seq_id) free(batch.n_seq_id);
  10715. if (batch.seq_id) {
  10716. for (int i = 0; batch.seq_id[i] != nullptr; ++i) {
  10717. free(batch.seq_id[i]);
  10718. }
  10719. free(batch.seq_id);
  10720. }
  10721. if (batch.logits) free(batch.logits);
  10722. }
  10723. int32_t llama_decode(
  10724. struct llama_context * ctx,
  10725. struct llama_batch batch) {
  10726. const int ret = llama_decode_internal(*ctx, batch);
  10727. if (ret < 0) {
  10728. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  10729. }
  10730. return ret;
  10731. }
  10732. float * llama_get_logits(struct llama_context * ctx) {
  10733. return ctx->logits.data();
  10734. }
  10735. float * llama_get_logits_ith(struct llama_context * ctx, int32_t i) {
  10736. assert(ctx->logits_valid.at(i));
  10737. return ctx->logits.data() + i*ctx->model.hparams.n_vocab;
  10738. }
  10739. float * llama_get_embeddings(struct llama_context * ctx) {
  10740. return ctx->embedding.data();
  10741. }
  10742. float * llama_get_embeddings_ith(struct llama_context * ctx, int32_t i) {
  10743. return ctx->embedding.data() + i*ctx->model.hparams.n_embd;
  10744. }
  10745. const char * llama_token_get_text(const struct llama_model * model, llama_token token) {
  10746. return model->vocab.id_to_token[token].text.c_str();
  10747. }
  10748. float llama_token_get_score(const struct llama_model * model, llama_token token) {
  10749. return model->vocab.id_to_token[token].score;
  10750. }
  10751. llama_token_type llama_token_get_type(const struct llama_model * model, llama_token token) {
  10752. return model->vocab.id_to_token[token].type;
  10753. }
  10754. llama_token llama_token_bos(const struct llama_model * model) {
  10755. return model->vocab.special_bos_id;
  10756. }
  10757. llama_token llama_token_eos(const struct llama_model * model) {
  10758. return model->vocab.special_eos_id;
  10759. }
  10760. llama_token llama_token_nl(const struct llama_model * model) {
  10761. return model->vocab.linefeed_id;
  10762. }
  10763. int32_t llama_add_bos_token(const struct llama_model * model) {
  10764. return model->vocab.special_add_bos;
  10765. }
  10766. int32_t llama_add_eos_token(const struct llama_model * model) {
  10767. return model->vocab.special_add_eos;
  10768. }
  10769. llama_token llama_token_prefix(const struct llama_model * model) {
  10770. return model->vocab.special_prefix_id;
  10771. }
  10772. llama_token llama_token_middle(const struct llama_model * model) {
  10773. return model->vocab.special_middle_id;
  10774. }
  10775. llama_token llama_token_suffix(const struct llama_model * model) {
  10776. return model->vocab.special_suffix_id;
  10777. }
  10778. llama_token llama_token_eot(const struct llama_model * model) {
  10779. return model->vocab.special_eot_id;
  10780. }
  10781. int32_t llama_tokenize(
  10782. const struct llama_model * model,
  10783. const char * text,
  10784. int32_t text_len,
  10785. llama_token * tokens,
  10786. int32_t n_max_tokens,
  10787. bool add_bos,
  10788. bool special) {
  10789. auto res = llama_tokenize_internal(model->vocab, std::string(text, text_len), add_bos, special);
  10790. if (n_max_tokens < (int) res.size()) {
  10791. // LLAMA_LOG_ERROR("%s: too many tokens\n", __func__);
  10792. return -((int) res.size());
  10793. }
  10794. for (size_t i = 0; i < res.size(); i++) {
  10795. tokens[i] = res[i];
  10796. }
  10797. return res.size();
  10798. }
  10799. static std::string llama_decode_text(const std::string & text) {
  10800. std::string decoded_text;
  10801. auto unicode_sequences = codepoints_from_utf8(text);
  10802. for (auto& unicode_sequence : unicode_sequences) {
  10803. decoded_text += unicode_to_bytes_bpe(codepoint_to_utf8(unicode_sequence));
  10804. }
  10805. return decoded_text;
  10806. }
  10807. // does not write null-terminator to buf
  10808. int32_t llama_token_to_piece(const struct llama_model * model, llama_token token, char * buf, int32_t length) {
  10809. if (0 <= token && token < llama_n_vocab(model)) {
  10810. switch (llama_vocab_get_type(model->vocab)) {
  10811. case LLAMA_VOCAB_TYPE_WPM:
  10812. case LLAMA_VOCAB_TYPE_SPM: {
  10813. // NOTE: we accept all unsupported token types,
  10814. // suppressing them like CONTROL tokens.
  10815. if (llama_is_normal_token(model->vocab, token)) {
  10816. std::string result = model->vocab.id_to_token[token].text;
  10817. llama_unescape_whitespace(result);
  10818. if (length < (int) result.length()) {
  10819. return -(int) result.length();
  10820. }
  10821. memcpy(buf, result.c_str(), result.length());
  10822. return result.length();
  10823. } else if (llama_is_user_defined_token(model->vocab, token)) {
  10824. std::string result = model->vocab.id_to_token[token].text;
  10825. if (length < (int) result.length()) {
  10826. return -result.length();
  10827. }
  10828. memcpy(buf, result.c_str(), result.length());
  10829. return result.length();
  10830. } else if (llama_is_unknown_token(model->vocab, token)) { // NOLINT
  10831. if (length < 3) {
  10832. return -3;
  10833. }
  10834. memcpy(buf, "\xe2\x96\x85", 3);
  10835. return 3;
  10836. } else if (llama_is_control_token(model->vocab, token)) {
  10837. ;
  10838. } else if (llama_is_byte_token(model->vocab, token)) {
  10839. if (length < 1) {
  10840. return -1;
  10841. }
  10842. buf[0] = llama_token_to_byte(model->vocab, token);
  10843. return 1;
  10844. }
  10845. break;
  10846. }
  10847. case LLAMA_VOCAB_TYPE_BPE: {
  10848. // NOTE: we accept all unsupported token types,
  10849. // suppressing them like CONTROL tokens.
  10850. if (llama_is_normal_token(model->vocab, token)) {
  10851. std::string result = model->vocab.id_to_token[token].text;
  10852. result = llama_decode_text(result);
  10853. if (length < (int) result.length()) {
  10854. return -(int) result.length();
  10855. }
  10856. memcpy(buf, result.c_str(), result.length());
  10857. return result.length();
  10858. } else if (llama_is_user_defined_token(model->vocab, token)) {
  10859. std::string result = model->vocab.id_to_token[token].text;
  10860. if (length < (int) result.length()) {
  10861. return -result.length();
  10862. }
  10863. memcpy(buf, result.c_str(), result.length());
  10864. return result.length();
  10865. } else if (llama_is_control_token(model->vocab, token)) {
  10866. ;
  10867. }
  10868. break;
  10869. }
  10870. default:
  10871. GGML_ASSERT(false);
  10872. }
  10873. }
  10874. return 0;
  10875. }
  10876. // trim whitespace from the beginning and end of a string
  10877. static std::string trim(const std::string & str) {
  10878. size_t start = 0;
  10879. size_t end = str.size();
  10880. while (start < end && isspace(str[start])) {
  10881. start += 1;
  10882. }
  10883. while (end > start && isspace(str[end - 1])) {
  10884. end -= 1;
  10885. }
  10886. return str.substr(start, end - start);
  10887. }
  10888. // Simple version of "llama_apply_chat_template" that only works with strings
  10889. // This function uses heuristic checks to determine commonly used template. It is not a jinja parser.
  10890. static int32_t llama_chat_apply_template_internal(
  10891. const std::string & tmpl,
  10892. const std::vector<const llama_chat_message *> & chat,
  10893. std::string & dest, bool add_ass) {
  10894. // Taken from the research: https://github.com/ggerganov/llama.cpp/issues/5527
  10895. std::stringstream ss;
  10896. if (tmpl.find("<|im_start|>") != std::string::npos) {
  10897. // chatml template
  10898. for (auto message : chat) {
  10899. ss << "<|im_start|>" << message->role << "\n" << message->content << "<|im_end|>\n";
  10900. }
  10901. if (add_ass) {
  10902. ss << "<|im_start|>assistant\n";
  10903. }
  10904. } else if (tmpl.find("[INST]") != std::string::npos) {
  10905. // llama2 template and its variants
  10906. // [variant] support system message
  10907. bool support_system_message = tmpl.find("<<SYS>>") != std::string::npos;
  10908. // [variant] space before + after response
  10909. bool space_around_response = tmpl.find("' ' + eos_token") != std::string::npos;
  10910. // [variant] add BOS inside history
  10911. bool add_bos_inside_history = tmpl.find("bos_token + '[INST]") != std::string::npos;
  10912. // [variant] trim spaces from the input message
  10913. bool strip_message = tmpl.find("content.strip()") != std::string::npos;
  10914. // construct the prompt
  10915. bool is_inside_turn = true; // skip BOS at the beginning
  10916. ss << "[INST] ";
  10917. for (auto message : chat) {
  10918. std::string content = strip_message ? trim(message->content) : message->content;
  10919. std::string role(message->role);
  10920. if (!is_inside_turn) {
  10921. is_inside_turn = true;
  10922. ss << (add_bos_inside_history ? "<s>[INST] " : "[INST] ");
  10923. }
  10924. if (role == "system") {
  10925. if (support_system_message) {
  10926. ss << "<<SYS>>\n" << content << "\n<</SYS>>\n\n";
  10927. } else {
  10928. // if the model does not support system message, we still include it in the first message, but without <<SYS>>
  10929. ss << content << "\n";
  10930. }
  10931. } else if (role == "user") {
  10932. ss << content << " [/INST]";
  10933. } else {
  10934. ss << (space_around_response ? " " : "") << content << (space_around_response ? " " : "") << "</s>";
  10935. is_inside_turn = false;
  10936. }
  10937. }
  10938. // llama2 templates seem to not care about "add_generation_prompt"
  10939. } else if (tmpl.find("<|user|>") != std::string::npos) {
  10940. // zephyr template
  10941. for (auto message : chat) {
  10942. ss << "<|" << message->role << "|>" << "\n" << message->content << "<|endoftext|>\n";
  10943. }
  10944. if (add_ass) {
  10945. ss << "<|assistant|>\n";
  10946. }
  10947. } else if (tmpl.find("bos_token + message['role']") != std::string::npos) {
  10948. // mlabonne/AlphaMonarch-7B template (the <s> is included inside history)
  10949. for (auto message : chat) {
  10950. std::string bos = (message == chat.front()) ? "" : "<s>"; // skip BOS for first message
  10951. ss << bos << message->role << "\n" << message->content << "</s>\n";
  10952. }
  10953. if (add_ass) {
  10954. ss << "<s>assistant\n";
  10955. }
  10956. } else if (tmpl.find("<start_of_turn>") != std::string::npos) {
  10957. // google/gemma-7b-it
  10958. std::string system_prompt = "";
  10959. for (auto message : chat) {
  10960. std::string role(message->role);
  10961. if (role == "system") {
  10962. // there is no system message for gemma, but we will merge it with user prompt, so nothing is broken
  10963. system_prompt = trim(message->content);
  10964. continue;
  10965. }
  10966. // in gemma, "assistant" is "model"
  10967. role = role == "assistant" ? "model" : message->role;
  10968. ss << "<start_of_turn>" << role << "\n";
  10969. if (!system_prompt.empty() && role != "model") {
  10970. ss << system_prompt << "\n\n";
  10971. system_prompt = "";
  10972. }
  10973. ss << trim(message->content) << "<end_of_turn>\n";
  10974. }
  10975. if (add_ass) {
  10976. ss << "<start_of_turn>model\n";
  10977. }
  10978. } else {
  10979. // template not supported
  10980. return -1;
  10981. }
  10982. dest = ss.str();
  10983. return dest.size();
  10984. }
  10985. LLAMA_API int32_t llama_chat_apply_template(
  10986. const struct llama_model * model,
  10987. const char * tmpl,
  10988. const struct llama_chat_message * chat,
  10989. size_t n_msg,
  10990. bool add_ass,
  10991. char * buf,
  10992. int32_t length) {
  10993. std::string curr_tmpl(tmpl == nullptr ? "" : tmpl);
  10994. if (tmpl == nullptr) {
  10995. GGML_ASSERT(model != nullptr);
  10996. // load template from model
  10997. std::vector<char> model_template(2048, 0); // longest known template is about 1200 bytes
  10998. std::string template_key = "tokenizer.chat_template";
  10999. int32_t res = llama_model_meta_val_str(model, template_key.c_str(), model_template.data(), model_template.size());
  11000. if (res < 0) {
  11001. // worst case: there is no information about template, we will use chatml by default
  11002. curr_tmpl = "<|im_start|>"; // see llama_chat_apply_template_internal
  11003. } else {
  11004. curr_tmpl = std::string(model_template.data(), model_template.size());
  11005. }
  11006. }
  11007. // format the chat to string
  11008. std::vector<const llama_chat_message *> chat_vec;
  11009. chat_vec.resize(n_msg);
  11010. for (size_t i = 0; i < n_msg; i++) {
  11011. chat_vec[i] = &chat[i];
  11012. }
  11013. std::string formatted_chat;
  11014. int32_t res = llama_chat_apply_template_internal(curr_tmpl, chat_vec, formatted_chat, add_ass);
  11015. if (res < 0) {
  11016. return res;
  11017. }
  11018. strncpy(buf, formatted_chat.c_str(), length);
  11019. return res;
  11020. }
  11021. struct llama_timings llama_get_timings(struct llama_context * ctx) {
  11022. struct llama_timings result = {
  11023. /*.t_start_ms =*/ 1e-3 * ctx->t_start_us,
  11024. /*.t_end_ms =*/ 1.00 * ggml_time_ms(),
  11025. /*.t_load_ms =*/ 1e-3 * ctx->t_load_us,
  11026. /*.t_sample_ms =*/ 1e-3 * ctx->t_sample_us,
  11027. /*.t_p_eval_ms =*/ 1e-3 * ctx->t_p_eval_us,
  11028. /*.t_eval_ms =*/ 1e-3 * ctx->t_eval_us,
  11029. /*.n_sample =*/ std::max(1, ctx->n_sample),
  11030. /*.n_p_eval =*/ std::max(1, ctx->n_p_eval),
  11031. /*.n_eval =*/ std::max(1, ctx->n_eval),
  11032. };
  11033. return result;
  11034. }
  11035. void llama_print_timings(struct llama_context * ctx) {
  11036. const llama_timings timings = llama_get_timings(ctx);
  11037. LLAMA_LOG_INFO("\n");
  11038. LLAMA_LOG_INFO("%s: load time = %10.2f ms\n", __func__, timings.t_load_ms);
  11039. LLAMA_LOG_INFO("%s: sample time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  11040. __func__, timings.t_sample_ms, timings.n_sample, timings.t_sample_ms / timings.n_sample, 1e3 / timings.t_sample_ms * timings.n_sample);
  11041. LLAMA_LOG_INFO("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  11042. __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);
  11043. LLAMA_LOG_INFO("%s: eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  11044. __func__, timings.t_eval_ms, timings.n_eval, timings.t_eval_ms / timings.n_eval, 1e3 / timings.t_eval_ms * timings.n_eval);
  11045. 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));
  11046. }
  11047. void llama_reset_timings(struct llama_context * ctx) {
  11048. ctx->t_start_us = ggml_time_us();
  11049. ctx->t_sample_us = ctx->n_sample = 0;
  11050. ctx->t_eval_us = ctx->n_eval = 0;
  11051. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  11052. }
  11053. const char * llama_print_system_info(void) {
  11054. static std::string s;
  11055. s = "";
  11056. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  11057. s += "AVX_VNNI = " + std::to_string(ggml_cpu_has_avx_vnni()) + " | ";
  11058. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  11059. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  11060. s += "AVX512_VBMI = " + std::to_string(ggml_cpu_has_avx512_vbmi()) + " | ";
  11061. s += "AVX512_VNNI = " + std::to_string(ggml_cpu_has_avx512_vnni()) + " | ";
  11062. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  11063. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  11064. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  11065. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  11066. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  11067. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  11068. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  11069. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  11070. s += "SSSE3 = " + std::to_string(ggml_cpu_has_ssse3()) + " | ";
  11071. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  11072. s += "MATMUL_INT8 = " + std::to_string(ggml_cpu_has_matmul_int8()) + " | ";
  11073. return s.c_str();
  11074. }
  11075. void llama_dump_timing_info_yaml(FILE * stream, const llama_context * ctx) {
  11076. fprintf(stream, "\n");
  11077. fprintf(stream, "###########\n");
  11078. fprintf(stream, "# Timings #\n");
  11079. fprintf(stream, "###########\n");
  11080. fprintf(stream, "\n");
  11081. fprintf(stream, "mst_eval: %.2f # ms / token during generation\n",
  11082. 1.0e-3 * ctx->t_eval_us / ctx->n_eval);
  11083. fprintf(stream, "mst_p_eval: %.2f # ms / token during prompt processing\n",
  11084. 1.0e-3 * ctx->t_p_eval_us / ctx->n_p_eval);
  11085. fprintf(stream, "mst_sample: %.2f # ms / token during sampling\n",
  11086. 1.0e-3 * ctx->t_sample_us / ctx->n_sample);
  11087. fprintf(stream, "n_eval: %d # number of tokens generated (excluding the first one)\n", ctx->n_eval);
  11088. fprintf(stream, "n_p_eval: %d # number of tokens processed in batches at the beginning\n", ctx->n_p_eval);
  11089. fprintf(stream, "n_sample: %d # number of sampled tokens\n", ctx->n_sample);
  11090. fprintf(stream, "t_eval_us: %" PRId64 " # total microseconds spent generating tokens\n", ctx->t_eval_us);
  11091. fprintf(stream, "t_load_us: %" PRId64 " # total microseconds spent loading the model\n", ctx->t_load_us);
  11092. fprintf(stream, "t_p_eval_us: %" PRId64 " # total microseconds spent prompt processing\n", ctx->t_p_eval_us);
  11093. fprintf(stream, "t_sample_us: %" PRId64 " # total microseconds spent sampling\n", ctx->t_sample_us);
  11094. fprintf(stream, "ts_eval: %.2f # tokens / second during generation\n",
  11095. 1.0e6 * ctx->n_eval / ctx->t_eval_us);
  11096. fprintf(stream, "ts_p_eval: %.2f # tokens / second during prompt processing\n",
  11097. 1.0e6 * ctx->n_p_eval / ctx->t_p_eval_us);
  11098. fprintf(stream, "ts_sample: %.2f # tokens / second during sampling\n",
  11099. 1.0e6 * ctx->n_sample / ctx->t_sample_us);
  11100. }
  11101. // For internal test use
  11102. const std::vector<std::pair<std::string, struct ggml_tensor *>> & llama_internal_get_tensor_map(
  11103. struct llama_context * ctx
  11104. ) {
  11105. return ctx->model.tensors_by_name;
  11106. }
  11107. void llama_log_set(ggml_log_callback log_callback, void * user_data) {
  11108. g_state.log_callback = log_callback ? log_callback : llama_log_callback_default;
  11109. g_state.log_callback_user_data = user_data;
  11110. #ifdef GGML_USE_METAL
  11111. ggml_backend_metal_log_set_callback(g_state.log_callback, g_state.log_callback_user_data);
  11112. #endif
  11113. }
  11114. static void llama_log_internal_v(ggml_log_level level, const char * format, va_list args) {
  11115. va_list args_copy;
  11116. va_copy(args_copy, args);
  11117. char buffer[128];
  11118. int len = vsnprintf(buffer, 128, format, args);
  11119. if (len < 128) {
  11120. g_state.log_callback(level, buffer, g_state.log_callback_user_data);
  11121. } else {
  11122. char* buffer2 = new char[len+1];
  11123. vsnprintf(buffer2, len+1, format, args_copy);
  11124. buffer2[len] = 0;
  11125. g_state.log_callback(level, buffer2, g_state.log_callback_user_data);
  11126. delete[] buffer2;
  11127. }
  11128. va_end(args_copy);
  11129. }
  11130. static void llama_log_internal(ggml_log_level level, const char * format, ...) {
  11131. va_list args;
  11132. va_start(args, format);
  11133. llama_log_internal_v(level, format, args);
  11134. va_end(args);
  11135. }
  11136. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data) {
  11137. (void) level;
  11138. (void) user_data;
  11139. fputs(text, stderr);
  11140. fflush(stderr);
  11141. }