llama.cpp 427 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141
  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. #endif
  12. #ifdef GGML_USE_METAL
  13. # include "ggml-metal.h"
  14. #endif
  15. #ifdef GGML_USE_MPI
  16. # include "ggml-mpi.h"
  17. #endif
  18. #ifndef QK_K
  19. # ifdef GGML_QKK_64
  20. # define QK_K 64
  21. # else
  22. # define QK_K 256
  23. # endif
  24. #endif
  25. #ifdef __has_include
  26. #if __has_include(<unistd.h>)
  27. #include <unistd.h>
  28. #if defined(_POSIX_MAPPED_FILES)
  29. #include <sys/mman.h>
  30. #include <fcntl.h>
  31. #endif
  32. #if defined(_POSIX_MEMLOCK_RANGE)
  33. #include <sys/resource.h>
  34. #endif
  35. #endif
  36. #endif
  37. #if defined(_WIN32)
  38. #define WIN32_LEAN_AND_MEAN
  39. #ifndef NOMINMAX
  40. #define NOMINMAX
  41. #endif
  42. #include <windows.h>
  43. #include <io.h>
  44. #endif
  45. #include <algorithm>
  46. #include <array>
  47. #include <cassert>
  48. #include <cinttypes>
  49. #include <climits>
  50. #include <cmath>
  51. #include <cstdarg>
  52. #include <cstddef>
  53. #include <cstdint>
  54. #include <cstdio>
  55. #include <cstring>
  56. #include <ctime>
  57. #include <forward_list>
  58. #include <fstream>
  59. #include <functional>
  60. #include <initializer_list>
  61. #include <map>
  62. #include <memory>
  63. #include <mutex>
  64. #include <numeric>
  65. #include <queue>
  66. #include <random>
  67. #include <regex>
  68. #include <set>
  69. #include <sstream>
  70. #include <thread>
  71. #include <type_traits>
  72. #include <unordered_map>
  73. #if defined(_MSC_VER)
  74. #pragma warning(disable: 4244 4267) // possible loss of data
  75. #endif
  76. #ifdef __GNUC__
  77. #ifdef __MINGW32__
  78. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(gnu_printf, __VA_ARGS__)))
  79. #else
  80. #define LLAMA_ATTRIBUTE_FORMAT(...) __attribute__((format(printf, __VA_ARGS__)))
  81. #endif
  82. #else
  83. #define LLAMA_ATTRIBUTE_FORMAT(...)
  84. #endif
  85. #define LLAMA_MAX_NODES 8192
  86. #define LLAMA_MAX_EXPERTS 8
  87. //
  88. // logging
  89. //
  90. LLAMA_ATTRIBUTE_FORMAT(2, 3)
  91. static void llama_log_internal (ggml_log_level level, const char* format, ...);
  92. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data);
  93. #define LLAMA_LOG_INFO(...) llama_log_internal(GGML_LOG_LEVEL_INFO , __VA_ARGS__)
  94. #define LLAMA_LOG_WARN(...) llama_log_internal(GGML_LOG_LEVEL_WARN , __VA_ARGS__)
  95. #define LLAMA_LOG_ERROR(...) llama_log_internal(GGML_LOG_LEVEL_ERROR, __VA_ARGS__)
  96. //
  97. // helpers
  98. //
  99. static size_t utf8_len(char src) {
  100. const size_t lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4 };
  101. uint8_t highbits = static_cast<uint8_t>(src) >> 4;
  102. return lookup[highbits];
  103. }
  104. static void replace_all(std::string & s, const std::string & search, const std::string & replace) {
  105. std::string result;
  106. for (size_t pos = 0; ; pos += search.length()) {
  107. auto new_pos = s.find(search, pos);
  108. if (new_pos == std::string::npos) {
  109. result += s.substr(pos, s.size() - pos);
  110. break;
  111. }
  112. result += s.substr(pos, new_pos - pos) + replace;
  113. pos = new_pos;
  114. }
  115. s = std::move(result);
  116. }
  117. static bool is_float_close(float a, float b, float abs_tol) {
  118. // Check for non-negative tolerance
  119. if (abs_tol < 0.0) {
  120. throw std::invalid_argument("Tolerance must be non-negative");
  121. }
  122. // Exact equality check
  123. if (a == b) {
  124. return true;
  125. }
  126. // Check for infinities
  127. if (std::isinf(a) || std::isinf(b)) {
  128. return false;
  129. }
  130. // Regular comparison using the provided absolute tolerance
  131. return std::fabs(b - a) <= abs_tol;
  132. }
  133. static void zeros(std::ofstream & file, size_t n) {
  134. char zero = 0;
  135. for (size_t i = 0; i < n; ++i) {
  136. file.write(&zero, 1);
  137. }
  138. }
  139. LLAMA_ATTRIBUTE_FORMAT(1, 2)
  140. static std::string format(const char * fmt, ...) {
  141. va_list ap;
  142. va_list ap2;
  143. va_start(ap, fmt);
  144. va_copy(ap2, ap);
  145. int size = vsnprintf(NULL, 0, fmt, ap);
  146. GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
  147. std::vector<char> buf(size + 1);
  148. int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
  149. GGML_ASSERT(size2 == size);
  150. va_end(ap2);
  151. va_end(ap);
  152. return std::string(buf.data(), size);
  153. }
  154. //
  155. // gguf constants (sync with gguf.py)
  156. //
  157. enum llm_arch {
  158. LLM_ARCH_LLAMA,
  159. LLM_ARCH_FALCON,
  160. LLM_ARCH_BAICHUAN,
  161. LLM_ARCH_GPT2,
  162. LLM_ARCH_GPTJ,
  163. LLM_ARCH_GPTNEOX,
  164. LLM_ARCH_MPT,
  165. LLM_ARCH_STARCODER,
  166. LLM_ARCH_PERSIMMON,
  167. LLM_ARCH_REFACT,
  168. LLM_ARCH_BLOOM,
  169. LLM_ARCH_STABLELM,
  170. LLM_ARCH_QWEN,
  171. LLM_ARCH_QWEN2,
  172. LLM_ARCH_PHI2,
  173. LLM_ARCH_PLAMO,
  174. LLM_ARCH_CODESHELL,
  175. LLM_ARCH_UNKNOWN,
  176. };
  177. static std::map<llm_arch, std::string> LLM_ARCH_NAMES = {
  178. { LLM_ARCH_LLAMA, "llama" },
  179. { LLM_ARCH_FALCON, "falcon" },
  180. { LLM_ARCH_GPT2, "gpt2" },
  181. { LLM_ARCH_GPTJ, "gptj" },
  182. { LLM_ARCH_GPTNEOX, "gptneox" },
  183. { LLM_ARCH_MPT, "mpt" },
  184. { LLM_ARCH_BAICHUAN, "baichuan" },
  185. { LLM_ARCH_STARCODER, "starcoder" },
  186. { LLM_ARCH_PERSIMMON, "persimmon" },
  187. { LLM_ARCH_REFACT, "refact" },
  188. { LLM_ARCH_BLOOM, "bloom" },
  189. { LLM_ARCH_STABLELM, "stablelm" },
  190. { LLM_ARCH_QWEN, "qwen" },
  191. { LLM_ARCH_QWEN2, "qwen2" },
  192. { LLM_ARCH_PHI2, "phi2" },
  193. { LLM_ARCH_PLAMO, "plamo" },
  194. { LLM_ARCH_CODESHELL, "codeshell" },
  195. };
  196. enum llm_kv {
  197. LLM_KV_GENERAL_ARCHITECTURE,
  198. LLM_KV_GENERAL_QUANTIZATION_VERSION,
  199. LLM_KV_GENERAL_ALIGNMENT,
  200. LLM_KV_GENERAL_NAME,
  201. LLM_KV_GENERAL_AUTHOR,
  202. LLM_KV_GENERAL_URL,
  203. LLM_KV_GENERAL_DESCRIPTION,
  204. LLM_KV_GENERAL_LICENSE,
  205. LLM_KV_GENERAL_SOURCE_URL,
  206. LLM_KV_GENERAL_SOURCE_HF_REPO,
  207. LLM_KV_CONTEXT_LENGTH,
  208. LLM_KV_EMBEDDING_LENGTH,
  209. LLM_KV_BLOCK_COUNT,
  210. LLM_KV_FEED_FORWARD_LENGTH,
  211. LLM_KV_USE_PARALLEL_RESIDUAL,
  212. LLM_KV_TENSOR_DATA_LAYOUT,
  213. LLM_KV_EXPERT_COUNT,
  214. LLM_KV_EXPERT_USED_COUNT,
  215. LLM_KV_ATTENTION_HEAD_COUNT,
  216. LLM_KV_ATTENTION_HEAD_COUNT_KV,
  217. LLM_KV_ATTENTION_MAX_ALIBI_BIAS,
  218. LLM_KV_ATTENTION_CLAMP_KQV,
  219. LLM_KV_ATTENTION_KEY_LENGTH,
  220. LLM_KV_ATTENTION_VALUE_LENGTH,
  221. LLM_KV_ATTENTION_LAYERNORM_EPS,
  222. LLM_KV_ATTENTION_LAYERNORM_RMS_EPS,
  223. LLM_KV_ROPE_DIMENSION_COUNT,
  224. LLM_KV_ROPE_FREQ_BASE,
  225. LLM_KV_ROPE_SCALE_LINEAR,
  226. LLM_KV_ROPE_SCALING_TYPE,
  227. LLM_KV_ROPE_SCALING_FACTOR,
  228. LLM_KV_ROPE_SCALING_ORIG_CTX_LEN,
  229. LLM_KV_ROPE_SCALING_FINETUNED,
  230. LLM_KV_TOKENIZER_MODEL,
  231. LLM_KV_TOKENIZER_LIST,
  232. LLM_KV_TOKENIZER_TOKEN_TYPE,
  233. LLM_KV_TOKENIZER_SCORES,
  234. LLM_KV_TOKENIZER_MERGES,
  235. LLM_KV_TOKENIZER_BOS_ID,
  236. LLM_KV_TOKENIZER_EOS_ID,
  237. LLM_KV_TOKENIZER_UNK_ID,
  238. LLM_KV_TOKENIZER_SEP_ID,
  239. LLM_KV_TOKENIZER_PAD_ID,
  240. LLM_KV_TOKENIZER_ADD_BOS,
  241. LLM_KV_TOKENIZER_ADD_EOS,
  242. LLM_KV_TOKENIZER_HF_JSON,
  243. LLM_KV_TOKENIZER_RWKV,
  244. };
  245. static std::map<llm_kv, std::string> LLM_KV_NAMES = {
  246. { LLM_KV_GENERAL_ARCHITECTURE, "general.architecture" },
  247. { LLM_KV_GENERAL_QUANTIZATION_VERSION, "general.quantization_version" },
  248. { LLM_KV_GENERAL_ALIGNMENT, "general.alignment" },
  249. { LLM_KV_GENERAL_NAME, "general.name" },
  250. { LLM_KV_GENERAL_AUTHOR, "general.author" },
  251. { LLM_KV_GENERAL_URL, "general.url" },
  252. { LLM_KV_GENERAL_DESCRIPTION, "general.description" },
  253. { LLM_KV_GENERAL_LICENSE, "general.license" },
  254. { LLM_KV_GENERAL_SOURCE_URL, "general.source.url" },
  255. { LLM_KV_GENERAL_SOURCE_HF_REPO, "general.source.huggingface.repository" },
  256. { LLM_KV_CONTEXT_LENGTH, "%s.context_length" },
  257. { LLM_KV_EMBEDDING_LENGTH, "%s.embedding_length" },
  258. { LLM_KV_BLOCK_COUNT, "%s.block_count" },
  259. { LLM_KV_FEED_FORWARD_LENGTH, "%s.feed_forward_length" },
  260. { LLM_KV_USE_PARALLEL_RESIDUAL, "%s.use_parallel_residual" },
  261. { LLM_KV_TENSOR_DATA_LAYOUT, "%s.tensor_data_layout" },
  262. { LLM_KV_EXPERT_COUNT, "%s.expert_count" },
  263. { LLM_KV_EXPERT_USED_COUNT, "%s.expert_used_count" },
  264. { LLM_KV_ATTENTION_HEAD_COUNT, "%s.attention.head_count" },
  265. { LLM_KV_ATTENTION_HEAD_COUNT_KV, "%s.attention.head_count_kv" },
  266. { LLM_KV_ATTENTION_MAX_ALIBI_BIAS, "%s.attention.max_alibi_bias" },
  267. { LLM_KV_ATTENTION_CLAMP_KQV, "%s.attention.clamp_kqv" },
  268. { LLM_KV_ATTENTION_KEY_LENGTH, "%s.attention.key_length" },
  269. { LLM_KV_ATTENTION_VALUE_LENGTH, "%s.attention.value_length" },
  270. { LLM_KV_ATTENTION_LAYERNORM_EPS, "%s.attention.layer_norm_epsilon" },
  271. { LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, "%s.attention.layer_norm_rms_epsilon" },
  272. { LLM_KV_ROPE_DIMENSION_COUNT, "%s.rope.dimension_count" },
  273. { LLM_KV_ROPE_FREQ_BASE, "%s.rope.freq_base" },
  274. { LLM_KV_ROPE_SCALE_LINEAR, "%s.rope.scale_linear" },
  275. { LLM_KV_ROPE_SCALING_TYPE, "%s.rope.scaling.type" },
  276. { LLM_KV_ROPE_SCALING_FACTOR, "%s.rope.scaling.factor" },
  277. { LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, "%s.rope.scaling.original_context_length" },
  278. { LLM_KV_ROPE_SCALING_FINETUNED, "%s.rope.scaling.finetuned" },
  279. { LLM_KV_TOKENIZER_MODEL, "tokenizer.ggml.model" },
  280. { LLM_KV_TOKENIZER_LIST, "tokenizer.ggml.tokens" },
  281. { LLM_KV_TOKENIZER_TOKEN_TYPE, "tokenizer.ggml.token_type" },
  282. { LLM_KV_TOKENIZER_SCORES, "tokenizer.ggml.scores" },
  283. { LLM_KV_TOKENIZER_MERGES, "tokenizer.ggml.merges" },
  284. { LLM_KV_TOKENIZER_BOS_ID, "tokenizer.ggml.bos_token_id" },
  285. { LLM_KV_TOKENIZER_EOS_ID, "tokenizer.ggml.eos_token_id" },
  286. { LLM_KV_TOKENIZER_UNK_ID, "tokenizer.ggml.unknown_token_id" },
  287. { LLM_KV_TOKENIZER_SEP_ID, "tokenizer.ggml.seperator_token_id" },
  288. { LLM_KV_TOKENIZER_PAD_ID, "tokenizer.ggml.padding_token_id" },
  289. { LLM_KV_TOKENIZER_ADD_BOS, "tokenizer.ggml.add_bos_token" },
  290. { LLM_KV_TOKENIZER_ADD_EOS, "tokenizer.ggml.add_eos_token" },
  291. { LLM_KV_TOKENIZER_HF_JSON, "tokenizer.huggingface.json" },
  292. { LLM_KV_TOKENIZER_RWKV, "tokenizer.rwkv.world" },
  293. };
  294. struct LLM_KV {
  295. LLM_KV(llm_arch arch) : arch(arch) {}
  296. llm_arch arch;
  297. std::string operator()(llm_kv kv) const {
  298. return ::format(LLM_KV_NAMES[kv].c_str(), LLM_ARCH_NAMES[arch].c_str());
  299. }
  300. };
  301. enum llm_tensor {
  302. LLM_TENSOR_TOKEN_EMBD,
  303. LLM_TENSOR_TOKEN_EMBD_NORM,
  304. LLM_TENSOR_POS_EMBD,
  305. LLM_TENSOR_OUTPUT,
  306. LLM_TENSOR_OUTPUT_NORM,
  307. LLM_TENSOR_ROPE_FREQS,
  308. LLM_TENSOR_ATTN_Q,
  309. LLM_TENSOR_ATTN_K,
  310. LLM_TENSOR_ATTN_V,
  311. LLM_TENSOR_ATTN_QKV,
  312. LLM_TENSOR_ATTN_OUT,
  313. LLM_TENSOR_ATTN_NORM,
  314. LLM_TENSOR_ATTN_NORM_2,
  315. LLM_TENSOR_ATTN_ROT_EMBD,
  316. LLM_TENSOR_FFN_GATE_INP,
  317. LLM_TENSOR_FFN_NORM,
  318. LLM_TENSOR_FFN_GATE,
  319. LLM_TENSOR_FFN_DOWN,
  320. LLM_TENSOR_FFN_UP,
  321. LLM_TENSOR_FFN_ACT,
  322. LLM_TENSOR_FFN_DOWN_EXP,
  323. LLM_TENSOR_FFN_GATE_EXP,
  324. LLM_TENSOR_FFN_UP_EXP,
  325. LLM_TENSOR_ATTN_Q_NORM,
  326. LLM_TENSOR_ATTN_K_NORM,
  327. };
  328. static std::map<llm_arch, std::map<llm_tensor, std::string>> LLM_TENSOR_NAMES = {
  329. {
  330. LLM_ARCH_LLAMA,
  331. {
  332. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  333. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  334. { LLM_TENSOR_OUTPUT, "output" },
  335. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  336. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  337. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  338. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  339. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  340. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  341. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  342. { LLM_TENSOR_FFN_GATE_INP, "blk.%d.ffn_gate_inp" },
  343. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  344. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  345. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  346. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  347. { LLM_TENSOR_FFN_GATE_EXP, "blk.%d.ffn_gate.%d" },
  348. { LLM_TENSOR_FFN_DOWN_EXP, "blk.%d.ffn_down.%d" },
  349. { LLM_TENSOR_FFN_UP_EXP, "blk.%d.ffn_up.%d" },
  350. },
  351. },
  352. {
  353. LLM_ARCH_BAICHUAN,
  354. {
  355. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  356. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  357. { LLM_TENSOR_OUTPUT, "output" },
  358. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  359. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  360. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  361. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  362. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  363. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  364. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  365. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  366. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  367. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  368. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  369. },
  370. },
  371. {
  372. LLM_ARCH_FALCON,
  373. {
  374. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  375. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  376. { LLM_TENSOR_OUTPUT, "output" },
  377. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  378. { LLM_TENSOR_ATTN_NORM_2, "blk.%d.attn_norm_2" },
  379. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  380. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  381. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  382. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  383. },
  384. },
  385. {
  386. LLM_ARCH_GPT2,
  387. {
  388. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  389. { LLM_TENSOR_POS_EMBD, "position_embd" },
  390. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  391. { LLM_TENSOR_OUTPUT, "output" },
  392. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  393. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  394. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  395. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  396. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  397. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  398. },
  399. },
  400. {
  401. LLM_ARCH_GPTJ,
  402. {
  403. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  404. },
  405. },
  406. {
  407. LLM_ARCH_GPTNEOX,
  408. {
  409. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  410. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  411. { LLM_TENSOR_OUTPUT, "output" },
  412. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  413. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  414. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  415. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  416. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  417. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  418. },
  419. },
  420. {
  421. LLM_ARCH_PERSIMMON,
  422. {
  423. { LLM_TENSOR_TOKEN_EMBD, "token_embd"},
  424. { LLM_TENSOR_OUTPUT_NORM, "output_norm"},
  425. { LLM_TENSOR_OUTPUT, "output"},
  426. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm"},
  427. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv"},
  428. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output"},
  429. { LLM_TENSOR_ATTN_Q_NORM, "blk.%d.attn_q_norm"},
  430. { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm"},
  431. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm"},
  432. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down"},
  433. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up"},
  434. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd"},
  435. },
  436. },
  437. {
  438. LLM_ARCH_MPT,
  439. {
  440. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  441. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  442. { LLM_TENSOR_OUTPUT, "output" },
  443. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  444. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  445. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  446. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  447. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  448. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  449. { LLM_TENSOR_FFN_ACT, "blk.%d.ffn.act" },
  450. },
  451. },
  452. {
  453. LLM_ARCH_STARCODER,
  454. {
  455. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  456. { LLM_TENSOR_POS_EMBD, "position_embd" },
  457. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  458. { LLM_TENSOR_OUTPUT, "output" },
  459. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  460. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  461. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  462. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  463. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  464. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  465. },
  466. },
  467. {
  468. LLM_ARCH_REFACT,
  469. {
  470. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  471. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  472. { LLM_TENSOR_OUTPUT, "output" },
  473. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  474. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  475. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  476. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  477. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  478. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  479. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  480. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  481. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  482. },
  483. },
  484. {
  485. LLM_ARCH_BLOOM,
  486. {
  487. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  488. { LLM_TENSOR_TOKEN_EMBD_NORM, "token_embd_norm" },
  489. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  490. { LLM_TENSOR_OUTPUT, "output" },
  491. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  492. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  493. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  494. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  495. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  496. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  497. },
  498. },
  499. {
  500. LLM_ARCH_STABLELM,
  501. {
  502. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  503. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  504. { LLM_TENSOR_OUTPUT, "output" },
  505. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  506. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  507. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  508. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  509. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  510. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  511. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  512. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  513. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  514. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  515. },
  516. },
  517. {
  518. LLM_ARCH_QWEN,
  519. {
  520. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  521. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  522. { LLM_TENSOR_OUTPUT, "output" },
  523. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  524. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  525. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  526. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  527. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  528. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  529. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  530. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  531. },
  532. },
  533. {
  534. LLM_ARCH_QWEN2,
  535. {
  536. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  537. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  538. { LLM_TENSOR_OUTPUT, "output" },
  539. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  540. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  541. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  542. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  543. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  544. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  545. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  546. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  547. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  548. },
  549. },
  550. {
  551. LLM_ARCH_PHI2,
  552. {
  553. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  554. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  555. { LLM_TENSOR_OUTPUT, "output" },
  556. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  557. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  558. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  559. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  560. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  561. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  562. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  563. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  564. },
  565. },
  566. {
  567. LLM_ARCH_PLAMO,
  568. {
  569. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  570. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  571. { LLM_TENSOR_OUTPUT, "output" },
  572. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  573. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  574. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  575. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  576. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  577. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  578. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  579. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  580. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  581. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  582. },
  583. },
  584. {
  585. LLM_ARCH_CODESHELL,
  586. {
  587. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  588. { LLM_TENSOR_OUTPUT_NORM, "output_norm" },
  589. { LLM_TENSOR_OUTPUT, "output" },
  590. { LLM_TENSOR_ROPE_FREQS, "rope_freqs" },
  591. { LLM_TENSOR_ATTN_NORM, "blk.%d.attn_norm" },
  592. { LLM_TENSOR_ATTN_Q, "blk.%d.attn_q" },
  593. { LLM_TENSOR_ATTN_K, "blk.%d.attn_k" },
  594. { LLM_TENSOR_ATTN_V, "blk.%d.attn_v" },
  595. { LLM_TENSOR_ATTN_QKV, "blk.%d.attn_qkv" },
  596. { LLM_TENSOR_ATTN_OUT, "blk.%d.attn_output" },
  597. { LLM_TENSOR_ATTN_ROT_EMBD, "blk.%d.attn_rot_embd" },
  598. { LLM_TENSOR_FFN_NORM, "blk.%d.ffn_norm" },
  599. { LLM_TENSOR_FFN_GATE, "blk.%d.ffn_gate" },
  600. { LLM_TENSOR_FFN_DOWN, "blk.%d.ffn_down" },
  601. { LLM_TENSOR_FFN_UP, "blk.%d.ffn_up" },
  602. },
  603. },
  604. {
  605. LLM_ARCH_UNKNOWN,
  606. {
  607. { LLM_TENSOR_TOKEN_EMBD, "token_embd" },
  608. },
  609. },
  610. };
  611. static llm_arch llm_arch_from_string(const std::string & name) {
  612. for (const auto & kv : LLM_ARCH_NAMES) { // NOLINT
  613. if (kv.second == name) {
  614. return kv.first;
  615. }
  616. }
  617. return LLM_ARCH_UNKNOWN;
  618. }
  619. // helper to handle gguf constants
  620. // usage:
  621. //
  622. // const auto tn = LLM_TN(LLM_ARCH_LLAMA);
  623. //
  624. // std::string name = tn(LLM_TENSOR_OUTPUT); -> "output"
  625. // std::string name = tn(LLM_TENSOR_TOKEN_EMBD, "bias"); -> "token_embd.bias"
  626. // std::string name = tn(LLM_TENSOR_ATTN_NORM, "weight", 3); -> "blk.3.attn_norm.weight"
  627. //
  628. struct LLM_TN {
  629. LLM_TN(llm_arch arch) : arch(arch) {}
  630. llm_arch arch;
  631. std::string operator()(llm_tensor tensor) const {
  632. return LLM_TENSOR_NAMES[arch].at(tensor);
  633. }
  634. std::string operator()(llm_tensor tensor, const std::string & suffix) const {
  635. return LLM_TENSOR_NAMES[arch].at(tensor) + "." + suffix;
  636. }
  637. std::string operator()(llm_tensor tensor, int bid) const {
  638. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid);
  639. }
  640. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid) const {
  641. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid) + "." + suffix;
  642. }
  643. std::string operator()(llm_tensor tensor, const std::string & suffix, int bid, int xid) const {
  644. return ::format(LLM_TENSOR_NAMES[arch].at(tensor).c_str(), bid, xid) + "." + suffix;
  645. }
  646. };
  647. //
  648. // gguf helpers
  649. //
  650. static std::map<int8_t, std::string> LLAMA_ROPE_SCALING_TYPES = {
  651. { LLAMA_ROPE_SCALING_NONE, "none" },
  652. { LLAMA_ROPE_SCALING_LINEAR, "linear" },
  653. { LLAMA_ROPE_SCALING_YARN, "yarn" },
  654. };
  655. static int8_t llama_rope_scaling_type_from_string(const std::string & name) {
  656. for (const auto & kv : LLAMA_ROPE_SCALING_TYPES) {
  657. if (kv.second == name) {
  658. return kv.first;
  659. }
  660. }
  661. return LLAMA_ROPE_SCALING_UNSPECIFIED;
  662. }
  663. static std::string gguf_data_to_str(enum gguf_type type, const void * data, int i) {
  664. switch (type) {
  665. case GGUF_TYPE_UINT8: return std::to_string(((const uint8_t *)data)[i]);
  666. case GGUF_TYPE_INT8: return std::to_string(((const int8_t *)data)[i]);
  667. case GGUF_TYPE_UINT16: return std::to_string(((const uint16_t *)data)[i]);
  668. case GGUF_TYPE_INT16: return std::to_string(((const int16_t *)data)[i]);
  669. case GGUF_TYPE_UINT32: return std::to_string(((const uint32_t *)data)[i]);
  670. case GGUF_TYPE_INT32: return std::to_string(((const int32_t *)data)[i]);
  671. case GGUF_TYPE_UINT64: return std::to_string(((const uint64_t *)data)[i]);
  672. case GGUF_TYPE_INT64: return std::to_string(((const int64_t *)data)[i]);
  673. case GGUF_TYPE_FLOAT32: return std::to_string(((const float *)data)[i]);
  674. case GGUF_TYPE_FLOAT64: return std::to_string(((const double *)data)[i]);
  675. case GGUF_TYPE_BOOL: return ((const bool *)data)[i] ? "true" : "false";
  676. default: return format("unknown type %d", type);
  677. }
  678. }
  679. static std::string gguf_kv_to_str(const struct gguf_context * ctx_gguf, int i) {
  680. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  681. switch (type) {
  682. case GGUF_TYPE_STRING:
  683. return gguf_get_val_str(ctx_gguf, i);
  684. case GGUF_TYPE_ARRAY:
  685. {
  686. const enum gguf_type arr_type = gguf_get_arr_type(ctx_gguf, i);
  687. int arr_n = gguf_get_arr_n(ctx_gguf, i);
  688. const void * data = gguf_get_arr_data(ctx_gguf, i);
  689. std::stringstream ss;
  690. ss << "[";
  691. for (int j = 0; j < arr_n; j++) {
  692. if (arr_type == GGUF_TYPE_STRING) {
  693. std::string val = gguf_get_arr_str(ctx_gguf, i, j);
  694. // escape quotes
  695. replace_all(val, "\\", "\\\\");
  696. replace_all(val, "\"", "\\\"");
  697. ss << '"' << val << '"';
  698. } else if (arr_type == GGUF_TYPE_ARRAY) {
  699. ss << "???";
  700. } else {
  701. ss << gguf_data_to_str(arr_type, data, j);
  702. }
  703. if (j < arr_n - 1) {
  704. ss << ", ";
  705. }
  706. }
  707. ss << "]";
  708. return ss.str();
  709. }
  710. default:
  711. return gguf_data_to_str(type, gguf_get_val_data(ctx_gguf, i), 0);
  712. }
  713. }
  714. //
  715. // ggml helpers
  716. //
  717. static void ggml_graph_compute_helper(std::vector<uint8_t> & buf, ggml_cgraph * graph, int n_threads) {
  718. struct ggml_cplan plan = ggml_graph_plan(graph, n_threads);
  719. if (plan.work_size > 0) {
  720. buf.resize(plan.work_size);
  721. plan.work_data = buf.data();
  722. }
  723. ggml_graph_compute(graph, &plan);
  724. }
  725. //
  726. // llama helpers
  727. //
  728. #if defined(_WIN32)
  729. static std::string llama_format_win_err(DWORD err) {
  730. LPSTR buf;
  731. size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  732. NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, NULL);
  733. if (!size) {
  734. return "FormatMessageA failed";
  735. }
  736. std::string ret(buf, size);
  737. LocalFree(buf);
  738. return ret;
  739. }
  740. #endif
  741. template <typename T>
  742. struct no_init {
  743. T value;
  744. no_init() { /* do nothing */ }
  745. };
  746. struct llama_file {
  747. // use FILE * so we don't have to re-open the file to mmap
  748. FILE * fp;
  749. size_t size;
  750. llama_file(const char * fname, const char * mode) {
  751. fp = std::fopen(fname, mode);
  752. if (fp == NULL) {
  753. throw std::runtime_error(format("failed to open %s: %s", fname, strerror(errno)));
  754. }
  755. seek(0, SEEK_END);
  756. size = tell();
  757. seek(0, SEEK_SET);
  758. }
  759. size_t tell() const {
  760. #ifdef _WIN32
  761. __int64 ret = _ftelli64(fp);
  762. #else
  763. long ret = std::ftell(fp);
  764. #endif
  765. GGML_ASSERT(ret != -1); // this really shouldn't fail
  766. return (size_t) ret;
  767. }
  768. void seek(size_t offset, int whence) const {
  769. #ifdef _WIN32
  770. int ret = _fseeki64(fp, (__int64) offset, whence);
  771. #else
  772. int ret = std::fseek(fp, (long) offset, whence);
  773. #endif
  774. GGML_ASSERT(ret == 0); // same
  775. }
  776. void read_raw(void * ptr, size_t len) const {
  777. if (len == 0) {
  778. return;
  779. }
  780. errno = 0;
  781. std::size_t ret = std::fread(ptr, len, 1, fp);
  782. if (ferror(fp)) {
  783. throw std::runtime_error(format("read error: %s", strerror(errno)));
  784. }
  785. if (ret != 1) {
  786. throw std::runtime_error("unexpectedly reached end of file");
  787. }
  788. }
  789. uint32_t read_u32() const {
  790. uint32_t ret;
  791. read_raw(&ret, sizeof(ret));
  792. return ret;
  793. }
  794. void write_raw(const void * ptr, size_t len) const {
  795. if (len == 0) {
  796. return;
  797. }
  798. errno = 0;
  799. size_t ret = std::fwrite(ptr, len, 1, fp);
  800. if (ret != 1) {
  801. throw std::runtime_error(format("write error: %s", strerror(errno)));
  802. }
  803. }
  804. void write_u32(std::uint32_t val) const {
  805. write_raw(&val, sizeof(val));
  806. }
  807. ~llama_file() {
  808. if (fp) {
  809. std::fclose(fp);
  810. }
  811. }
  812. };
  813. struct llama_mmap {
  814. void * addr;
  815. size_t size;
  816. llama_mmap(const llama_mmap &) = delete;
  817. #ifdef _POSIX_MAPPED_FILES
  818. static constexpr bool SUPPORTED = true;
  819. // list of mapped fragments (first_offset, last_offset)
  820. std::vector<std::pair<size_t, size_t>> mapped_fragments;
  821. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1 /* -1 = max value */, bool numa = false) {
  822. size = file->size;
  823. int fd = fileno(file->fp);
  824. int flags = MAP_SHARED;
  825. // prefetch/readahead impairs performance on NUMA systems
  826. if (numa) { prefetch = 0; }
  827. #ifdef __linux__
  828. // advise the kernel to read the file sequentially (increases readahead)
  829. if (posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL)) {
  830. LLAMA_LOG_WARN("warning: posix_fadvise(.., POSIX_FADV_SEQUENTIAL) failed: %s\n",
  831. strerror(errno));
  832. }
  833. if (prefetch) { flags |= MAP_POPULATE; }
  834. #endif
  835. addr = mmap(NULL, file->size, PROT_READ, flags, fd, 0);
  836. if (addr == MAP_FAILED) { // NOLINT
  837. throw std::runtime_error(format("mmap failed: %s", strerror(errno)));
  838. }
  839. if (prefetch > 0) {
  840. // advise the kernel to preload the mapped memory
  841. if (posix_madvise(addr, std::min(file->size, prefetch), POSIX_MADV_WILLNEED)) {
  842. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_WILLNEED) failed: %s\n",
  843. strerror(errno));
  844. }
  845. }
  846. if (numa) {
  847. // advise the kernel not to use readahead
  848. // (because the next page might not belong on the same node)
  849. if (posix_madvise(addr, file->size, POSIX_MADV_RANDOM)) {
  850. LLAMA_LOG_WARN("warning: posix_madvise(.., POSIX_MADV_RANDOM) failed: %s\n",
  851. strerror(errno));
  852. }
  853. }
  854. // initialize list of mapped_fragments
  855. mapped_fragments.emplace_back(0, file->size);
  856. }
  857. static void align_range(size_t * first, size_t * last, size_t page_size) {
  858. // align first to the next page
  859. size_t offset_in_page = *first & (page_size - 1);
  860. size_t offset_to_page = offset_in_page == 0 ? 0 : page_size - offset_in_page;
  861. *first += offset_to_page;
  862. // align last to the previous page
  863. *last = *last & ~(page_size - 1);
  864. if (*last <= *first) {
  865. *last = *first;
  866. }
  867. }
  868. // partially unmap the file in the range [first, last)
  869. void unmap_fragment(size_t first, size_t last) {
  870. // note: this function must not be called multiple times with overlapping ranges
  871. // otherwise, there is a risk of invalidating addresses that have been repurposed for other mappings
  872. int page_size = sysconf(_SC_PAGESIZE);
  873. align_range(&first, &last, page_size);
  874. size_t len = last - first;
  875. if (len == 0) {
  876. return;
  877. }
  878. GGML_ASSERT(first % page_size == 0);
  879. GGML_ASSERT(last % page_size == 0);
  880. GGML_ASSERT(last > first);
  881. void * next_page_start = (uint8_t *) addr + first;
  882. // unmap the range
  883. if (munmap(next_page_start, len)) {
  884. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  885. }
  886. // update the list of mapped fragments to avoid unmapping the same range again in the destructor
  887. std::vector<std::pair<size_t, size_t>> new_mapped_fragments;
  888. for (const auto & frag : mapped_fragments) {
  889. if (frag.first < first && frag.second > last) {
  890. // the range is in the middle of the fragment, split it
  891. new_mapped_fragments.emplace_back(frag.first, first);
  892. new_mapped_fragments.emplace_back(last, frag.second);
  893. } else if (frag.first < first && frag.second > first) {
  894. // the range starts in the middle of the fragment
  895. new_mapped_fragments.emplace_back(frag.first, first);
  896. } else if (frag.first < last && frag.second > last) {
  897. // the range ends in the middle of the fragment
  898. new_mapped_fragments.emplace_back(last, frag.second);
  899. } else if (frag.first >= first && frag.second <= last) {
  900. // the range covers the entire fragment
  901. } else {
  902. // the range is outside the fragment
  903. new_mapped_fragments.push_back(frag);
  904. }
  905. }
  906. mapped_fragments = std::move(new_mapped_fragments);
  907. }
  908. ~llama_mmap() {
  909. for (const auto & frag : mapped_fragments) {
  910. if (munmap((char *) addr + frag.first, frag.second - frag.first)) {
  911. LLAMA_LOG_WARN("warning: munmap failed: %s\n", strerror(errno));
  912. }
  913. }
  914. }
  915. #elif defined(_WIN32)
  916. static constexpr bool SUPPORTED = true;
  917. llama_mmap(struct llama_file * file, size_t prefetch = (size_t) -1, bool numa = false) {
  918. GGML_UNUSED(numa);
  919. size = file->size;
  920. HANDLE hFile = (HANDLE) _get_osfhandle(_fileno(file->fp));
  921. HANDLE hMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
  922. if (hMapping == NULL) {
  923. DWORD error = GetLastError();
  924. throw std::runtime_error(format("CreateFileMappingA failed: %s", llama_format_win_err(error).c_str()));
  925. }
  926. addr = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
  927. DWORD error = GetLastError();
  928. CloseHandle(hMapping);
  929. if (addr == NULL) {
  930. throw std::runtime_error(format("MapViewOfFile failed: %s", llama_format_win_err(error).c_str()));
  931. }
  932. if (prefetch > 0) {
  933. #if _WIN32_WINNT >= 0x602
  934. // PrefetchVirtualMemory is only present on Windows 8 and above, so we dynamically load it
  935. BOOL (WINAPI *pPrefetchVirtualMemory) (HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG);
  936. HMODULE hKernel32 = GetModuleHandleW(L"kernel32.dll");
  937. // may fail on pre-Windows 8 systems
  938. pPrefetchVirtualMemory = reinterpret_cast<decltype(pPrefetchVirtualMemory)> (GetProcAddress(hKernel32, "PrefetchVirtualMemory"));
  939. if (pPrefetchVirtualMemory) {
  940. // advise the kernel to preload the mapped memory
  941. WIN32_MEMORY_RANGE_ENTRY range;
  942. range.VirtualAddress = addr;
  943. range.NumberOfBytes = (SIZE_T) std::min(size, prefetch);
  944. if (!pPrefetchVirtualMemory(GetCurrentProcess(), 1, &range, 0)) {
  945. LLAMA_LOG_WARN("warning: PrefetchVirtualMemory failed: %s\n",
  946. llama_format_win_err(GetLastError()).c_str());
  947. }
  948. }
  949. #else
  950. throw std::runtime_error("PrefetchVirtualMemory unavailable");
  951. #endif
  952. }
  953. }
  954. void unmap_fragment(size_t first, size_t last) {
  955. // not supported
  956. GGML_UNUSED(first);
  957. GGML_UNUSED(last);
  958. }
  959. ~llama_mmap() {
  960. if (!UnmapViewOfFile(addr)) {
  961. LLAMA_LOG_WARN("warning: UnmapViewOfFile failed: %s\n",
  962. llama_format_win_err(GetLastError()).c_str());
  963. }
  964. }
  965. #else
  966. static constexpr bool SUPPORTED = false;
  967. llama_mmap(struct llama_file * file, size_t prefetch = -1, bool numa = false) {
  968. GGML_UNUSED(file);
  969. GGML_UNUSED(prefetch);
  970. GGML_UNUSED(numa);
  971. throw std::runtime_error("mmap not supported");
  972. }
  973. void unmap_fragment(size_t first, size_t last) {
  974. GGML_UNUSED(first);
  975. GGML_UNUSED(last);
  976. throw std::runtime_error("mmap not supported");
  977. }
  978. #endif
  979. };
  980. // Represents some region of memory being locked using mlock or VirtualLock;
  981. // will automatically unlock on destruction.
  982. struct llama_mlock {
  983. void * addr = NULL;
  984. size_t size = 0;
  985. bool failed_already = false;
  986. llama_mlock() {}
  987. llama_mlock(const llama_mlock &) = delete;
  988. ~llama_mlock() {
  989. if (size) {
  990. raw_unlock(addr, size);
  991. }
  992. }
  993. void init(void * ptr) {
  994. GGML_ASSERT(addr == NULL && size == 0); // NOLINT
  995. addr = ptr;
  996. }
  997. void grow_to(size_t target_size) {
  998. GGML_ASSERT(addr);
  999. if (failed_already) {
  1000. return;
  1001. }
  1002. size_t granularity = lock_granularity();
  1003. target_size = (target_size + granularity - 1) & ~(granularity - 1);
  1004. if (target_size > size) {
  1005. if (raw_lock((uint8_t *) addr + size, target_size - size)) {
  1006. size = target_size;
  1007. } else {
  1008. failed_already = true;
  1009. }
  1010. }
  1011. }
  1012. #ifdef _POSIX_MEMLOCK_RANGE
  1013. static constexpr bool SUPPORTED = true;
  1014. static size_t lock_granularity() {
  1015. return (size_t) sysconf(_SC_PAGESIZE);
  1016. }
  1017. #ifdef __APPLE__
  1018. #define MLOCK_SUGGESTION \
  1019. "Try increasing the sysctl values 'vm.user_wire_limit' and 'vm.global_user_wire_limit' and/or " \
  1020. "decreasing 'vm.global_no_user_wire_amount'. Also try increasing RLIMIT_MLOCK (ulimit -l).\n"
  1021. #else
  1022. #define MLOCK_SUGGESTION \
  1023. "Try increasing RLIMIT_MLOCK ('ulimit -l' as root).\n"
  1024. #endif
  1025. bool raw_lock(const void * addr, size_t size) const {
  1026. if (!mlock(addr, size)) {
  1027. return true;
  1028. }
  1029. char* errmsg = std::strerror(errno);
  1030. bool suggest = (errno == ENOMEM);
  1031. // Check if the resource limit is fine after all
  1032. struct rlimit lock_limit;
  1033. if (suggest && getrlimit(RLIMIT_MEMLOCK, &lock_limit)) {
  1034. suggest = false;
  1035. }
  1036. if (suggest && (lock_limit.rlim_max > lock_limit.rlim_cur + size)) {
  1037. suggest = false;
  1038. }
  1039. LLAMA_LOG_WARN("warning: failed to mlock %zu-byte buffer (after previously locking %zu bytes): %s\n%s",
  1040. size, this->size, errmsg, suggest ? MLOCK_SUGGESTION : "");
  1041. return false;
  1042. }
  1043. #undef MLOCK_SUGGESTION
  1044. static void raw_unlock(void * addr, size_t size) {
  1045. if (munlock(addr, size)) {
  1046. LLAMA_LOG_WARN("warning: failed to munlock buffer: %s\n", std::strerror(errno));
  1047. }
  1048. }
  1049. #elif defined(_WIN32)
  1050. static constexpr bool SUPPORTED = true;
  1051. static size_t lock_granularity() {
  1052. SYSTEM_INFO si;
  1053. GetSystemInfo(&si);
  1054. return (size_t) si.dwPageSize;
  1055. }
  1056. bool raw_lock(void * ptr, size_t len) const {
  1057. for (int tries = 1; ; tries++) {
  1058. if (VirtualLock(ptr, len)) {
  1059. return true;
  1060. }
  1061. if (tries == 2) {
  1062. LLAMA_LOG_WARN("warning: failed to VirtualLock %zu-byte buffer (after previously locking %zu bytes): %s\n",
  1063. len, size, llama_format_win_err(GetLastError()).c_str());
  1064. return false;
  1065. }
  1066. // It failed but this was only the first try; increase the working
  1067. // set size and try again.
  1068. SIZE_T min_ws_size, max_ws_size;
  1069. if (!GetProcessWorkingSetSize(GetCurrentProcess(), &min_ws_size, &max_ws_size)) {
  1070. LLAMA_LOG_WARN("warning: GetProcessWorkingSetSize failed: %s\n",
  1071. llama_format_win_err(GetLastError()).c_str());
  1072. return false;
  1073. }
  1074. // Per MSDN: "The maximum number of pages that a process can lock
  1075. // is equal to the number of pages in its minimum working set minus
  1076. // a small overhead."
  1077. // Hopefully a megabyte is enough overhead:
  1078. size_t increment = len + 1048576;
  1079. // The minimum must be <= the maximum, so we need to increase both:
  1080. min_ws_size += increment;
  1081. max_ws_size += increment;
  1082. if (!SetProcessWorkingSetSize(GetCurrentProcess(), min_ws_size, max_ws_size)) {
  1083. LLAMA_LOG_WARN("warning: SetProcessWorkingSetSize failed: %s\n",
  1084. llama_format_win_err(GetLastError()).c_str());
  1085. return false;
  1086. }
  1087. }
  1088. }
  1089. static void raw_unlock(void * ptr, size_t len) {
  1090. if (!VirtualUnlock(ptr, len)) {
  1091. LLAMA_LOG_WARN("warning: failed to VirtualUnlock buffer: %s\n",
  1092. llama_format_win_err(GetLastError()).c_str());
  1093. }
  1094. }
  1095. #else
  1096. static constexpr bool SUPPORTED = false;
  1097. static size_t lock_granularity() {
  1098. return (size_t) 65536;
  1099. }
  1100. bool raw_lock(const void * addr, size_t len) const {
  1101. LLAMA_LOG_WARN("warning: mlock not supported on this system\n");
  1102. return false;
  1103. }
  1104. static void raw_unlock(const void * addr, size_t len) {}
  1105. #endif
  1106. };
  1107. static std::string llama_token_to_piece(const struct llama_context * ctx, llama_token token) {
  1108. std::vector<char> result(8, 0);
  1109. const int n_tokens = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1110. if (n_tokens < 0) {
  1111. result.resize(-n_tokens);
  1112. int check = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1113. GGML_ASSERT(check == -n_tokens);
  1114. }
  1115. else {
  1116. result.resize(n_tokens);
  1117. }
  1118. return std::string(result.data(), result.size());
  1119. }
  1120. static ggml_backend_buffer_type_t llama_default_buffer_type_cpu(bool host_buffer) {
  1121. ggml_backend_buffer_type_t buft = nullptr;
  1122. #if defined(GGML_USE_CUBLAS)
  1123. // host buffers should only be used when data is expected to be copied to/from the GPU
  1124. if (host_buffer) {
  1125. buft = ggml_backend_cuda_host_buffer_type();
  1126. }
  1127. #elif defined(GGML_USE_CPU_HBM)
  1128. buft = ggml_backend_cpu_hbm_buffer_type();
  1129. #endif
  1130. if (buft == nullptr) {
  1131. buft = ggml_backend_cpu_buffer_type();
  1132. }
  1133. return buft;
  1134. GGML_UNUSED(host_buffer);
  1135. }
  1136. static ggml_backend_buffer_type_t llama_default_buffer_type_offload(int gpu) {
  1137. ggml_backend_buffer_type_t buft = nullptr;
  1138. #ifdef GGML_USE_METAL
  1139. buft = ggml_backend_metal_buffer_type();
  1140. #elif defined(GGML_USE_CUBLAS)
  1141. buft = ggml_backend_cuda_buffer_type(gpu);
  1142. #elif defined(GGML_USE_CLBLAST)
  1143. buft = ggml_backend_opencl_buffer_type();
  1144. #endif
  1145. if (buft == nullptr) {
  1146. buft = llama_default_buffer_type_cpu(true);
  1147. }
  1148. return buft;
  1149. GGML_UNUSED(gpu);
  1150. }
  1151. static ggml_backend_buffer_type_t llama_default_buffer_type_split(int fallback_gpu, const float * tensor_split) {
  1152. ggml_backend_buffer_type_t buft = nullptr;
  1153. #ifdef GGML_USE_CUBLAS
  1154. if (ggml_backend_cuda_get_device_count() > 1) {
  1155. buft = ggml_backend_cuda_split_buffer_type(tensor_split);
  1156. }
  1157. #endif
  1158. if (buft == nullptr) {
  1159. buft = llama_default_buffer_type_offload(fallback_gpu);
  1160. }
  1161. return buft;
  1162. GGML_UNUSED(tensor_split);
  1163. }
  1164. //
  1165. // globals
  1166. //
  1167. struct llama_state {
  1168. llama_state() {
  1169. #ifdef GGML_USE_METAL
  1170. ggml_backend_metal_log_set_callback(log_callback, log_callback_user_data);
  1171. #endif
  1172. }
  1173. // We save the log callback globally
  1174. ggml_log_callback log_callback = llama_log_callback_default;
  1175. void * log_callback_user_data = nullptr;
  1176. };
  1177. static llama_state g_state;
  1178. // available llama models
  1179. enum e_model {
  1180. MODEL_UNKNOWN,
  1181. MODEL_0_5B,
  1182. MODEL_1B,
  1183. MODEL_3B,
  1184. MODEL_4B,
  1185. MODEL_7B,
  1186. MODEL_8B,
  1187. MODEL_13B,
  1188. MODEL_15B,
  1189. MODEL_30B,
  1190. MODEL_34B,
  1191. MODEL_40B,
  1192. MODEL_65B,
  1193. MODEL_70B,
  1194. MODEL_SMALL,
  1195. MODEL_MEDIUM,
  1196. MODEL_LARGE,
  1197. MODEL_XL,
  1198. };
  1199. static const size_t kiB = 1024;
  1200. static const size_t MiB = 1024*kiB;
  1201. static const size_t GiB = 1024*MiB;
  1202. struct llama_hparams {
  1203. bool vocab_only;
  1204. uint32_t n_vocab;
  1205. uint32_t n_ctx_train; // context size the model was trained on
  1206. uint32_t n_embd;
  1207. uint32_t n_head;
  1208. uint32_t n_head_kv;
  1209. uint32_t n_layer;
  1210. uint32_t n_rot;
  1211. 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
  1212. uint32_t n_embd_head_v; // dimension of values (d_v) aka n_embd_head
  1213. uint32_t n_ff;
  1214. uint32_t n_expert = 0;
  1215. uint32_t n_expert_used = 0;
  1216. float f_norm_eps;
  1217. float f_norm_rms_eps;
  1218. float rope_freq_base_train;
  1219. float rope_freq_scale_train;
  1220. uint32_t n_yarn_orig_ctx;
  1221. int8_t rope_scaling_type_train : 3;
  1222. bool rope_finetuned : 1;
  1223. float f_clamp_kqv;
  1224. float f_max_alibi_bias;
  1225. bool operator!=(const llama_hparams & other) const {
  1226. if (this->vocab_only != other.vocab_only) return true;
  1227. if (this->n_vocab != other.n_vocab) return true;
  1228. if (this->n_ctx_train != other.n_ctx_train) return true;
  1229. if (this->n_embd != other.n_embd) return true;
  1230. if (this->n_head != other.n_head) return true;
  1231. if (this->n_head_kv != other.n_head_kv) return true;
  1232. if (this->n_layer != other.n_layer) return true;
  1233. if (this->n_rot != other.n_rot) return true;
  1234. if (this->n_embd_head_k != other.n_embd_head_k) return true;
  1235. if (this->n_embd_head_v != other.n_embd_head_v) return true;
  1236. if (this->n_ff != other.n_ff) return true;
  1237. if (this->n_expert != other.n_expert) return true;
  1238. if (this->n_expert_used != other.n_expert_used) return true;
  1239. if (this->rope_finetuned != other.rope_finetuned) return true;
  1240. if (this->n_yarn_orig_ctx != other.n_yarn_orig_ctx) return true;
  1241. const float EPSILON = 1e-9f;
  1242. if (!is_float_close(this->f_norm_eps, other.f_norm_eps, EPSILON)) return true;
  1243. if (!is_float_close(this->f_norm_rms_eps, other.f_norm_rms_eps, EPSILON)) return true;
  1244. if (!is_float_close(this->rope_freq_base_train, other.rope_freq_base_train, EPSILON)) return true;
  1245. if (!is_float_close(this->rope_freq_scale_train, other.rope_freq_scale_train, EPSILON)) return true;
  1246. return false;
  1247. }
  1248. uint32_t n_gqa() const {
  1249. return n_head/n_head_kv;
  1250. }
  1251. uint32_t n_embd_k_gqa() const { // dimension of key embeddings across all k-v heads
  1252. return n_embd_head_k * n_head_kv;
  1253. }
  1254. uint32_t n_embd_v_gqa() const { // dimension of value embeddings across all k-v heads
  1255. return n_embd_head_v * n_head_kv;
  1256. }
  1257. };
  1258. struct llama_cparams {
  1259. uint32_t n_ctx; // context size used during inference
  1260. uint32_t n_batch;
  1261. uint32_t n_threads; // number of threads to use for generation
  1262. uint32_t n_threads_batch; // number of threads to use for batch processing
  1263. float rope_freq_base;
  1264. float rope_freq_scale;
  1265. uint32_t n_yarn_orig_ctx;
  1266. // These hyperparameters are not exposed in GGUF, because all
  1267. // existing YaRN models use the same values for them.
  1268. float yarn_ext_factor;
  1269. float yarn_attn_factor;
  1270. float yarn_beta_fast;
  1271. float yarn_beta_slow;
  1272. bool mul_mat_q;
  1273. bool offload_kqv;
  1274. ggml_backend_sched_eval_callback cb_eval;
  1275. void * cb_eval_user_data;
  1276. };
  1277. struct llama_layer {
  1278. // normalization
  1279. struct ggml_tensor * attn_norm;
  1280. struct ggml_tensor * attn_norm_b;
  1281. struct ggml_tensor * attn_norm_2;
  1282. struct ggml_tensor * attn_norm_2_b;
  1283. struct ggml_tensor * attn_q_norm;
  1284. struct ggml_tensor * attn_q_norm_b;
  1285. struct ggml_tensor * attn_k_norm;
  1286. struct ggml_tensor * attn_k_norm_b;
  1287. // attention
  1288. struct ggml_tensor * wq;
  1289. struct ggml_tensor * wk;
  1290. struct ggml_tensor * wv;
  1291. struct ggml_tensor * wo;
  1292. struct ggml_tensor * wqkv;
  1293. // attention bias
  1294. struct ggml_tensor * bq;
  1295. struct ggml_tensor * bk;
  1296. struct ggml_tensor * bv;
  1297. struct ggml_tensor * bo;
  1298. struct ggml_tensor * bqkv;
  1299. // normalization
  1300. struct ggml_tensor * ffn_norm;
  1301. struct ggml_tensor * ffn_norm_b;
  1302. // ff
  1303. struct ggml_tensor * ffn_gate; // w1
  1304. struct ggml_tensor * ffn_down; // w2
  1305. struct ggml_tensor * ffn_up; // w3
  1306. // ff MoE
  1307. struct ggml_tensor * ffn_gate_inp;
  1308. struct ggml_tensor * ffn_gate_exp[LLAMA_MAX_EXPERTS];
  1309. struct ggml_tensor * ffn_down_exp[LLAMA_MAX_EXPERTS];
  1310. struct ggml_tensor * ffn_up_exp [LLAMA_MAX_EXPERTS];
  1311. // ff bias
  1312. struct ggml_tensor * ffn_down_b; // b2
  1313. struct ggml_tensor * ffn_up_b; // b3
  1314. struct ggml_tensor * ffn_act;
  1315. };
  1316. struct llama_kv_cell {
  1317. llama_pos pos = -1;
  1318. llama_pos delta = 0;
  1319. std::set<llama_seq_id> seq_id;
  1320. bool has_seq_id(const llama_seq_id & id) const {
  1321. return seq_id.find(id) != seq_id.end();
  1322. }
  1323. };
  1324. // ring-buffer of cached KV data
  1325. struct llama_kv_cache {
  1326. bool has_shift = false;
  1327. // Note: The value of head isn't only used to optimize searching
  1328. // for a free KV slot. llama_decode_internal also uses it, so it
  1329. // cannot be freely changed after a slot has been allocated.
  1330. uint32_t head = 0;
  1331. uint32_t size = 0;
  1332. uint32_t used = 0; // used cells (i.e. at least one seq_id)
  1333. // computed before each graph build
  1334. uint32_t n = 0;
  1335. std::vector<llama_kv_cell> cells;
  1336. std::vector<struct ggml_tensor *> k_l; // per layer
  1337. std::vector<struct ggml_tensor *> v_l;
  1338. std::vector<struct ggml_context *> ctxs;
  1339. std::vector<ggml_backend_buffer_t> bufs;
  1340. size_t total_size() const {
  1341. size_t size = 0;
  1342. for (ggml_backend_buffer_t buf : bufs) {
  1343. size += ggml_backend_buffer_get_size(buf);
  1344. }
  1345. return size;
  1346. }
  1347. ~llama_kv_cache() {
  1348. for (struct ggml_context * ctx : ctxs) {
  1349. ggml_free(ctx);
  1350. }
  1351. for (ggml_backend_buffer_t buf : bufs) {
  1352. ggml_backend_buffer_free(buf);
  1353. }
  1354. }
  1355. };
  1356. struct llama_vocab {
  1357. using id = int32_t;
  1358. using token = std::string;
  1359. using ttype = llama_token_type;
  1360. struct token_data {
  1361. token text;
  1362. float score;
  1363. ttype type;
  1364. };
  1365. enum llama_vocab_type type = LLAMA_VOCAB_TYPE_SPM;
  1366. std::unordered_map<token, id> token_to_id;
  1367. std::vector<token_data> id_to_token;
  1368. std::unordered_map<token, id> special_tokens_cache;
  1369. std::map<std::pair<std::string, std::string>, int> bpe_ranks;
  1370. // default LLaMA special tokens
  1371. id special_bos_id = 1;
  1372. id special_eos_id = 2;
  1373. id special_unk_id = 0;
  1374. id special_sep_id = -1;
  1375. id special_pad_id = -1;
  1376. int special_add_bos = -1; // -1 unknown, 1 add, 0 don't add.
  1377. int special_add_eos = -1; // -1 unknown, 1 add, 0 don't add.
  1378. id linefeed_id = 13;
  1379. id special_prefix_id = 32007;
  1380. id special_middle_id = 32009;
  1381. id special_suffix_id = 32008;
  1382. id special_eot_id = 32010;
  1383. int find_bpe_rank(const std::string & token_left, const std::string & token_right) const {
  1384. GGML_ASSERT(token_left.find(' ') == std::string::npos);
  1385. GGML_ASSERT(token_left.find('\n') == std::string::npos);
  1386. GGML_ASSERT(token_right.find(' ') == std::string::npos);
  1387. GGML_ASSERT(token_right.find('\n') == std::string::npos);
  1388. auto it = bpe_ranks.find(std::make_pair(token_left, token_right));
  1389. if (it == bpe_ranks.end()) {
  1390. return -1;
  1391. }
  1392. return it->second;
  1393. }
  1394. };
  1395. struct llama_model {
  1396. e_model type = MODEL_UNKNOWN;
  1397. llm_arch arch = LLM_ARCH_UNKNOWN;
  1398. llama_ftype ftype = LLAMA_FTYPE_ALL_F32;
  1399. std::string name = "n/a";
  1400. llama_hparams hparams = {};
  1401. llama_vocab vocab;
  1402. struct ggml_tensor * tok_embd;
  1403. struct ggml_tensor * pos_embd;
  1404. struct ggml_tensor * tok_norm;
  1405. struct ggml_tensor * tok_norm_b;
  1406. struct ggml_tensor * output_norm;
  1407. struct ggml_tensor * output_norm_b;
  1408. struct ggml_tensor * output;
  1409. struct ggml_tensor * output_b;
  1410. std::vector<llama_layer> layers;
  1411. llama_split_mode split_mode;
  1412. int main_gpu;
  1413. int n_gpu_layers;
  1414. // gguf metadata
  1415. std::unordered_map<std::string, std::string> gguf_kv;
  1416. // layer -> buffer type mapping
  1417. struct layer_buft {
  1418. layer_buft() : buft_matrix(nullptr), buft(nullptr) {}
  1419. layer_buft(ggml_backend_buffer_type_t matrix) : buft_matrix(matrix), buft(matrix) {}
  1420. layer_buft(ggml_backend_buffer_type_t matrix, ggml_backend_buffer_type_t other) : buft_matrix(matrix), buft(other) {}
  1421. ggml_backend_buffer_type_t buft_matrix; // matrices only - used by split buffers and backends that support only matrix multiplication
  1422. ggml_backend_buffer_type_t buft; // everything else
  1423. };
  1424. layer_buft buft_input;
  1425. layer_buft buft_output;
  1426. std::vector<layer_buft> buft_layer;
  1427. // contexts where the model tensors metadata is stored
  1428. std::vector<struct ggml_context *> ctxs;
  1429. // the model memory buffers for the tensor data
  1430. std::vector<ggml_backend_buffer_t> bufs;
  1431. // model memory mapped file
  1432. std::unique_ptr<llama_mmap> mapping;
  1433. // objects representing data potentially being locked in memory
  1434. std::vector<std::unique_ptr<llama_mlock>> mlock_bufs;
  1435. llama_mlock mlock_mmap;
  1436. // for quantize-stats only
  1437. std::vector<std::pair<std::string, struct ggml_tensor *>> tensors_by_name;
  1438. int64_t t_load_us = 0;
  1439. int64_t t_start_us = 0;
  1440. ~llama_model() {
  1441. for (struct ggml_context * ctx : ctxs) {
  1442. ggml_free(ctx);
  1443. }
  1444. for (ggml_backend_buffer_t buf : bufs) {
  1445. ggml_backend_buffer_free(buf);
  1446. }
  1447. }
  1448. };
  1449. struct llama_context {
  1450. llama_context(const llama_model & model) : model(model), t_start_us(model.t_start_us), t_load_us(model.t_load_us) {}
  1451. ~llama_context() {
  1452. ggml_backend_sched_free(sched);
  1453. for (ggml_backend_t backend : backends) {
  1454. ggml_backend_free(backend);
  1455. }
  1456. ggml_backend_buffer_free(buf_input);
  1457. ggml_free(ctx_input);
  1458. }
  1459. llama_cparams cparams;
  1460. std::vector<ggml_backend_t> backends;
  1461. #ifdef GGML_USE_METAL
  1462. ggml_backend_t backend_metal = nullptr;
  1463. #endif
  1464. ggml_backend_t backend_cpu = nullptr;
  1465. const llama_model & model;
  1466. // key + value cache for the self attention
  1467. struct llama_kv_cache kv_self;
  1468. std::mt19937 rng;
  1469. bool has_evaluated_once = false;
  1470. int64_t t_start_us;
  1471. int64_t t_load_us;
  1472. int64_t t_sample_us = 0;
  1473. int64_t t_p_eval_us = 0;
  1474. int64_t t_eval_us = 0;
  1475. int32_t n_sample = 0; // number of tokens sampled
  1476. int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1)
  1477. int32_t n_eval = 0; // number of eval calls
  1478. // decode output (2-dimensional array: [n_tokens][n_vocab])
  1479. std::vector<float> logits;
  1480. #ifndef NDEBUG
  1481. // guard against access to unset logits
  1482. std::vector<bool> logits_valid;
  1483. #endif
  1484. bool logits_all = false;
  1485. // input embedding (1-dimensional array: [n_embd])
  1486. std::vector<float> embedding;
  1487. // memory buffers used to evaluate the model
  1488. std::vector<uint8_t> buf_compute_meta;
  1489. ggml_backend_sched_t sched = nullptr;
  1490. // allocator for the input tensors
  1491. ggml_tallocr * alloc = nullptr;
  1492. // input tensors
  1493. ggml_backend_buffer_t buf_input = nullptr;
  1494. ggml_context * ctx_input = nullptr;
  1495. struct ggml_tensor * inp_tokens; // I32 [n_batch]
  1496. struct ggml_tensor * inp_embd; // F32 [n_embd, n_batch]
  1497. struct ggml_tensor * inp_pos; // I32 [n_batch]
  1498. struct ggml_tensor * inp_KQ_mask; // F32 [n_ctx, n_batch]
  1499. struct ggml_tensor * inp_K_shift; // I32 [n_ctx]
  1500. #ifdef GGML_USE_MPI
  1501. ggml_mpi_context * ctx_mpi = NULL;
  1502. #endif
  1503. };
  1504. //
  1505. // kv cache helpers
  1506. //
  1507. static bool llama_kv_cache_init(
  1508. struct llama_kv_cache & cache,
  1509. const llama_model & model,
  1510. ggml_type ktype,
  1511. ggml_type vtype,
  1512. uint32_t n_ctx,
  1513. bool offload) {
  1514. const struct llama_hparams & hparams = model.hparams;
  1515. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  1516. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  1517. const int64_t n_layer = hparams.n_layer;
  1518. cache.has_shift = false;
  1519. cache.head = 0;
  1520. cache.size = n_ctx;
  1521. cache.used = 0;
  1522. cache.cells.clear();
  1523. cache.cells.resize(n_ctx);
  1524. #ifdef GGML_USE_CLBLAST
  1525. offload = false;
  1526. #endif
  1527. // count used buffer types
  1528. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  1529. if (offload) {
  1530. for (int64_t i = 0; i < n_layer; ++i) {
  1531. buft_layer_count[model.buft_layer[i].buft]++;
  1532. }
  1533. } else {
  1534. buft_layer_count[llama_default_buffer_type_cpu(true)] = n_layer;
  1535. }
  1536. // create a context for each buffer type
  1537. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  1538. for (auto & it : buft_layer_count) {
  1539. int n_layers = it.second;
  1540. struct ggml_init_params params = {
  1541. /*.mem_size =*/ 2u*n_layers*ggml_tensor_overhead(),
  1542. /*.mem_buffer =*/ NULL,
  1543. /*.no_alloc =*/ true,
  1544. };
  1545. ggml_context * ctx = ggml_init(params);
  1546. if (!ctx) {
  1547. LLAMA_LOG_ERROR("%s: failed to allocate context for kv cache\n", __func__);
  1548. return false;
  1549. }
  1550. ctx_map[it.first] = ctx;
  1551. cache.ctxs.push_back(ctx);
  1552. }
  1553. cache.k_l.reserve(n_layer);
  1554. cache.v_l.reserve(n_layer);
  1555. for (int i = 0; i < (int) n_layer; i++) {
  1556. struct ggml_context * ctx = offload ? ctx_map.at(model.buft_layer[i].buft) : cache.ctxs.front();
  1557. ggml_tensor * k = ggml_new_tensor_1d(ctx, ktype, n_embd_k_gqa*n_ctx);
  1558. ggml_tensor * v = ggml_new_tensor_1d(ctx, vtype, n_embd_v_gqa*n_ctx);
  1559. ggml_format_name(k, "cache_k_l%d", i);
  1560. ggml_format_name(v, "cache_v_l%d", i);
  1561. cache.k_l.push_back(k);
  1562. cache.v_l.push_back(v);
  1563. }
  1564. // allocate tensors and initialize the buffers to avoid NaNs in the padding
  1565. for (auto it : ctx_map) {
  1566. ggml_backend_buffer_type_t buft = it.first;
  1567. ggml_context * ctx = it.second;
  1568. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  1569. if (!buf) {
  1570. LLAMA_LOG_ERROR("%s: failed to allocate buffer for kv cache\n", __func__);
  1571. return false;
  1572. }
  1573. ggml_backend_buffer_clear(buf, 0);
  1574. 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);
  1575. cache.bufs.push_back(buf);
  1576. }
  1577. return true;
  1578. }
  1579. // find an empty slot of size "n_tokens" in the cache
  1580. // updates the cache head
  1581. // Note: On success, it's important that cache.head points
  1582. // to the first cell of the slot.
  1583. static bool llama_kv_cache_find_slot(
  1584. struct llama_kv_cache & cache,
  1585. const struct llama_batch & batch) {
  1586. const uint32_t n_ctx = cache.size;
  1587. const uint32_t n_tokens = batch.n_tokens;
  1588. if (n_tokens > n_ctx) {
  1589. LLAMA_LOG_ERROR("%s: n_tokens=%d > n_ctx=%d\n", __func__, n_tokens, n_ctx);
  1590. return false;
  1591. }
  1592. uint32_t n_tested = 0;
  1593. while (true) {
  1594. if (cache.head + n_tokens > n_ctx) {
  1595. n_tested += n_ctx - cache.head;
  1596. cache.head = 0;
  1597. continue;
  1598. }
  1599. bool found = true;
  1600. for (uint32_t i = 0; i < n_tokens; i++) {
  1601. if (cache.cells[cache.head + i].pos >= 0) {
  1602. found = false;
  1603. cache.head += i + 1;
  1604. n_tested += i + 1;
  1605. break;
  1606. }
  1607. }
  1608. if (found) {
  1609. break;
  1610. }
  1611. if (n_tested >= n_ctx) {
  1612. //LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens);
  1613. return false;
  1614. }
  1615. }
  1616. for (uint32_t i = 0; i < n_tokens; i++) {
  1617. cache.cells[cache.head + i].pos = batch.pos[i];
  1618. for (int32_t j = 0; j < batch.n_seq_id[i]; j++) {
  1619. cache.cells[cache.head + i].seq_id.insert(batch.seq_id[i][j]);
  1620. }
  1621. }
  1622. cache.used += n_tokens;
  1623. return true;
  1624. }
  1625. // find how many cells are currently in use
  1626. static int32_t llama_kv_cache_cell_max(const struct llama_kv_cache & cache) {
  1627. for (uint32_t i = cache.size - 1; i > 0; --i) {
  1628. if (cache.cells[i].pos >= 0 && !cache.cells[i].seq_id.empty()) {
  1629. return i + 1;
  1630. }
  1631. }
  1632. return 0;
  1633. }
  1634. static void llama_kv_cache_clear(struct llama_kv_cache & cache) {
  1635. for (int32_t i = 0; i < (int32_t) cache.size; ++i) {
  1636. cache.cells[i].pos = -1;
  1637. cache.cells[i].seq_id.clear();
  1638. }
  1639. cache.head = 0;
  1640. cache.used = 0;
  1641. }
  1642. static void llama_kv_cache_seq_rm(
  1643. struct llama_kv_cache & cache,
  1644. llama_seq_id seq_id,
  1645. llama_pos p0,
  1646. llama_pos p1) {
  1647. uint32_t new_head = cache.size;
  1648. if (p0 < 0) p0 = 0;
  1649. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1650. for (uint32_t i = 0; i < cache.size; ++i) {
  1651. if (cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1652. if (seq_id < 0) {
  1653. cache.cells[i].seq_id.clear();
  1654. } else if (cache.cells[i].has_seq_id(seq_id)) {
  1655. cache.cells[i].seq_id.erase(seq_id);
  1656. } else {
  1657. continue;
  1658. }
  1659. if (cache.cells[i].seq_id.empty()) {
  1660. // keep count of the number of used cells
  1661. if (cache.cells[i].pos >= 0) cache.used--;
  1662. cache.cells[i].pos = -1;
  1663. if (new_head == cache.size) new_head = i;
  1664. }
  1665. }
  1666. }
  1667. // If we freed up a slot, set head to it so searching can start there.
  1668. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  1669. }
  1670. static void llama_kv_cache_seq_cp(
  1671. struct llama_kv_cache & cache,
  1672. llama_seq_id seq_id_src,
  1673. llama_seq_id seq_id_dst,
  1674. llama_pos p0,
  1675. llama_pos p1) {
  1676. if (p0 < 0) p0 = 0;
  1677. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1678. cache.head = 0;
  1679. for (uint32_t i = 0; i < cache.size; ++i) {
  1680. if (cache.cells[i].has_seq_id(seq_id_src) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1681. cache.cells[i].seq_id.insert(seq_id_dst);
  1682. }
  1683. }
  1684. }
  1685. static void llama_kv_cache_seq_keep(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  1686. uint32_t new_head = cache.size;
  1687. for (uint32_t i = 0; i < cache.size; ++i) {
  1688. if (!cache.cells[i].has_seq_id(seq_id)) {
  1689. if (cache.cells[i].pos >= 0) cache.used--;
  1690. cache.cells[i].pos = -1;
  1691. cache.cells[i].seq_id.clear();
  1692. if (new_head == cache.size) new_head = i;
  1693. } else {
  1694. cache.cells[i].seq_id.clear();
  1695. cache.cells[i].seq_id.insert(seq_id);
  1696. }
  1697. }
  1698. // If we freed up a slot, set head to it so searching can start there.
  1699. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  1700. }
  1701. static void llama_kv_cache_seq_shift(
  1702. struct llama_kv_cache & cache,
  1703. llama_seq_id seq_id,
  1704. llama_pos p0,
  1705. llama_pos p1,
  1706. llama_pos delta) {
  1707. uint32_t new_head = cache.size;
  1708. if (p0 < 0) p0 = 0;
  1709. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1710. for (uint32_t i = 0; i < cache.size; ++i) {
  1711. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1712. cache.has_shift = true;
  1713. cache.cells[i].pos += delta;
  1714. cache.cells[i].delta += delta;
  1715. if (cache.cells[i].pos < 0) {
  1716. if (!cache.cells[i].seq_id.empty()) cache.used--;
  1717. cache.cells[i].pos = -1;
  1718. cache.cells[i].seq_id.clear();
  1719. if (new_head == cache.size) new_head = i;
  1720. }
  1721. }
  1722. }
  1723. // If we freed up a slot, set head to it so searching can start there.
  1724. // Otherwise we just start the next search from the beginning.
  1725. cache.head = new_head != cache.size ? new_head : 0;
  1726. }
  1727. static void llama_kv_cache_seq_div(
  1728. struct llama_kv_cache & cache,
  1729. llama_seq_id seq_id,
  1730. llama_pos p0,
  1731. llama_pos p1,
  1732. int d) {
  1733. if (p0 < 0) p0 = 0;
  1734. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1735. for (uint32_t i = 0; i < cache.size; ++i) {
  1736. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1737. cache.has_shift = true;
  1738. {
  1739. llama_pos p_old = cache.cells[i].pos;
  1740. cache.cells[i].pos /= d;
  1741. cache.cells[i].delta += cache.cells[i].pos - p_old;
  1742. }
  1743. }
  1744. }
  1745. }
  1746. //
  1747. // model loading and saving
  1748. //
  1749. enum llama_fver {
  1750. GGUF_FILE_VERSION_V1 = 1,
  1751. GGUF_FILE_VERSION_V2 = 2,
  1752. GGUF_FILE_VERSION_V3 = 3,
  1753. };
  1754. static const char * llama_file_version_name(llama_fver version) {
  1755. switch (version) {
  1756. case GGUF_FILE_VERSION_V1: return "GGUF V1 (support until nov 2023)";
  1757. case GGUF_FILE_VERSION_V2: return "GGUF V2";
  1758. case GGUF_FILE_VERSION_V3: return "GGUF V3 (latest)";
  1759. }
  1760. return "unknown";
  1761. }
  1762. static std::string llama_format_tensor_shape(const std::vector<int64_t> & ne) {
  1763. char buf[256];
  1764. snprintf(buf, sizeof(buf), "%5" PRId64, ne.at(0));
  1765. for (size_t i = 1; i < ne.size(); i++) {
  1766. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, ne.at(i));
  1767. }
  1768. return buf;
  1769. }
  1770. static std::string llama_format_tensor_shape(const struct ggml_tensor * t) {
  1771. char buf[256];
  1772. snprintf(buf, sizeof(buf), "%5" PRId64, t->ne[0]);
  1773. for (int i = 1; i < GGML_MAX_DIMS; i++) {
  1774. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, t->ne[i]);
  1775. }
  1776. return buf;
  1777. }
  1778. namespace GGUFMeta {
  1779. template <typename T, gguf_type gt_, T (*gfun)(const gguf_context *, const int)>
  1780. struct GKV_Base_Type {
  1781. static constexpr gguf_type gt = gt_;
  1782. static T getter(const gguf_context * ctx, const int kid) {
  1783. return gfun(ctx, kid);
  1784. }
  1785. };
  1786. template<typename T> struct GKV_Base;
  1787. template<> struct GKV_Base<bool >: GKV_Base_Type<bool, GGUF_TYPE_BOOL, gguf_get_val_bool> {};
  1788. template<> struct GKV_Base<uint8_t >: GKV_Base_Type<uint8_t, GGUF_TYPE_UINT8, gguf_get_val_u8 > {};
  1789. template<> struct GKV_Base<uint16_t >: GKV_Base_Type<uint16_t, GGUF_TYPE_UINT16, gguf_get_val_u16 > {};
  1790. template<> struct GKV_Base<uint32_t >: GKV_Base_Type<uint32_t, GGUF_TYPE_UINT32, gguf_get_val_u32 > {};
  1791. template<> struct GKV_Base<uint64_t >: GKV_Base_Type<uint64_t, GGUF_TYPE_UINT64, gguf_get_val_u64 > {};
  1792. template<> struct GKV_Base<int8_t >: GKV_Base_Type<int8_t, GGUF_TYPE_INT8, gguf_get_val_i8 > {};
  1793. template<> struct GKV_Base<int16_t >: GKV_Base_Type<int16_t, GGUF_TYPE_INT16, gguf_get_val_i16 > {};
  1794. template<> struct GKV_Base<int32_t >: GKV_Base_Type<int32_t, GGUF_TYPE_INT32, gguf_get_val_i32 > {};
  1795. template<> struct GKV_Base<int64_t >: GKV_Base_Type<int64_t, GGUF_TYPE_INT64, gguf_get_val_i64 > {};
  1796. template<> struct GKV_Base<float >: GKV_Base_Type<float, GGUF_TYPE_FLOAT32, gguf_get_val_f32 > {};
  1797. template<> struct GKV_Base<double >: GKV_Base_Type<double, GGUF_TYPE_FLOAT64, gguf_get_val_f64 > {};
  1798. template<> struct GKV_Base<const char *>: GKV_Base_Type<const char *, GGUF_TYPE_STRING, gguf_get_val_str > {};
  1799. template<> struct GKV_Base<std::string> {
  1800. static constexpr gguf_type gt = GGUF_TYPE_STRING;
  1801. static std::string getter(const gguf_context * ctx, const int kid) {
  1802. return gguf_get_val_str(ctx, kid);
  1803. }
  1804. };
  1805. struct ArrayInfo{
  1806. const gguf_type gt;
  1807. const size_t length;
  1808. const void * data;
  1809. };
  1810. template<> struct GKV_Base<ArrayInfo> {
  1811. public:
  1812. static constexpr gguf_type gt = GGUF_TYPE_ARRAY;
  1813. static ArrayInfo getter(const gguf_context *ctx, const int k) {
  1814. return ArrayInfo {
  1815. gguf_get_arr_type(ctx, k),
  1816. size_t(gguf_get_arr_n(ctx, k)),
  1817. gguf_get_arr_data(ctx, k),
  1818. };
  1819. }
  1820. };
  1821. template<typename T>
  1822. class GKV: public GKV_Base<T> {
  1823. GKV() = delete;
  1824. public:
  1825. static T get_kv(const gguf_context * ctx, const int k) {
  1826. const enum gguf_type kt = gguf_get_kv_type(ctx, k);
  1827. if (kt != GKV::gt) {
  1828. throw std::runtime_error(format("key %s has wrong type %s but expected type %s",
  1829. gguf_get_key(ctx, k), gguf_type_name(kt), gguf_type_name(GKV::gt)));
  1830. }
  1831. return GKV::getter(ctx, k);
  1832. }
  1833. static const char * override_type_to_str(const llama_model_kv_override_type ty) {
  1834. switch (ty) {
  1835. case LLAMA_KV_OVERRIDE_BOOL: return "bool";
  1836. case LLAMA_KV_OVERRIDE_INT: return "int";
  1837. case LLAMA_KV_OVERRIDE_FLOAT: return "float";
  1838. }
  1839. return "unknown";
  1840. }
  1841. static bool validate_override(const llama_model_kv_override_type expected_type, const struct llama_model_kv_override *override) {
  1842. if (!override) { return false; }
  1843. if (override->tag == expected_type) {
  1844. LLAMA_LOG_INFO("%s: Using metadata override (%5s) '%s' = ",
  1845. __func__, override_type_to_str(override->tag), override->key);
  1846. switch (override->tag) {
  1847. case LLAMA_KV_OVERRIDE_BOOL: {
  1848. LLAMA_LOG_INFO("%s\n", override->bool_value ? "true" : "false");
  1849. } break;
  1850. case LLAMA_KV_OVERRIDE_INT: {
  1851. LLAMA_LOG_INFO("%" PRId64 "\n", override->int_value);
  1852. } break;
  1853. case LLAMA_KV_OVERRIDE_FLOAT: {
  1854. LLAMA_LOG_INFO("%.6f\n", override->float_value);
  1855. } break;
  1856. default:
  1857. // Shouldn't be possible to end up here, but just in case...
  1858. throw std::runtime_error(
  1859. format("Unsupported attempt to override %s type for metadata key %s\n",
  1860. override_type_to_str(override->tag), override->key));
  1861. }
  1862. return true;
  1863. }
  1864. LLAMA_LOG_WARN("%s: Warning: Bad metadata override type for key '%s', expected %s but got %s\n",
  1865. __func__, override->key, override_type_to_str(expected_type), override_type_to_str(override->tag));
  1866. return false;
  1867. }
  1868. template<typename OT>
  1869. static typename std::enable_if<std::is_same<OT, bool>::value, bool>::type
  1870. try_override(OT & target, const struct llama_model_kv_override *override) {
  1871. if (validate_override(LLAMA_KV_OVERRIDE_BOOL, override)) {
  1872. target = override->bool_value;
  1873. return true;
  1874. }
  1875. return false;
  1876. }
  1877. template<typename OT>
  1878. static typename std::enable_if<!std::is_same<OT, bool>::value && std::is_integral<OT>::value, bool>::type
  1879. try_override(OT & target, const struct llama_model_kv_override *override) {
  1880. if (validate_override(LLAMA_KV_OVERRIDE_INT, override)) {
  1881. target = override->int_value;
  1882. return true;
  1883. }
  1884. return false;
  1885. }
  1886. template<typename OT>
  1887. static typename std::enable_if<std::is_floating_point<OT>::value, bool>::type
  1888. try_override(T & target, const struct llama_model_kv_override *override) {
  1889. if (validate_override(LLAMA_KV_OVERRIDE_FLOAT, override)) {
  1890. target = override->float_value;
  1891. return true;
  1892. }
  1893. return false;
  1894. }
  1895. template<typename OT>
  1896. static typename std::enable_if<std::is_same<OT, std::string>::value, bool>::type
  1897. try_override(T & target, const struct llama_model_kv_override *override) {
  1898. (void)target;
  1899. (void)override;
  1900. if (!override) { return false; }
  1901. // Currently, we should never end up here so it would be a bug if we do.
  1902. throw std::runtime_error(format("Unsupported attempt to override string type for metadata key %s\n",
  1903. override ? override->key : "NULL"));
  1904. }
  1905. static bool set(const gguf_context * ctx, const int k, T & target, const struct llama_model_kv_override *override = nullptr) {
  1906. if (try_override<T>(target, override)) {
  1907. return true;
  1908. }
  1909. if (k < 0) { return false; }
  1910. target = get_kv(ctx, k);
  1911. return true;
  1912. }
  1913. static bool set(const gguf_context * ctx, const char * key, T & target, const struct llama_model_kv_override *override = nullptr) {
  1914. return set(ctx, gguf_find_key(ctx, key), target, override);
  1915. }
  1916. static bool set(const gguf_context * ctx, const std::string & key, T & target, const struct llama_model_kv_override *override = nullptr) {
  1917. return set(ctx, key.c_str(), target, override);
  1918. }
  1919. };
  1920. }
  1921. struct llama_model_loader {
  1922. int n_kv = 0;
  1923. int n_tensors = 0;
  1924. int n_created = 0;
  1925. int64_t n_elements = 0;
  1926. size_t n_bytes = 0;
  1927. bool use_mmap = false;
  1928. llama_file file;
  1929. llama_ftype ftype;
  1930. llama_fver fver;
  1931. std::unique_ptr<llama_mmap> mapping;
  1932. std::unordered_map<std::string, struct llama_model_kv_override> kv_overrides;
  1933. struct gguf_context * ctx_gguf = NULL;
  1934. struct ggml_context * ctx_meta = NULL;
  1935. std::string arch_name;
  1936. LLM_KV llm_kv = LLM_KV(LLM_ARCH_UNKNOWN);
  1937. llama_model_loader(const std::string & fname, bool use_mmap, const struct llama_model_kv_override * param_overrides_p) : file(fname.c_str(), "rb") {
  1938. int trace = 0;
  1939. if (getenv("LLAMA_TRACE")) {
  1940. trace = atoi(getenv("LLAMA_TRACE"));
  1941. }
  1942. struct gguf_init_params params = {
  1943. /*.no_alloc = */ true,
  1944. /*.ctx = */ &ctx_meta,
  1945. };
  1946. if (param_overrides_p != nullptr) {
  1947. for (const struct llama_model_kv_override *p = param_overrides_p; p->key[0] != 0; p++) {
  1948. kv_overrides.insert({std::string(p->key), *p});
  1949. }
  1950. }
  1951. ctx_gguf = gguf_init_from_file(fname.c_str(), params);
  1952. if (!ctx_gguf) {
  1953. throw std::runtime_error(format("%s: failed to load model from %s\n", __func__, fname.c_str()));
  1954. }
  1955. get_key(llm_kv(LLM_KV_GENERAL_ARCHITECTURE), arch_name, false);
  1956. llm_kv = LLM_KV(llm_arch_from_string(arch_name));
  1957. n_kv = gguf_get_n_kv(ctx_gguf);
  1958. n_tensors = gguf_get_n_tensors(ctx_gguf);
  1959. fver = (enum llama_fver ) gguf_get_version(ctx_gguf);
  1960. for (int i = 0; i < n_tensors; i++) {
  1961. const char * name = gguf_get_tensor_name(ctx_gguf, i);
  1962. struct ggml_tensor * t = ggml_get_tensor(ctx_meta, name);
  1963. n_elements += ggml_nelements(t);
  1964. n_bytes += ggml_nbytes(t);
  1965. }
  1966. LLAMA_LOG_INFO("%s: loaded meta data with %d key-value pairs and %d tensors from %s (version %s)\n",
  1967. __func__, n_kv, n_tensors, fname.c_str(), llama_file_version_name(fver));
  1968. // determine file type based on the number of tensors for each quantization and print meta data
  1969. // TODO: make optional
  1970. {
  1971. std::map<enum ggml_type, uint32_t> n_type;
  1972. uint32_t n_type_max = 0;
  1973. enum ggml_type type_max = GGML_TYPE_F32;
  1974. for (int i = 0; i < n_tensors; i++) {
  1975. enum ggml_type type = gguf_get_tensor_type(ctx_gguf, i);
  1976. n_type[type]++;
  1977. if (n_type_max < n_type[type]) {
  1978. n_type_max = n_type[type];
  1979. type_max = type;
  1980. }
  1981. if (trace > 0) {
  1982. struct ggml_tensor * meta = ggml_get_tensor(ctx_meta, gguf_get_tensor_name(ctx_gguf, i));
  1983. 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());
  1984. }
  1985. }
  1986. switch (type_max) {
  1987. case GGML_TYPE_F32: ftype = LLAMA_FTYPE_ALL_F32; break;
  1988. case GGML_TYPE_F16: ftype = LLAMA_FTYPE_MOSTLY_F16; break;
  1989. case GGML_TYPE_Q4_0: ftype = LLAMA_FTYPE_MOSTLY_Q4_0; break;
  1990. case GGML_TYPE_Q4_1: ftype = LLAMA_FTYPE_MOSTLY_Q4_1; break;
  1991. case GGML_TYPE_Q5_0: ftype = LLAMA_FTYPE_MOSTLY_Q5_0; break;
  1992. case GGML_TYPE_Q5_1: ftype = LLAMA_FTYPE_MOSTLY_Q5_1; break;
  1993. case GGML_TYPE_Q8_0: ftype = LLAMA_FTYPE_MOSTLY_Q8_0; break;
  1994. case GGML_TYPE_Q2_K: ftype = LLAMA_FTYPE_MOSTLY_Q2_K; break;
  1995. case GGML_TYPE_Q3_K: ftype = LLAMA_FTYPE_MOSTLY_Q3_K_M; break;
  1996. case GGML_TYPE_Q4_K: ftype = LLAMA_FTYPE_MOSTLY_Q4_K_M; break;
  1997. case GGML_TYPE_Q5_K: ftype = LLAMA_FTYPE_MOSTLY_Q5_K_M; break;
  1998. case GGML_TYPE_Q6_K: ftype = LLAMA_FTYPE_MOSTLY_Q6_K; break;
  1999. case GGML_TYPE_IQ2_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XXS; break;
  2000. case GGML_TYPE_IQ2_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XS; break;
  2001. default:
  2002. {
  2003. LLAMA_LOG_WARN("%s: unknown type %s\n", __func__, ggml_type_name(type_max));
  2004. ftype = LLAMA_FTYPE_ALL_F32;
  2005. } break;
  2006. }
  2007. // this is a way to mark that we have "guessed" the file type
  2008. ftype = (llama_ftype) (ftype | LLAMA_FTYPE_GUESSED);
  2009. {
  2010. const int kid = gguf_find_key(ctx_gguf, "general.file_type");
  2011. if (kid >= 0) {
  2012. ftype = (llama_ftype) gguf_get_val_u32(ctx_gguf, kid);
  2013. }
  2014. }
  2015. LLAMA_LOG_INFO("%s: Dumping metadata keys/values. Note: KV overrides do not apply in this output.\n", __func__);
  2016. for (int i = 0; i < n_kv; i++) {
  2017. const char * name = gguf_get_key(ctx_gguf, i);
  2018. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  2019. const std::string type_name =
  2020. type == GGUF_TYPE_ARRAY
  2021. ? 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))
  2022. : gguf_type_name(type);
  2023. std::string value = gguf_kv_to_str(ctx_gguf, i);
  2024. const size_t MAX_VALUE_LEN = 40;
  2025. if (value.size() > MAX_VALUE_LEN) {
  2026. value = format("%s...", value.substr(0, MAX_VALUE_LEN - 3).c_str());
  2027. }
  2028. replace_all(value, "\n", "\\n");
  2029. LLAMA_LOG_INFO("%s: - kv %3d: %42s %-16s = %s\n", __func__, i, name, type_name.c_str(), value.c_str());
  2030. }
  2031. // print type counts
  2032. for (auto & kv : n_type) {
  2033. if (kv.second == 0) {
  2034. continue;
  2035. }
  2036. LLAMA_LOG_INFO("%s: - type %4s: %4d tensors\n", __func__, ggml_type_name(kv.first), kv.second);
  2037. }
  2038. }
  2039. if (!llama_mmap::SUPPORTED) {
  2040. LLAMA_LOG_WARN("%s: mmap is not supported on this platform\n", __func__);
  2041. use_mmap = false;
  2042. }
  2043. this->use_mmap = use_mmap;
  2044. }
  2045. ~llama_model_loader() {
  2046. if (ctx_gguf) {
  2047. gguf_free(ctx_gguf);
  2048. }
  2049. if (ctx_meta) {
  2050. ggml_free(ctx_meta);
  2051. }
  2052. }
  2053. template<typename T>
  2054. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2055. get_arr_n(const std::string & key, T & result, const bool required = true) {
  2056. const int kid = gguf_find_key(ctx_gguf, key.c_str());
  2057. if (kid < 0) {
  2058. if (required) {
  2059. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2060. }
  2061. return false;
  2062. }
  2063. struct GGUFMeta::ArrayInfo arr_info =
  2064. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(ctx_gguf, kid);
  2065. result = arr_info.length;
  2066. return true;
  2067. }
  2068. template<typename T>
  2069. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2070. get_arr_n(const enum llm_kv kid, T & result, const bool required = true) {
  2071. return get_arr_n(llm_kv(kid), result, required);
  2072. }
  2073. template<typename T>
  2074. bool get_key(const std::string & key, T & result, const bool required = true) {
  2075. auto it = kv_overrides.find(key);
  2076. const struct llama_model_kv_override * override =
  2077. it != kv_overrides.end() ? &it->second : nullptr;
  2078. const bool found = GGUFMeta::GKV<T>::set(ctx_gguf, key, result, override);
  2079. if (required && !found) {
  2080. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2081. }
  2082. return found;
  2083. }
  2084. template<typename T>
  2085. bool get_key(const enum llm_kv kid, T & result, const bool required = true) {
  2086. return get_key(llm_kv(kid), result, required);
  2087. }
  2088. std::string get_arch_name() const {
  2089. return arch_name;
  2090. }
  2091. enum llm_arch get_arch() const {
  2092. return llm_kv.arch;
  2093. }
  2094. const char * get_tensor_name(int i) const {
  2095. return gguf_get_tensor_name(ctx_gguf, i);
  2096. }
  2097. struct ggml_tensor * get_tensor_meta(const char * name) const {
  2098. return ggml_get_tensor(ctx_meta, name);
  2099. }
  2100. struct ggml_tensor * get_tensor_meta(int i) const {
  2101. return get_tensor_meta(get_tensor_name(i));
  2102. }
  2103. struct ggml_tensor * create_tensor_for(struct ggml_context * ctx, struct ggml_tensor * meta) {
  2104. struct ggml_tensor * tensor = ggml_dup_tensor(ctx, meta);
  2105. ggml_set_name(tensor, ggml_get_name(meta));
  2106. n_created++;
  2107. return tensor;
  2108. }
  2109. struct ggml_tensor * create_tensor(struct ggml_context * ctx, const std::string & name, const std::vector<int64_t> & ne, bool required = true) {
  2110. struct ggml_tensor * cur = ggml_get_tensor(ctx_meta, name.c_str());
  2111. if (cur == NULL) {
  2112. if (!required) {
  2113. return NULL;
  2114. }
  2115. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
  2116. }
  2117. {
  2118. bool is_ok = true;
  2119. for (size_t i = 0; i < ne.size(); ++i) {
  2120. if (ne[i] != cur->ne[i]) {
  2121. is_ok = false;
  2122. break;
  2123. }
  2124. }
  2125. if (!is_ok) {
  2126. throw std::runtime_error(
  2127. format("%s: tensor '%s' has wrong shape; expected %s, got %s",
  2128. __func__, name.c_str(),
  2129. llama_format_tensor_shape(ne).c_str(),
  2130. llama_format_tensor_shape(cur).c_str()));
  2131. }
  2132. }
  2133. return create_tensor_for(ctx, cur);
  2134. }
  2135. void done_getting_tensors() const {
  2136. if (n_created != n_tensors) {
  2137. throw std::runtime_error(format("%s: wrong number of tensors; expected %d, got %d", __func__, n_tensors, n_created));
  2138. }
  2139. }
  2140. size_t file_offset(const char * name) const {
  2141. const int idx = gguf_find_tensor(ctx_gguf, name);
  2142. if (idx < 0) {
  2143. throw std::runtime_error(format("%s: tensor '%s' not found in the file", __func__, name));
  2144. }
  2145. return gguf_get_data_offset(ctx_gguf) + gguf_get_tensor_offset(ctx_gguf, idx);
  2146. }
  2147. void init_mapping(bool prefetch = true, llama_mlock * lmlock = nullptr) {
  2148. // prefetch the whole file - all the data is needed anyway
  2149. if (use_mmap) {
  2150. mapping.reset(new llama_mmap(&file, prefetch ? -1 : 0, ggml_is_numa()));
  2151. }
  2152. // compute the total size of all tensors for progress reporting
  2153. for (int i = 0; i < gguf_get_n_tensors(ctx_gguf); i++) {
  2154. struct ggml_tensor * cur = ggml_get_tensor(ctx_meta, gguf_get_tensor_name(ctx_gguf, i));
  2155. size_data += ggml_nbytes(cur);
  2156. }
  2157. if (use_mmap && mapping) {
  2158. if (lmlock) {
  2159. lmlock->init(mapping->addr);
  2160. }
  2161. mmap_used_first = mapping->size;
  2162. }
  2163. }
  2164. void get_mapping_range(size_t * first, size_t * last, ggml_context * ctx) const {
  2165. GGML_ASSERT(mapping);
  2166. *first = mapping->size;
  2167. *last = 0;
  2168. for (ggml_tensor * tensor = ggml_get_first_tensor(ctx); tensor; tensor = ggml_get_next_tensor(ctx, tensor)) {
  2169. const size_t offs = file_offset(ggml_get_name(tensor));
  2170. *first = std::min(*first, offs);
  2171. *last = std::max(*last, offs + ggml_nbytes(tensor));
  2172. }
  2173. }
  2174. // for backwards compatibility, does not support ggml-backend
  2175. void load_data_for(struct ggml_tensor * cur) const {
  2176. const size_t offs = file_offset(ggml_get_name(cur));
  2177. if (use_mmap && mapping) {
  2178. if (cur->data == nullptr) {
  2179. cur->data = (uint8_t *)mapping->addr + offs;
  2180. } else {
  2181. memcpy(cur->data, (uint8_t *)mapping->addr + offs, ggml_nbytes(cur));
  2182. }
  2183. } else {
  2184. GGML_ASSERT(cur->data != nullptr);
  2185. file.seek(offs, SEEK_SET);
  2186. file.read_raw(cur->data, ggml_nbytes(cur));
  2187. }
  2188. }
  2189. size_t size_done = 0;
  2190. size_t size_data = 0;
  2191. size_t mmap_used_first = -1;
  2192. size_t mmap_used_last = 0;
  2193. // Returns false if cancelled by progress_callback
  2194. 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) {
  2195. GGML_ASSERT(size_data != 0 && "call init_mapping() first");
  2196. std::vector<no_init<uint8_t>> read_buf;
  2197. for (int i = 0; i < gguf_get_n_tensors(ctx_gguf); i++) {
  2198. struct ggml_tensor * cur = ggml_get_tensor(ctx, gguf_get_tensor_name(ctx_gguf, i));
  2199. if (!cur) {
  2200. // some tensors may be allocated in a different context
  2201. continue;
  2202. }
  2203. if (progress_callback) {
  2204. if (!progress_callback((float) size_done / size_data, progress_callback_user_data)) {
  2205. return false;
  2206. }
  2207. }
  2208. const size_t offs = file_offset(ggml_get_name(cur));
  2209. if (use_mmap && mapping) {
  2210. if (buf_mmap && cur->data == nullptr) {
  2211. ggml_backend_tensor_alloc(buf_mmap, cur, (uint8_t *) mapping->addr + offs);
  2212. if (lmlock) {
  2213. lmlock->grow_to(offs + ggml_nbytes(cur));
  2214. }
  2215. mmap_used_first = std::min(mmap_used_first, offs);
  2216. mmap_used_last = std::max(mmap_used_last, offs + ggml_nbytes(cur));
  2217. } else {
  2218. ggml_backend_tensor_set(cur, (uint8_t *) mapping->addr + offs, 0, ggml_nbytes(cur));
  2219. }
  2220. } else {
  2221. if (ggml_backend_buffer_is_host(cur->buffer)) {
  2222. file.seek(offs, SEEK_SET);
  2223. file.read_raw(cur->data, ggml_nbytes(cur));
  2224. } else {
  2225. read_buf.resize(ggml_nbytes(cur));
  2226. file.seek(offs, SEEK_SET);
  2227. file.read_raw(read_buf.data(), ggml_nbytes(cur));
  2228. ggml_backend_tensor_set(cur, read_buf.data(), 0, ggml_nbytes(cur));
  2229. }
  2230. }
  2231. size_done += ggml_nbytes(cur);
  2232. }
  2233. // check if this is the last call and do final cleanup
  2234. if (size_done >= size_data) {
  2235. // unmap offloaded tensors and metadata
  2236. if (use_mmap && mapping) {
  2237. mapping->unmap_fragment(0, mmap_used_first);
  2238. if (mmap_used_last != 0) {
  2239. mapping->unmap_fragment(mmap_used_last, mapping->size);
  2240. }
  2241. }
  2242. if (progress_callback) {
  2243. // Even though the model is done loading, we still honor
  2244. // cancellation since we need to free allocations.
  2245. return progress_callback(1.0f, progress_callback_user_data);
  2246. }
  2247. }
  2248. return true;
  2249. }
  2250. };
  2251. //
  2252. // load LLaMA models
  2253. //
  2254. static std::string llama_model_arch_name(llm_arch arch) {
  2255. auto it = LLM_ARCH_NAMES.find(arch);
  2256. if (it == LLM_ARCH_NAMES.end()) {
  2257. return "unknown";
  2258. }
  2259. return it->second;
  2260. }
  2261. static std::string llama_model_ftype_name(llama_ftype ftype) {
  2262. if (ftype & LLAMA_FTYPE_GUESSED) {
  2263. return llama_model_ftype_name((enum llama_ftype) (ftype & ~LLAMA_FTYPE_GUESSED)) + " (guessed)";
  2264. }
  2265. switch (ftype) {
  2266. case LLAMA_FTYPE_ALL_F32: return "all F32";
  2267. case LLAMA_FTYPE_MOSTLY_F16: return "F16";
  2268. case LLAMA_FTYPE_MOSTLY_Q4_0: return "Q4_0";
  2269. case LLAMA_FTYPE_MOSTLY_Q4_1: return "Q4_1";
  2270. case LLAMA_FTYPE_MOSTLY_Q4_1_SOME_F16:
  2271. return "Q4_1, some F16";
  2272. case LLAMA_FTYPE_MOSTLY_Q5_0: return "Q5_0";
  2273. case LLAMA_FTYPE_MOSTLY_Q5_1: return "Q5_1";
  2274. case LLAMA_FTYPE_MOSTLY_Q8_0: return "Q8_0";
  2275. // K-quants
  2276. case LLAMA_FTYPE_MOSTLY_Q2_K: return "Q2_K - Medium";
  2277. case LLAMA_FTYPE_MOSTLY_Q2_K_S: return "Q2_K - Small";
  2278. case LLAMA_FTYPE_MOSTLY_Q3_K_S: return "Q3_K - Small";
  2279. case LLAMA_FTYPE_MOSTLY_Q3_K_M: return "Q3_K - Medium";
  2280. case LLAMA_FTYPE_MOSTLY_Q3_K_L: return "Q3_K - Large";
  2281. case LLAMA_FTYPE_MOSTLY_Q4_K_S: return "Q4_K - Small";
  2282. case LLAMA_FTYPE_MOSTLY_Q4_K_M: return "Q4_K - Medium";
  2283. case LLAMA_FTYPE_MOSTLY_Q5_K_S: return "Q5_K - Small";
  2284. case LLAMA_FTYPE_MOSTLY_Q5_K_M: return "Q5_K - Medium";
  2285. case LLAMA_FTYPE_MOSTLY_Q6_K: return "Q6_K";
  2286. case LLAMA_FTYPE_MOSTLY_IQ2_XXS:return "IQ2_XSS - 2.0625 bpw";
  2287. case LLAMA_FTYPE_MOSTLY_IQ2_XS: return "IQ2_XS - 2.3125 bpw";
  2288. case LLAMA_FTYPE_MOSTLY_Q3_K_XS:return "Q3_K - Extra small";
  2289. default: return "unknown, may not work";
  2290. }
  2291. }
  2292. static const char * llama_model_type_name(e_model type) {
  2293. switch (type) {
  2294. case MODEL_1B: return "1B";
  2295. case MODEL_3B: return "3B";
  2296. case MODEL_7B: return "7B";
  2297. case MODEL_8B: return "8B";
  2298. case MODEL_13B: return "13B";
  2299. case MODEL_15B: return "15B";
  2300. case MODEL_30B: return "30B";
  2301. case MODEL_34B: return "34B";
  2302. case MODEL_40B: return "40B";
  2303. case MODEL_65B: return "65B";
  2304. case MODEL_70B: return "70B";
  2305. case MODEL_SMALL: return "0.1B";
  2306. case MODEL_MEDIUM: return "0.4B";
  2307. case MODEL_LARGE: return "0.8B";
  2308. case MODEL_XL: return "1.5B";
  2309. default: return "?B";
  2310. }
  2311. }
  2312. static void llm_load_arch(llama_model_loader & ml, llama_model & model) {
  2313. model.arch = ml.get_arch();
  2314. if (model.arch == LLM_ARCH_UNKNOWN) {
  2315. throw std::runtime_error("unknown model architecture: '" + ml.get_arch_name() + "'");
  2316. }
  2317. }
  2318. static void llm_load_hparams(
  2319. llama_model_loader & ml,
  2320. llama_model & model) {
  2321. auto & hparams = model.hparams;
  2322. const gguf_context * ctx = ml.ctx_gguf;
  2323. // get metadata as string
  2324. for (int i = 0; i < gguf_get_n_kv(ctx); i++) {
  2325. enum gguf_type type = gguf_get_kv_type(ctx, i);
  2326. if (type == GGUF_TYPE_ARRAY) {
  2327. continue;
  2328. }
  2329. const char * name = gguf_get_key(ctx, i);
  2330. const std::string value = gguf_kv_to_str(ctx, i);
  2331. model.gguf_kv.emplace(name, value);
  2332. }
  2333. // get general kv
  2334. ml.get_key(LLM_KV_GENERAL_NAME, model.name, false);
  2335. // get hparams kv
  2336. ml.get_arr_n(LLM_KV_TOKENIZER_LIST, hparams.n_vocab);
  2337. ml.get_key (LLM_KV_CONTEXT_LENGTH, hparams.n_ctx_train);
  2338. ml.get_key (LLM_KV_EMBEDDING_LENGTH, hparams.n_embd);
  2339. ml.get_key (LLM_KV_FEED_FORWARD_LENGTH, hparams.n_ff);
  2340. ml.get_key (LLM_KV_ATTENTION_HEAD_COUNT, hparams.n_head);
  2341. ml.get_key (LLM_KV_BLOCK_COUNT, hparams.n_layer);
  2342. ml.get_key (LLM_KV_EXPERT_COUNT, hparams.n_expert, false);
  2343. ml.get_key (LLM_KV_EXPERT_USED_COUNT, hparams.n_expert_used, false);
  2344. GGML_ASSERT(hparams.n_expert <= LLAMA_MAX_EXPERTS);
  2345. GGML_ASSERT(hparams.n_expert_used <= hparams.n_expert);
  2346. if (hparams.n_expert > 0) {
  2347. GGML_ASSERT(hparams.n_expert_used > 0);
  2348. } else {
  2349. GGML_ASSERT(hparams.n_expert_used == 0);
  2350. }
  2351. // n_head_kv is optional, default to n_head
  2352. hparams.n_head_kv = hparams.n_head;
  2353. ml.get_key(LLM_KV_ATTENTION_HEAD_COUNT_KV, hparams.n_head_kv, false);
  2354. bool rope_finetuned = false;
  2355. ml.get_key(LLM_KV_ROPE_SCALING_FINETUNED, rope_finetuned, false);
  2356. hparams.rope_finetuned = rope_finetuned;
  2357. hparams.n_yarn_orig_ctx = hparams.n_ctx_train;
  2358. ml.get_key(LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, hparams.n_yarn_orig_ctx, false);
  2359. // rope_freq_base (optional)
  2360. hparams.rope_freq_base_train = 10000.0f;
  2361. ml.get_key(LLM_KV_ROPE_FREQ_BASE, hparams.rope_freq_base_train, false);
  2362. std::string rope_scaling("linear");
  2363. ml.get_key(LLM_KV_ROPE_SCALING_TYPE, rope_scaling, false);
  2364. hparams.rope_scaling_type_train = llama_rope_scaling_type_from_string(rope_scaling);
  2365. GGML_ASSERT(hparams.rope_scaling_type_train != LLAMA_ROPE_SCALING_UNSPECIFIED);
  2366. // rope_freq_scale (inverse of the kv) is optional
  2367. float ropescale = 0.0f;
  2368. if (!ml.get_key(LLM_KV_ROPE_SCALING_FACTOR, ropescale, false)) {
  2369. // try the old key name
  2370. ml.get_key(LLM_KV_ROPE_SCALE_LINEAR, ropescale, false);
  2371. }
  2372. hparams.rope_freq_scale_train = ropescale == 0.0f ? 1.0f : 1.0f/ropescale;
  2373. // sanity check for n_rot (optional)
  2374. {
  2375. hparams.n_rot = hparams.n_embd / hparams.n_head;
  2376. ml.get_key(LLM_KV_ROPE_DIMENSION_COUNT, hparams.n_rot, false);
  2377. if (model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON) {
  2378. if (hparams.n_rot != hparams.n_embd / hparams.n_head) {
  2379. throw std::runtime_error(format("invalid n_rot: %u, expected %u", hparams.n_rot, hparams.n_embd / hparams.n_head));
  2380. }
  2381. }
  2382. // gpt-neox n_rot = rotary_pct * (n_embd / n_head)
  2383. // gpt-j n_rot = rotary_dim
  2384. }
  2385. hparams.n_embd_head_k = hparams.n_embd / hparams.n_head;
  2386. ml.get_key(LLM_KV_ATTENTION_KEY_LENGTH, hparams.n_embd_head_k, false);
  2387. hparams.n_embd_head_v = hparams.n_embd / hparams.n_head;
  2388. ml.get_key(LLM_KV_ATTENTION_VALUE_LENGTH, hparams.n_embd_head_v, false);
  2389. // arch-specific KVs
  2390. switch (model.arch) {
  2391. case LLM_ARCH_LLAMA:
  2392. {
  2393. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2394. switch (hparams.n_layer) {
  2395. case 22: model.type = e_model::MODEL_1B; break;
  2396. case 26: model.type = e_model::MODEL_3B; break;
  2397. case 32: model.type = e_model::MODEL_7B; break;
  2398. case 40: model.type = e_model::MODEL_13B; break;
  2399. case 48: model.type = e_model::MODEL_34B; break;
  2400. case 60: model.type = e_model::MODEL_30B; break;
  2401. case 80: model.type = hparams.n_head == hparams.n_head_kv ? e_model::MODEL_65B : e_model::MODEL_70B; break;
  2402. default: model.type = e_model::MODEL_UNKNOWN;
  2403. }
  2404. } break;
  2405. case LLM_ARCH_FALCON:
  2406. {
  2407. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2408. switch (hparams.n_layer) {
  2409. case 32: model.type = e_model::MODEL_7B; break;
  2410. case 60: model.type = e_model::MODEL_40B; break;
  2411. default: model.type = e_model::MODEL_UNKNOWN;
  2412. }
  2413. } break;
  2414. case LLM_ARCH_BAICHUAN:
  2415. {
  2416. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2417. switch (hparams.n_layer) {
  2418. case 32: model.type = e_model::MODEL_7B; break;
  2419. case 40: model.type = e_model::MODEL_13B; break;
  2420. default: model.type = e_model::MODEL_UNKNOWN;
  2421. }
  2422. } break;
  2423. case LLM_ARCH_STARCODER:
  2424. {
  2425. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2426. switch (hparams.n_layer) {
  2427. case 24: model.type = e_model::MODEL_1B; break;
  2428. case 36: model.type = e_model::MODEL_3B; break;
  2429. case 42: model.type = e_model::MODEL_7B; break;
  2430. case 40: model.type = e_model::MODEL_15B; break;
  2431. default: model.type = e_model::MODEL_UNKNOWN;
  2432. }
  2433. } break;
  2434. case LLM_ARCH_PERSIMMON:
  2435. {
  2436. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2437. switch (hparams.n_layer) {
  2438. case 36: model.type = e_model::MODEL_8B; break;
  2439. default: model.type = e_model::MODEL_UNKNOWN;
  2440. }
  2441. } break;
  2442. case LLM_ARCH_REFACT:
  2443. {
  2444. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2445. switch (hparams.n_layer) {
  2446. case 32: model.type = e_model::MODEL_1B; break;
  2447. default: model.type = e_model::MODEL_UNKNOWN;
  2448. }
  2449. } break;
  2450. case LLM_ARCH_BLOOM:
  2451. {
  2452. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2453. switch (hparams.n_layer) {
  2454. case 24: model.type = e_model::MODEL_1B; break;
  2455. case 30:
  2456. switch (hparams.n_embd) {
  2457. case 2560: model.type = e_model::MODEL_3B; break;
  2458. case 4096: model.type = e_model::MODEL_7B; break;
  2459. } break;
  2460. }
  2461. } break;
  2462. case LLM_ARCH_MPT:
  2463. {
  2464. hparams.f_clamp_kqv = 0.0f;
  2465. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2466. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv, false);
  2467. ml.get_key(LLM_KV_ATTENTION_MAX_ALIBI_BIAS, hparams.f_max_alibi_bias);
  2468. switch (hparams.n_layer) {
  2469. case 32: model.type = e_model::MODEL_7B; break;
  2470. case 48: model.type = e_model::MODEL_30B; break;
  2471. default: model.type = e_model::MODEL_UNKNOWN;
  2472. }
  2473. } break;
  2474. case LLM_ARCH_STABLELM:
  2475. {
  2476. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2477. switch (hparams.n_layer) {
  2478. case 24: model.type = e_model::MODEL_1B; break;
  2479. case 32: model.type = e_model::MODEL_3B; break;
  2480. default: model.type = e_model::MODEL_UNKNOWN;
  2481. }
  2482. } break;
  2483. case LLM_ARCH_QWEN:
  2484. {
  2485. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2486. switch (hparams.n_layer) {
  2487. case 32: model.type = e_model::MODEL_7B; break;
  2488. case 40: model.type = e_model::MODEL_13B; break;
  2489. default: model.type = e_model::MODEL_UNKNOWN;
  2490. }
  2491. } break;
  2492. case LLM_ARCH_QWEN2:
  2493. {
  2494. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2495. switch (hparams.n_layer) {
  2496. case 24: model.type = hparams.n_embd == 1024 ? e_model::MODEL_0_5B : e_model::MODEL_1B; break;
  2497. case 32: model.type = e_model::MODEL_7B; break;
  2498. case 40: model.type = hparams.n_head == 20 ? e_model::MODEL_4B : e_model::MODEL_13B; break;
  2499. case 80: model.type = e_model::MODEL_70B; break;
  2500. default: model.type = e_model::MODEL_UNKNOWN;
  2501. }
  2502. } break;
  2503. case LLM_ARCH_PHI2:
  2504. {
  2505. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2506. switch (hparams.n_layer) {
  2507. case 24: model.type = e_model::MODEL_1B; break;
  2508. case 32: model.type = e_model::MODEL_3B; break;
  2509. default: model.type = e_model::MODEL_UNKNOWN;
  2510. }
  2511. } break;
  2512. case LLM_ARCH_PLAMO:
  2513. {
  2514. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2515. switch (hparams.n_layer) {
  2516. case 40: model.type = e_model::MODEL_13B; break;
  2517. default: model.type = e_model::MODEL_UNKNOWN;
  2518. }
  2519. } break;
  2520. case LLM_ARCH_GPT2:
  2521. {
  2522. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2523. switch (hparams.n_layer) {
  2524. case 12: model.type = e_model::MODEL_SMALL; break;
  2525. case 24: model.type = e_model::MODEL_MEDIUM; break;
  2526. case 36: model.type = e_model::MODEL_LARGE; break;
  2527. case 48: model.type = e_model::MODEL_XL; break;
  2528. default: model.type = e_model::MODEL_UNKNOWN;
  2529. }
  2530. } break;
  2531. case LLM_ARCH_CODESHELL:
  2532. {
  2533. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2534. switch (hparams.n_layer) {
  2535. case 42: model.type = e_model::MODEL_SMALL; break;
  2536. default: model.type = e_model::MODEL_UNKNOWN;
  2537. }
  2538. } break;
  2539. default: (void)0;
  2540. }
  2541. model.ftype = ml.ftype;
  2542. }
  2543. // TODO: This should probably be in llama.h
  2544. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special = false);
  2545. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch);
  2546. static void llm_load_vocab(
  2547. llama_model_loader & ml,
  2548. llama_model & model) {
  2549. auto & vocab = model.vocab;
  2550. struct gguf_context * ctx = ml.ctx_gguf;
  2551. const auto kv = LLM_KV(model.arch);
  2552. const int token_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_LIST).c_str());
  2553. if (token_idx == -1) {
  2554. throw std::runtime_error("cannot find tokenizer vocab in model file\n");
  2555. }
  2556. const float * scores = nullptr;
  2557. const int score_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_SCORES).c_str());
  2558. if (score_idx != -1) {
  2559. scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
  2560. }
  2561. const int * toktypes = nullptr;
  2562. const int toktype_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE).c_str());
  2563. if (toktype_idx != -1) {
  2564. toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
  2565. }
  2566. // determine vocab type
  2567. {
  2568. std::string tokenizer_name;
  2569. ml.get_key(LLM_KV_TOKENIZER_MODEL, tokenizer_name);
  2570. if (tokenizer_name == "llama") {
  2571. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  2572. // default special tokens
  2573. vocab.special_bos_id = 1;
  2574. vocab.special_eos_id = 2;
  2575. vocab.special_unk_id = 0;
  2576. vocab.special_sep_id = -1;
  2577. vocab.special_pad_id = -1;
  2578. } else if (tokenizer_name == "gpt2") {
  2579. vocab.type = LLAMA_VOCAB_TYPE_BPE;
  2580. // read bpe merges and populate bpe ranks
  2581. const int merges_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_MERGES).c_str());
  2582. if (merges_keyidx == -1) {
  2583. throw std::runtime_error("cannot find tokenizer merges in model file\n");
  2584. }
  2585. const int n_merges = gguf_get_arr_n(ctx, merges_keyidx);
  2586. for (int i = 0; i < n_merges; i++) {
  2587. const std::string word = gguf_get_arr_str(ctx, merges_keyidx, i);
  2588. GGML_ASSERT(codepoints_from_utf8(word).size() > 0);
  2589. std::string first;
  2590. std::string second;
  2591. const size_t pos = word.find(' ', 1);
  2592. if (pos != std::string::npos) {
  2593. first = word.substr(0, pos);
  2594. second = word.substr(pos + 1);
  2595. }
  2596. vocab.bpe_ranks.emplace(std::make_pair(first, second), i);
  2597. }
  2598. // default special tokens
  2599. vocab.special_bos_id = 11;
  2600. vocab.special_eos_id = 11;
  2601. vocab.special_unk_id = -1;
  2602. vocab.special_sep_id = -1;
  2603. vocab.special_pad_id = -1;
  2604. } else {
  2605. LLAMA_LOG_WARN("%s: unknown tokenizer: '%s'", __func__, tokenizer_name.c_str());
  2606. LLAMA_LOG_WARN("%s: using default tokenizer: 'llama'", __func__);
  2607. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  2608. }
  2609. }
  2610. const uint32_t n_vocab = gguf_get_arr_n(ctx, token_idx);
  2611. vocab.id_to_token.resize(n_vocab);
  2612. for (uint32_t i = 0; i < n_vocab; i++) {
  2613. std::string word = gguf_get_arr_str(ctx, token_idx, i);
  2614. GGML_ASSERT(codepoints_from_utf8(word).size() > 0);
  2615. vocab.token_to_id[word] = i;
  2616. auto & token_data = vocab.id_to_token[i];
  2617. token_data.text = std::move(word);
  2618. token_data.score = scores ? scores[i] : 0.0f;
  2619. token_data.type = toktypes ? (llama_token_type) toktypes[i] : LLAMA_TOKEN_TYPE_NORMAL;
  2620. }
  2621. GGML_ASSERT(vocab.id_to_token.size() == vocab.token_to_id.size());
  2622. // determine the newline token: LLaMA "<0x0A>" == 10 == '\n', Falcon 193 == '\n'
  2623. if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  2624. vocab.linefeed_id = llama_byte_to_token(vocab, '\n');
  2625. } else {
  2626. const std::vector<int> ids = llama_tokenize_internal(vocab, "\u010A", false);
  2627. GGML_ASSERT(!ids.empty() && "model vocab missing newline token");
  2628. vocab.linefeed_id = ids[0];
  2629. }
  2630. // special tokens
  2631. {
  2632. const std::vector<std::pair<enum llm_kv, int32_t &>> special_token_types = {
  2633. { LLM_KV_TOKENIZER_BOS_ID, vocab.special_bos_id },
  2634. { LLM_KV_TOKENIZER_EOS_ID, vocab.special_eos_id },
  2635. { LLM_KV_TOKENIZER_UNK_ID, vocab.special_unk_id },
  2636. { LLM_KV_TOKENIZER_SEP_ID, vocab.special_sep_id },
  2637. { LLM_KV_TOKENIZER_PAD_ID, vocab.special_pad_id },
  2638. };
  2639. for (const auto & it : special_token_types) {
  2640. const std::string & key = kv(std::get<0>(it));
  2641. int32_t & id = std::get<1>(it);
  2642. uint32_t new_id;
  2643. if (!ml.get_key(std::get<0>(it), new_id, false)) {
  2644. continue;
  2645. }
  2646. if (new_id >= vocab.id_to_token.size()) {
  2647. LLAMA_LOG_WARN("%s: bad special token: '%s' = %ud, using default id %d\n",
  2648. __func__, key.c_str(), new_id, id);
  2649. } else {
  2650. id = new_id;
  2651. }
  2652. }
  2653. // Handle add_bos_token and add_eos_token
  2654. {
  2655. bool temp = true;
  2656. if (ml.get_key(LLM_KV_TOKENIZER_ADD_BOS, temp, false)) {
  2657. vocab.special_add_bos = int(temp);
  2658. }
  2659. if (ml.get_key(LLM_KV_TOKENIZER_ADD_EOS, temp, false)) {
  2660. vocab.special_add_eos = int(temp);
  2661. }
  2662. }
  2663. }
  2664. // build special tokens cache
  2665. {
  2666. // TODO: It is unclear (to me) at this point, whether special tokes are guaranteed to be of a deterministic type,
  2667. // and will always be correctly labeled in 'added_tokens.json' etc.
  2668. // The assumption is, since special tokens aren't meant to be exposed to end user, they are designed
  2669. // to be unmatchable by the tokenizer, therefore tokens from the vocab, which are unmatchable by the tokenizer
  2670. // are special tokens.
  2671. // From testing, this appears to correlate 1:1 with special tokens.
  2672. //
  2673. // Counting special tokens and verifying in only one direction
  2674. // is sufficient to detect difference in those two sets.
  2675. //
  2676. uint32_t special_tokens_count_by_type = 0;
  2677. uint32_t special_tokens_count_from_verification = 0;
  2678. bool special_tokens_definition_mismatch = false;
  2679. for (const auto & t : vocab.token_to_id) {
  2680. const auto & token = t.first;
  2681. const auto & id = t.second;
  2682. // Count all non-normal tokens in the vocab while iterating
  2683. if (vocab.id_to_token[id].type != LLAMA_TOKEN_TYPE_NORMAL) {
  2684. special_tokens_count_by_type++;
  2685. }
  2686. // Skip single character tokens
  2687. if (token.length() > 1) {
  2688. bool is_tokenizable = false;
  2689. // Split token string representation in two, in all possible ways
  2690. // and check if both halves can be matched to a valid token
  2691. for (unsigned i = 1; i < token.length();) {
  2692. const auto left = token.substr(0, i);
  2693. const auto right = token.substr(i);
  2694. // check if we didnt partition in the middle of a utf sequence
  2695. auto utf = utf8_len(left.at(left.length() - 1));
  2696. if (utf == 1) {
  2697. if (vocab.token_to_id.find(left) != vocab.token_to_id.end() &&
  2698. vocab.token_to_id.find(right) != vocab.token_to_id.end() ) {
  2699. is_tokenizable = true;
  2700. break;
  2701. }
  2702. i++;
  2703. } else {
  2704. // skip over the rest of multibyte utf sequence
  2705. i += utf - 1;
  2706. }
  2707. }
  2708. if (!is_tokenizable) {
  2709. // Some tokens are multibyte, but they are utf sequences with equivalent text length of 1
  2710. // it's faster to re-filter them here, since there are way less candidates now
  2711. // Calculate a total "utf" length of a token string representation
  2712. size_t utf8_str_len = 0;
  2713. for (unsigned i = 0; i < token.length();) {
  2714. utf8_str_len++;
  2715. i += utf8_len(token.at(i));
  2716. }
  2717. // And skip the ones which are one character
  2718. if (utf8_str_len > 1) {
  2719. // At this point what we have left are special tokens only
  2720. vocab.special_tokens_cache[token] = id;
  2721. // Count manually found special tokens
  2722. special_tokens_count_from_verification++;
  2723. // If this manually found special token is not marked as such, flag a mismatch
  2724. if (vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL) {
  2725. special_tokens_definition_mismatch = true;
  2726. }
  2727. }
  2728. }
  2729. }
  2730. }
  2731. if (special_tokens_definition_mismatch || special_tokens_count_from_verification != special_tokens_count_by_type) {
  2732. LLAMA_LOG_WARN("%s: mismatch in special tokens definition ( %u/%zu vs %u/%zu ).\n",
  2733. __func__,
  2734. special_tokens_count_from_verification, vocab.id_to_token.size(),
  2735. special_tokens_count_by_type, vocab.id_to_token.size()
  2736. );
  2737. } else {
  2738. LLAMA_LOG_INFO("%s: special tokens definition check successful ( %u/%zu ).\n",
  2739. __func__,
  2740. special_tokens_count_from_verification, vocab.id_to_token.size()
  2741. );
  2742. }
  2743. }
  2744. }
  2745. static void llm_load_print_meta(llama_model_loader & ml, llama_model & model) {
  2746. const auto & hparams = model.hparams;
  2747. const auto & vocab = model.vocab;
  2748. const auto rope_scaling_type = LLAMA_ROPE_SCALING_TYPES.at(hparams.rope_scaling_type_train);
  2749. // hparams
  2750. LLAMA_LOG_INFO("%s: format = %s\n", __func__, llama_file_version_name(ml.fver));
  2751. LLAMA_LOG_INFO("%s: arch = %s\n", __func__, LLM_ARCH_NAMES.at(model.arch).c_str());
  2752. LLAMA_LOG_INFO("%s: vocab type = %s\n", __func__, vocab.type == LLAMA_VOCAB_TYPE_SPM ? "SPM" : "BPE"); // TODO: fix
  2753. LLAMA_LOG_INFO("%s: n_vocab = %u\n", __func__, hparams.n_vocab);
  2754. LLAMA_LOG_INFO("%s: n_merges = %u\n", __func__, (int) vocab.bpe_ranks.size());
  2755. LLAMA_LOG_INFO("%s: n_ctx_train = %u\n", __func__, hparams.n_ctx_train);
  2756. LLAMA_LOG_INFO("%s: n_embd = %u\n", __func__, hparams.n_embd);
  2757. LLAMA_LOG_INFO("%s: n_head = %u\n", __func__, hparams.n_head);
  2758. LLAMA_LOG_INFO("%s: n_head_kv = %u\n", __func__, hparams.n_head_kv);
  2759. LLAMA_LOG_INFO("%s: n_layer = %u\n", __func__, hparams.n_layer);
  2760. LLAMA_LOG_INFO("%s: n_rot = %u\n", __func__, hparams.n_rot);
  2761. LLAMA_LOG_INFO("%s: n_embd_head_k = %u\n", __func__, hparams.n_embd_head_k);
  2762. LLAMA_LOG_INFO("%s: n_embd_head_v = %u\n", __func__, hparams.n_embd_head_v);
  2763. LLAMA_LOG_INFO("%s: n_gqa = %u\n", __func__, hparams.n_gqa());
  2764. LLAMA_LOG_INFO("%s: n_embd_k_gqa = %u\n", __func__, hparams.n_embd_k_gqa());
  2765. LLAMA_LOG_INFO("%s: n_embd_v_gqa = %u\n", __func__, hparams.n_embd_v_gqa());
  2766. LLAMA_LOG_INFO("%s: f_norm_eps = %.1e\n", __func__, hparams.f_norm_eps);
  2767. LLAMA_LOG_INFO("%s: f_norm_rms_eps = %.1e\n", __func__, hparams.f_norm_rms_eps);
  2768. LLAMA_LOG_INFO("%s: f_clamp_kqv = %.1e\n", __func__, hparams.f_clamp_kqv);
  2769. LLAMA_LOG_INFO("%s: f_max_alibi_bias = %.1e\n", __func__, hparams.f_max_alibi_bias);
  2770. LLAMA_LOG_INFO("%s: n_ff = %u\n", __func__, hparams.n_ff);
  2771. LLAMA_LOG_INFO("%s: n_expert = %u\n", __func__, hparams.n_expert);
  2772. LLAMA_LOG_INFO("%s: n_expert_used = %u\n", __func__, hparams.n_expert_used);
  2773. LLAMA_LOG_INFO("%s: rope scaling = %s\n", __func__, rope_scaling_type.c_str());
  2774. LLAMA_LOG_INFO("%s: freq_base_train = %.1f\n", __func__, hparams.rope_freq_base_train);
  2775. LLAMA_LOG_INFO("%s: freq_scale_train = %g\n", __func__, hparams.rope_freq_scale_train);
  2776. LLAMA_LOG_INFO("%s: n_yarn_orig_ctx = %u\n", __func__, hparams.n_yarn_orig_ctx);
  2777. LLAMA_LOG_INFO("%s: rope_finetuned = %s\n", __func__, hparams.rope_finetuned ? "yes" : "unknown");
  2778. LLAMA_LOG_INFO("%s: model type = %s\n", __func__, llama_model_type_name(model.type));
  2779. LLAMA_LOG_INFO("%s: model ftype = %s\n", __func__, llama_model_ftype_name(model.ftype).c_str());
  2780. if (ml.n_elements >= 1e12) {
  2781. LLAMA_LOG_INFO("%s: model params = %.2f T\n", __func__, ml.n_elements*1e-12);
  2782. } else if (ml.n_elements >= 1e9) {
  2783. LLAMA_LOG_INFO("%s: model params = %.2f B\n", __func__, ml.n_elements*1e-9);
  2784. } else if (ml.n_elements >= 1e6) {
  2785. LLAMA_LOG_INFO("%s: model params = %.2f M\n", __func__, ml.n_elements*1e-6);
  2786. } else {
  2787. LLAMA_LOG_INFO("%s: model params = %.2f K\n", __func__, ml.n_elements*1e-3);
  2788. }
  2789. if (ml.n_bytes < GiB) {
  2790. 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);
  2791. } else {
  2792. 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);
  2793. }
  2794. // general kv
  2795. LLAMA_LOG_INFO("%s: general.name = %s\n", __func__, model.name.c_str());
  2796. // special tokens
  2797. 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() ); }
  2798. 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() ); }
  2799. 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() ); }
  2800. 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() ); }
  2801. 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() ); }
  2802. 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() ); }
  2803. }
  2804. // Returns false if cancelled by progress_callback
  2805. static bool llm_load_tensors(
  2806. llama_model_loader & ml,
  2807. llama_model & model,
  2808. int n_gpu_layers,
  2809. enum llama_split_mode split_mode,
  2810. int main_gpu,
  2811. const float * tensor_split,
  2812. bool use_mlock,
  2813. llama_progress_callback progress_callback,
  2814. void * progress_callback_user_data) {
  2815. model.t_start_us = ggml_time_us();
  2816. auto & hparams = model.hparams;
  2817. model.split_mode = split_mode;
  2818. model.main_gpu = main_gpu;
  2819. model.n_gpu_layers = n_gpu_layers;
  2820. const int64_t n_layer = hparams.n_layer;
  2821. const int64_t i_gpu_start = std::max((int64_t) hparams.n_layer - n_gpu_layers, (int64_t) 0);
  2822. // there is very little benefit to offloading the input layer, so always keep it on the CPU
  2823. model.buft_input = llama_default_buffer_type_cpu(true);
  2824. model.buft_layer.resize(n_layer);
  2825. // assign cpu layers
  2826. for (int64_t i = 0; i < i_gpu_start; ++i) {
  2827. model.buft_layer[i] = llama_default_buffer_type_cpu(true);
  2828. }
  2829. #ifdef GGML_USE_CUBLAS
  2830. if (split_mode == LLAMA_SPLIT_LAYER) {
  2831. // calculate the split points
  2832. int device_count = ggml_backend_cuda_get_device_count();
  2833. bool all_zero = tensor_split == nullptr || std::all_of(tensor_split, tensor_split + device_count, [](float x) { return x == 0.0f; });
  2834. float splits[GGML_CUDA_MAX_DEVICES];
  2835. if (all_zero) {
  2836. // default split, by free memory
  2837. for (int i = 0; i < device_count; ++i) {
  2838. size_t total;
  2839. size_t free;
  2840. ggml_backend_cuda_get_device_memory(i, &total, &free);
  2841. splits[i] = free;
  2842. }
  2843. } else {
  2844. std::copy(tensor_split, tensor_split + device_count, splits);
  2845. }
  2846. // sum and normalize the splits to get the split points
  2847. float split_sum = 0.0f;
  2848. for (int i = 0; i < device_count; ++i) {
  2849. split_sum += splits[i];
  2850. splits[i] = split_sum;
  2851. }
  2852. for (int i = 0; i < device_count; ++i) {
  2853. splits[i] /= split_sum;
  2854. }
  2855. // assign the repeating layers to the devices according to the splits
  2856. int act_gpu_layers = std::min(n_gpu_layers, (int)n_layer + 1);
  2857. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  2858. int layer_gpu = std::upper_bound(splits, splits + device_count, float(i - i_gpu_start)/act_gpu_layers) - splits;
  2859. model.buft_layer[i] = llama_default_buffer_type_offload(layer_gpu);
  2860. }
  2861. // assign the output layer
  2862. if (n_gpu_layers > n_layer) {
  2863. int layer_gpu = std::upper_bound(splits, splits + device_count, float(act_gpu_layers - 1)/act_gpu_layers) - splits;
  2864. model.buft_output = llama_default_buffer_type_offload(layer_gpu);
  2865. } else {
  2866. model.buft_output = llama_default_buffer_type_cpu(true);
  2867. }
  2868. } else
  2869. #endif
  2870. {
  2871. ggml_backend_buffer_type_t split_buft;
  2872. if (split_mode == LLAMA_SPLIT_ROW) {
  2873. split_buft = llama_default_buffer_type_split(main_gpu, tensor_split);
  2874. } else {
  2875. // LLAMA_SPLIT_NONE or LLAMA_SPLIT_LAYER in backends where it is not supported
  2876. split_buft = llama_default_buffer_type_offload(main_gpu);
  2877. }
  2878. // assign the repeating layers
  2879. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  2880. model.buft_layer[i] = {
  2881. split_buft,
  2882. llama_default_buffer_type_offload(main_gpu)
  2883. };
  2884. }
  2885. // assign the output layer
  2886. if (n_gpu_layers > n_layer) {
  2887. model.buft_output = {
  2888. split_buft,
  2889. llama_default_buffer_type_offload(main_gpu)
  2890. };
  2891. } else {
  2892. model.buft_output = llama_default_buffer_type_cpu(true);
  2893. }
  2894. }
  2895. // count used buffer types
  2896. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  2897. buft_layer_count[model.buft_input.buft]++;
  2898. buft_layer_count[model.buft_input.buft_matrix]++;
  2899. buft_layer_count[model.buft_output.buft]++;
  2900. buft_layer_count[model.buft_output.buft_matrix]++;
  2901. for (int64_t i = 0; i < n_layer; ++i) {
  2902. buft_layer_count[model.buft_layer[i].buft]++;
  2903. buft_layer_count[model.buft_layer[i].buft_matrix]++;
  2904. }
  2905. // create one context per buffer type
  2906. size_t ctx_size = ggml_tensor_overhead()*ml.n_tensors;
  2907. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  2908. for (auto & it : buft_layer_count) {
  2909. struct ggml_init_params params = {
  2910. /*.mem_size =*/ ctx_size,
  2911. /*.mem_buffer =*/ NULL,
  2912. /*.no_alloc =*/ true,
  2913. };
  2914. ggml_context * ctx = ggml_init(params);
  2915. if (!ctx) {
  2916. throw std::runtime_error(format("failed to create context"));
  2917. }
  2918. ctx_map[it.first] = ctx;
  2919. model.ctxs.push_back(ctx);
  2920. }
  2921. LLAMA_LOG_INFO("%s: ggml ctx size = %7.2f MiB\n", __func__, model.ctxs.size()*ctx_size/1024.0/1024.0);
  2922. // create tensors for the weights
  2923. {
  2924. const int64_t n_embd = hparams.n_embd;
  2925. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  2926. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  2927. const int64_t n_embd_gqa = n_embd_v_gqa;
  2928. const int64_t n_vocab = hparams.n_vocab;
  2929. const int64_t n_ff = hparams.n_ff;
  2930. GGML_ASSERT(n_embd_gqa == n_embd_k_gqa);
  2931. ggml_context * ctx_input = ctx_map.at(model.buft_input.buft);
  2932. ggml_context * ctx_output = ctx_map.at(model.buft_output.buft);
  2933. ggml_context * ctx_output_split = ctx_map.at(model.buft_output.buft_matrix);
  2934. auto ctx_for_layer = [&](int i) { return ctx_map.at(model.buft_layer[i].buft); };
  2935. auto ctx_for_layer_split = [&](int i) { return ctx_map.at(model.buft_layer[i].buft_matrix); };
  2936. model.layers.resize(n_layer);
  2937. const auto tn = LLM_TN(model.arch);
  2938. switch (model.arch) {
  2939. case LLM_ARCH_LLAMA:
  2940. case LLM_ARCH_REFACT:
  2941. {
  2942. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  2943. // output
  2944. {
  2945. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  2946. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  2947. }
  2948. for (int i = 0; i < n_layer; ++i) {
  2949. ggml_context * ctx_layer = ctx_for_layer(i);
  2950. ggml_context * ctx_split = ctx_for_layer_split(i);
  2951. auto & layer = model.layers[i];
  2952. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  2953. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  2954. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  2955. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  2956. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  2957. // optional bias tensors
  2958. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, false);
  2959. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, false);
  2960. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, false);
  2961. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, false);
  2962. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  2963. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd}, false);
  2964. if (layer.ffn_gate_inp == nullptr) {
  2965. GGML_ASSERT(hparams.n_expert == 0);
  2966. GGML_ASSERT(hparams.n_expert_used == 0);
  2967. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  2968. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  2969. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  2970. } else {
  2971. GGML_ASSERT(hparams.n_expert > 0);
  2972. GGML_ASSERT(hparams.n_expert_used > 0);
  2973. // MoE branch
  2974. for (uint32_t x = 0; x < hparams.n_expert; ++x) {
  2975. layer.ffn_gate_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, x), {n_embd, n_ff});
  2976. layer.ffn_down_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, x), { n_ff, n_embd});
  2977. layer.ffn_up_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, x), {n_embd, n_ff});
  2978. }
  2979. }
  2980. }
  2981. } break;
  2982. case LLM_ARCH_BAICHUAN:
  2983. {
  2984. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  2985. {
  2986. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  2987. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  2988. }
  2989. for (int i = 0; i < n_layer; ++i) {
  2990. ggml_context * ctx_layer = ctx_for_layer(i);
  2991. ggml_context * ctx_split = ctx_for_layer_split(i);
  2992. auto & layer = model.layers[i];
  2993. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  2994. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  2995. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  2996. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  2997. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  2998. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  2999. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3000. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3001. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3002. }
  3003. } break;
  3004. case LLM_ARCH_FALCON:
  3005. {
  3006. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3007. // output
  3008. {
  3009. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3010. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3011. if (gguf_find_tensor(ml.ctx_gguf, tn(LLM_TENSOR_OUTPUT, "weight").c_str()) >= 0) {
  3012. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3013. } else {
  3014. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}); // needs to be on GPU
  3015. ml.n_created--; // artificial tensor
  3016. }
  3017. }
  3018. for (int i = 0; i < n_layer; ++i) {
  3019. ggml_context * ctx_layer = ctx_for_layer(i);
  3020. ggml_context * ctx_split = ctx_for_layer_split(i);
  3021. auto & layer = model.layers[i];
  3022. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3023. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3024. if (gguf_find_tensor(ml.ctx_gguf, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i).c_str()) >= 0) {
  3025. layer.attn_norm_2 = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i), {n_embd});
  3026. layer.attn_norm_2_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "bias", i), {n_embd});
  3027. }
  3028. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3029. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3030. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3031. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3032. }
  3033. } break;
  3034. case LLM_ARCH_STARCODER:
  3035. {
  3036. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3037. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3038. // output
  3039. {
  3040. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3041. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3042. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3043. }
  3044. for (int i = 0; i < n_layer; ++i) {
  3045. ggml_context * ctx_layer = ctx_for_layer(i);
  3046. ggml_context * ctx_split = ctx_for_layer_split(i);
  3047. auto & layer = model.layers[i];
  3048. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3049. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3050. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3051. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3052. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3053. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3054. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3055. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3056. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3057. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3058. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3059. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3060. }
  3061. } break;
  3062. case LLM_ARCH_PERSIMMON:
  3063. {
  3064. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3065. {
  3066. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3067. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3068. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3069. }
  3070. for (int i = 0; i < n_layer; ++i) {
  3071. ggml_context * ctx_layer = ctx_for_layer(i);
  3072. ggml_context * ctx_split = ctx_for_layer_split(i);
  3073. auto & layer = model.layers[i];
  3074. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3075. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3076. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3077. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3078. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3079. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3080. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3081. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3082. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3083. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3084. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3085. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3086. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {64});
  3087. layer.attn_q_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "bias", i), {64});
  3088. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {64});
  3089. layer.attn_k_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "bias", i), {64});
  3090. }
  3091. } break;
  3092. case LLM_ARCH_BLOOM:
  3093. {
  3094. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3095. model.tok_norm = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  3096. model.tok_norm_b = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  3097. // output
  3098. {
  3099. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3100. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3101. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3102. }
  3103. for (int i = 0; i < n_layer; ++i) {
  3104. ggml_context * ctx_layer = ctx_for_layer(i);
  3105. ggml_context * ctx_split = ctx_for_layer_split(i);
  3106. auto & layer = model.layers[i];
  3107. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3108. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3109. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3110. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3111. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3112. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3113. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3114. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3115. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3116. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3117. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3118. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3119. }
  3120. } break;
  3121. case LLM_ARCH_MPT:
  3122. {
  3123. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3124. // output
  3125. {
  3126. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3127. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3128. }
  3129. for (int i = 0; i < n_layer; ++i) {
  3130. ggml_context * ctx_layer = ctx_for_layer(i);
  3131. ggml_context * ctx_split = ctx_for_layer_split(i);
  3132. auto & layer = model.layers[i];
  3133. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3134. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3135. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3136. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3137. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3138. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3139. // AWQ ScaleActivation layer
  3140. layer.ffn_act = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_ACT, "scales", i), {n_ff}, false);
  3141. }
  3142. } break;
  3143. case LLM_ARCH_STABLELM:
  3144. {
  3145. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3146. // output
  3147. {
  3148. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3149. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3150. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3151. }
  3152. for (int i = 0; i < n_layer; ++i) {
  3153. ggml_context * ctx_layer = ctx_for_layer(i);
  3154. ggml_context * ctx_split = ctx_for_layer_split(i);
  3155. auto & layer = model.layers[i];
  3156. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3157. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3158. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3159. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3160. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3161. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3162. // optional bias tensors, present in Stable LM 2 1.6B
  3163. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, false);
  3164. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, false);
  3165. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, false);
  3166. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3167. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3168. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3169. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3170. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3171. }
  3172. } break;
  3173. case LLM_ARCH_QWEN:
  3174. {
  3175. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3176. // output
  3177. {
  3178. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3179. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3180. }
  3181. for (int i = 0; i < n_layer; ++i) {
  3182. ggml_context * ctx_layer = ctx_for_layer(i);
  3183. ggml_context * ctx_split = ctx_for_layer_split(i);
  3184. auto & layer = model.layers[i];
  3185. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3186. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd*3});
  3187. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd*3});
  3188. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3189. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3190. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff/2});
  3191. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff/2, n_embd});
  3192. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff/2});
  3193. }
  3194. } break;
  3195. case LLM_ARCH_QWEN2:
  3196. {
  3197. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3198. // output
  3199. {
  3200. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3201. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3202. }
  3203. for (int i = 0; i < n_layer; ++i) {
  3204. ggml_context * ctx_layer = ctx_for_layer(i);
  3205. ggml_context * ctx_split = ctx_for_layer_split(i);
  3206. auto & layer = model.layers[i];
  3207. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3208. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3209. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3210. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3211. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3212. // optional bias tensors
  3213. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  3214. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  3215. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  3216. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3217. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3218. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3219. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3220. }
  3221. } break;
  3222. case LLM_ARCH_PHI2:
  3223. {
  3224. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3225. // output
  3226. {
  3227. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3228. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3229. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3230. model.output_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT, "bias"), {n_vocab});
  3231. }
  3232. for (int i = 0; i < n_layer; ++i) {
  3233. ggml_context * ctx_layer = ctx_for_layer(i);
  3234. ggml_context * ctx_split = ctx_for_layer_split(i);
  3235. auto & layer = model.layers[i];
  3236. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3237. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3238. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, false);
  3239. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, false);
  3240. if (layer.wqkv == nullptr) {
  3241. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3242. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  3243. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3244. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  3245. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3246. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  3247. }
  3248. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3249. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3250. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3251. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3252. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3253. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3254. }
  3255. } break;
  3256. case LLM_ARCH_PLAMO:
  3257. {
  3258. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3259. // output
  3260. {
  3261. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3262. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3263. }
  3264. for (int i = 0; i < n_layer; ++i) {
  3265. ggml_context * ctx_layer = ctx_for_layer(i);
  3266. ggml_context * ctx_split = ctx_for_layer_split(i);
  3267. auto & layer = model.layers[i];
  3268. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3269. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3270. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3271. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3272. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3273. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3274. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3275. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3276. }
  3277. } break;
  3278. case LLM_ARCH_GPT2:
  3279. {
  3280. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3281. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3282. // output
  3283. {
  3284. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3285. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3286. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3287. }
  3288. for (int i = 0; i < n_layer; ++i) {
  3289. ggml_context * ctx_layer = ctx_for_layer(i);
  3290. ggml_context * ctx_split = ctx_for_layer_split(i);
  3291. auto & layer = model.layers[i];
  3292. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3293. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3294. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3295. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3296. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3297. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3298. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3299. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3300. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3301. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3302. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3303. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3304. }
  3305. } break;
  3306. case LLM_ARCH_CODESHELL:
  3307. {
  3308. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3309. // output
  3310. {
  3311. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3312. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3313. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3314. }
  3315. for (int i = 0; i < n_layer; ++i) {
  3316. ggml_context * ctx_layer = ctx_for_layer(i);
  3317. ggml_context * ctx_split = ctx_for_layer_split(i);
  3318. auto & layer = model.layers[i];
  3319. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3320. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3321. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3322. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3323. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3324. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3325. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3326. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3327. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3328. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3329. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3330. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3331. }
  3332. } break;
  3333. default:
  3334. throw std::runtime_error("unknown architecture");
  3335. }
  3336. }
  3337. ml.done_getting_tensors();
  3338. ml.init_mapping(true, use_mlock ? &model.mlock_mmap : nullptr);
  3339. // create the backend buffers
  3340. std::vector<std::pair<ggml_context *, ggml_backend_buffer_t>> ctx_bufs;
  3341. for (auto & it : ctx_map) {
  3342. ggml_backend_buffer_type_t buft = it.first;
  3343. ggml_context * ctx = it.second;
  3344. ggml_backend_buffer_t buf = nullptr;
  3345. // only the mmap region containing the tensors in the model is mapped to the backend buffer
  3346. // 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
  3347. // this allows using partial offloading when the model size exceeds the metal buffer size, but not the RAM size
  3348. if (ml.use_mmap && buft == llama_default_buffer_type_cpu(true)) {
  3349. size_t first, last;
  3350. ml.get_mapping_range(&first, &last, ctx);
  3351. buf = ggml_backend_cpu_buffer_from_ptr((char *) ml.mapping->addr + first, last - first);
  3352. }
  3353. #ifdef GGML_USE_METAL
  3354. else if (ml.use_mmap && buft == ggml_backend_metal_buffer_type()) {
  3355. const size_t max_size = ggml_get_max_tensor_size(ctx);
  3356. size_t first, last;
  3357. ml.get_mapping_range(&first, &last, ctx);
  3358. buf = ggml_backend_metal_buffer_from_ptr((char *) ml.mapping->addr + first, last - first, max_size);
  3359. }
  3360. #endif
  3361. else {
  3362. buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  3363. if (buf != nullptr && use_mlock && ggml_backend_buffer_is_host(buf)) {
  3364. model.mlock_bufs.emplace_back(new llama_mlock);
  3365. auto & mlock_buf = model.mlock_bufs.back();
  3366. mlock_buf->init (ggml_backend_buffer_get_base(buf));
  3367. mlock_buf->grow_to(ggml_backend_buffer_get_size(buf));
  3368. }
  3369. }
  3370. if (buf == nullptr) {
  3371. throw std::runtime_error("failed to allocate buffer");
  3372. }
  3373. // indicate that this buffer contains weights
  3374. // 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
  3375. ggml_backend_buffer_set_usage(buf, GGML_BACKEND_BUFFER_USAGE_WEIGHTS);
  3376. model.bufs.push_back(buf);
  3377. ctx_bufs.emplace_back(ctx, buf);
  3378. }
  3379. // print memory requirements
  3380. {
  3381. const int n_gpu = std::min(n_gpu_layers, int(hparams.n_layer));
  3382. LLAMA_LOG_INFO("%s: offloading %d repeating layers to GPU\n", __func__, n_gpu);
  3383. if (n_gpu_layers > (int) hparams.n_layer) {
  3384. LLAMA_LOG_INFO("%s: offloading non-repeating layers to GPU\n", __func__);
  3385. }
  3386. const int max_backend_supported_layers = hparams.n_layer + 1;
  3387. const int max_offloadable_layers = hparams.n_layer + 1;
  3388. LLAMA_LOG_INFO("%s: offloaded %d/%d layers to GPU\n", __func__, std::min(n_gpu_layers, max_offloadable_layers), max_backend_supported_layers);
  3389. for (ggml_backend_buffer_t buf : model.bufs) {
  3390. 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);
  3391. }
  3392. }
  3393. // populate tensors_by_name
  3394. for (ggml_context * ctx : model.ctxs) {
  3395. for (auto * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  3396. model.tensors_by_name.emplace_back(ggml_get_name(cur), cur);
  3397. }
  3398. }
  3399. // load tensor data
  3400. for (auto & it : ctx_bufs) {
  3401. ggml_context * ctx = it.first;
  3402. ggml_backend_buffer_t buf = it.second;
  3403. if (!ml.load_all_data(ctx, progress_callback, progress_callback_user_data, buf, use_mlock ? &model.mlock_mmap : NULL)) {
  3404. return false;
  3405. }
  3406. }
  3407. model.mapping = std::move(ml.mapping);
  3408. // loading time will be recalculate after the first eval, so
  3409. // we take page faults deferred by mmap() into consideration
  3410. model.t_load_us = ggml_time_us() - model.t_start_us;
  3411. return true;
  3412. }
  3413. // Returns 0 on success, -1 on error, and -2 on cancellation via llama_progress_callback
  3414. static int llama_model_load(const std::string & fname, llama_model & model, const llama_model_params & params) {
  3415. try {
  3416. llama_model_loader ml(fname, params.use_mmap, params.kv_overrides);
  3417. model.hparams.vocab_only = params.vocab_only;
  3418. llm_load_arch (ml, model);
  3419. llm_load_hparams(ml, model);
  3420. llm_load_vocab (ml, model);
  3421. llm_load_print_meta(ml, model);
  3422. if (model.hparams.n_vocab != model.vocab.id_to_token.size()) {
  3423. throw std::runtime_error("vocab size mismatch");
  3424. }
  3425. if (params.vocab_only) {
  3426. LLAMA_LOG_INFO("%s: vocab only - skipping tensors\n", __func__);
  3427. return 0;
  3428. }
  3429. if (!llm_load_tensors(
  3430. ml, model, params.n_gpu_layers, params.split_mode, params.main_gpu, params.tensor_split, params.use_mlock,
  3431. params.progress_callback, params.progress_callback_user_data
  3432. )) {
  3433. return -2;
  3434. }
  3435. } catch (const std::exception & err) {
  3436. LLAMA_LOG_ERROR("%s: error loading model: %s\n", __func__, err.what());
  3437. return -1;
  3438. }
  3439. return 0;
  3440. }
  3441. //
  3442. // llm_build
  3443. //
  3444. using llm_build_cb = std::function<void(struct ggml_tensor * cur, const char * name, int nl)>;
  3445. enum llm_rope_type {
  3446. LLM_ROPE,
  3447. LLM_ROPE_NEOX,
  3448. LLM_ROPE_GLM,
  3449. };
  3450. enum llm_ffn_op_type {
  3451. LLM_FFN_SILU,
  3452. LLM_FFN_GELU,
  3453. LLM_FFN_RELU,
  3454. LLM_FFN_RELU_SQR,
  3455. };
  3456. enum llm_ffn_gate_type {
  3457. LLM_FFN_SEQ,
  3458. LLM_FFN_PAR, // ffn_gate is parallel to ffn_up
  3459. };
  3460. enum llm_norm_type {
  3461. LLM_NORM,
  3462. LLM_NORM_RMS,
  3463. };
  3464. static struct ggml_tensor * llm_build_inp_embd(
  3465. struct ggml_context * ctx,
  3466. const llama_hparams & hparams,
  3467. const llama_batch & batch,
  3468. struct ggml_tensor * tok_embd,
  3469. struct ggml_tensor * inp_tokens,
  3470. struct ggml_tensor * inp_embd,
  3471. const llm_build_cb & cb) {
  3472. const int64_t n_embd = hparams.n_embd;
  3473. struct ggml_tensor * inpL;
  3474. if (batch.token) {
  3475. struct ggml_tensor * inp_tokens_v = ggml_view_1d(ctx, inp_tokens, batch.n_tokens, 0);
  3476. cb(inp_tokens, "inp_tokens", -1);
  3477. inpL = ggml_get_rows(ctx, tok_embd, inp_tokens_v);
  3478. } else {
  3479. #ifdef GGML_USE_MPI
  3480. GGML_ASSERT(false && "not implemented");
  3481. #endif
  3482. inpL = ggml_view_2d(ctx, inp_embd, n_embd, batch.n_tokens, inp_embd->nb[1], 0);
  3483. }
  3484. return inpL;
  3485. }
  3486. // Persimmon: n_rot = n_embd_head_k/2
  3487. // Other: n_rot = n_embd_head_k
  3488. static void llm_build_k_shift(
  3489. struct ggml_context * ctx,
  3490. const llama_hparams & hparams,
  3491. const llama_cparams & cparams,
  3492. const llama_kv_cache & kv,
  3493. struct ggml_cgraph * graph,
  3494. struct ggml_tensor * K_shift,
  3495. llm_rope_type type,
  3496. int64_t n_ctx,
  3497. float freq_base,
  3498. float freq_scale,
  3499. const llm_build_cb & cb) {
  3500. const int64_t n_layer = hparams.n_layer;
  3501. const int64_t n_head_kv = hparams.n_head_kv;
  3502. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  3503. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3504. const int32_t n_rot = hparams.n_rot;
  3505. const int32_t n_orig_ctx = cparams.n_yarn_orig_ctx;
  3506. const float ext_factor = cparams.yarn_ext_factor;
  3507. const float attn_factor = cparams.yarn_attn_factor;
  3508. const float beta_fast = cparams.yarn_beta_fast;
  3509. const float beta_slow = cparams.yarn_beta_slow;
  3510. int rope_type = 0;
  3511. switch (type) {
  3512. case LLM_ROPE: rope_type = 0; break;
  3513. case LLM_ROPE_NEOX: rope_type = 2; break;
  3514. case LLM_ROPE_GLM: rope_type = 4; break;
  3515. }
  3516. for (int il = 0; il < n_layer; ++il) {
  3517. struct ggml_tensor * tmp =
  3518. // we rotate only the first n_rot dimensions
  3519. ggml_rope_custom_inplace(ctx,
  3520. ggml_view_3d(ctx, kv.k_l[il],
  3521. n_embd_head_k, n_head_kv, n_ctx,
  3522. ggml_row_size(kv.k_l[il]->type, n_embd_head_k),
  3523. ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa),
  3524. 0),
  3525. K_shift, n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  3526. ext_factor, attn_factor, beta_fast, beta_slow);
  3527. cb(tmp, "K_shifted", il);
  3528. ggml_build_forward_expand(graph, tmp);
  3529. }
  3530. }
  3531. static void llm_build_kv_store(
  3532. struct ggml_context * ctx,
  3533. const llama_hparams & hparams,
  3534. const llama_kv_cache & kv,
  3535. struct ggml_cgraph * graph,
  3536. struct ggml_tensor * k_cur,
  3537. struct ggml_tensor * v_cur,
  3538. int64_t n_ctx,
  3539. int32_t n_tokens,
  3540. int32_t kv_head,
  3541. const llm_build_cb & cb,
  3542. int64_t il) {
  3543. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3544. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  3545. // compute the transposed [n_tokens, n_embd] V matrix
  3546. struct ggml_tensor * v_cur_t = ggml_transpose(ctx, ggml_reshape_2d(ctx, v_cur, n_embd_v_gqa, n_tokens));
  3547. //struct ggml_tensor * v_cur_t = ggml_transpose(ctx, v_cur); // TODO: reshape above is likely not needed
  3548. cb(v_cur_t, "v_cur_t", il);
  3549. struct ggml_tensor * k_cache_view = ggml_view_1d(ctx, kv.k_l[il], n_tokens*n_embd_k_gqa,
  3550. (ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa))*kv_head);
  3551. cb(k_cache_view, "k_cache_view", il);
  3552. struct ggml_tensor * v_cache_view = ggml_view_2d(ctx, kv.v_l[il], n_tokens, n_embd_v_gqa,
  3553. ( n_ctx)*ggml_element_size(kv.v_l[il]),
  3554. (kv_head)*ggml_element_size(kv.v_l[il]));
  3555. cb(v_cache_view, "v_cache_view", il);
  3556. // important: storing RoPE-ed version of K in the KV cache!
  3557. ggml_build_forward_expand(graph, ggml_cpy(ctx, k_cur, k_cache_view));
  3558. ggml_build_forward_expand(graph, ggml_cpy(ctx, v_cur_t, v_cache_view));
  3559. }
  3560. static struct ggml_tensor * llm_build_norm(
  3561. struct ggml_context * ctx,
  3562. struct ggml_tensor * cur,
  3563. const llama_hparams & hparams,
  3564. struct ggml_tensor * mw,
  3565. struct ggml_tensor * mb,
  3566. llm_norm_type type,
  3567. const llm_build_cb & cb,
  3568. int il) {
  3569. switch (type) {
  3570. case LLM_NORM: cur = ggml_norm (ctx, cur, hparams.f_norm_eps); break;
  3571. case LLM_NORM_RMS: cur = ggml_rms_norm(ctx, cur, hparams.f_norm_rms_eps); break;
  3572. }
  3573. if (mw || mb) {
  3574. cb(cur, "norm", il);
  3575. }
  3576. if (mw) {
  3577. cur = ggml_mul(ctx, cur, mw);
  3578. if (mb) {
  3579. cb(cur, "norm_w", il);
  3580. }
  3581. }
  3582. if (mb) {
  3583. cur = ggml_add(ctx, cur, mb);
  3584. }
  3585. return cur;
  3586. }
  3587. static struct ggml_tensor * llm_build_ffn(
  3588. struct ggml_context * ctx,
  3589. struct ggml_tensor * cur,
  3590. struct ggml_tensor * up,
  3591. struct ggml_tensor * up_b,
  3592. struct ggml_tensor * gate,
  3593. struct ggml_tensor * gate_b,
  3594. struct ggml_tensor * down,
  3595. struct ggml_tensor * down_b,
  3596. struct ggml_tensor * act_scales,
  3597. llm_ffn_op_type type_op,
  3598. llm_ffn_gate_type type_gate,
  3599. const llm_build_cb & cb,
  3600. int il) {
  3601. struct ggml_tensor * tmp = ggml_mul_mat(ctx, up, cur);
  3602. cb(tmp, "ffn_up", il);
  3603. if (up_b) {
  3604. tmp = ggml_add(ctx, tmp, up_b);
  3605. cb(tmp, "ffn_up_b", il);
  3606. }
  3607. if (gate) {
  3608. switch (type_gate) {
  3609. case LLM_FFN_SEQ:
  3610. {
  3611. cur = ggml_mul_mat(ctx, gate, tmp);
  3612. cb(cur, "ffn_gate", il);
  3613. } break;
  3614. case LLM_FFN_PAR:
  3615. {
  3616. cur = ggml_mul_mat(ctx, gate, cur);
  3617. cb(cur, "ffn_gate", il);
  3618. } break;
  3619. }
  3620. if (gate_b) {
  3621. cur = ggml_add(ctx, cur, gate_b);
  3622. cb(cur, "ffn_gate_b", il);
  3623. }
  3624. } else {
  3625. cur = tmp;
  3626. }
  3627. switch (type_op) {
  3628. case LLM_FFN_SILU:
  3629. {
  3630. cur = ggml_silu(ctx, cur);
  3631. cb(cur, "ffn_silu", il);
  3632. } break;
  3633. case LLM_FFN_GELU:
  3634. {
  3635. cur = ggml_gelu(ctx, cur);
  3636. cb(cur, "ffn_gelu", il);
  3637. if (act_scales != NULL) {
  3638. cur = ggml_div(ctx, cur, act_scales);
  3639. cb(cur, "ffn_act", il);
  3640. }
  3641. } break;
  3642. case LLM_FFN_RELU:
  3643. {
  3644. cur = ggml_relu(ctx, cur);
  3645. cb(cur, "ffn_relu", il);
  3646. } break;
  3647. case LLM_FFN_RELU_SQR:
  3648. {
  3649. cur = ggml_relu(ctx, cur);
  3650. cb(cur, "ffn_relu", il);
  3651. cur = ggml_sqr(ctx, cur);
  3652. cb(cur, "ffn_sqr(relu)", il);
  3653. } break;
  3654. }
  3655. if (type_gate == LLM_FFN_PAR) {
  3656. cur = ggml_mul(ctx, cur, tmp);
  3657. cb(cur, "ffn_gate_par", il);
  3658. }
  3659. cur = ggml_mul_mat(ctx, down, cur);
  3660. if (down_b) {
  3661. cb(cur, "ffn_down", il);
  3662. }
  3663. if (down_b) {
  3664. cur = ggml_add(ctx, cur, down_b);
  3665. }
  3666. return cur;
  3667. }
  3668. // if max_alibi_bias > 0 then apply ALiBi
  3669. static struct ggml_tensor * llm_build_kqv(
  3670. struct ggml_context * ctx,
  3671. const llama_model & model,
  3672. const llama_hparams & hparams,
  3673. const llama_kv_cache & kv,
  3674. struct ggml_cgraph * graph,
  3675. struct ggml_tensor * wo,
  3676. struct ggml_tensor * wo_b,
  3677. struct ggml_tensor * q_cur,
  3678. struct ggml_tensor * kq_mask,
  3679. int64_t n_ctx,
  3680. int32_t n_tokens,
  3681. int32_t n_kv,
  3682. float max_alibi_bias,
  3683. float kq_scale,
  3684. const llm_build_cb & cb,
  3685. int il) {
  3686. const int64_t n_head = hparams.n_head;
  3687. const int64_t n_head_kv = hparams.n_head_kv;
  3688. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  3689. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3690. const int64_t n_embd_head_v = hparams.n_embd_head_v;
  3691. struct ggml_tensor * q = ggml_permute(ctx, q_cur, 0, 2, 1, 3);
  3692. cb(q, "q", il);
  3693. struct ggml_tensor * k =
  3694. ggml_view_3d(ctx, kv.k_l[il],
  3695. n_embd_head_k, n_kv, n_head_kv,
  3696. ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa),
  3697. ggml_row_size(kv.k_l[il]->type, n_embd_head_k),
  3698. 0);
  3699. cb(k, "k", il);
  3700. struct ggml_tensor * kq = ggml_mul_mat(ctx, k, q);
  3701. cb(kq, "kq", il);
  3702. if (model.arch == LLM_ARCH_PHI2) {
  3703. // for this arch, we need to perform the KQ multiplication with F32 precision, otherwise we get NaNs
  3704. // ref: https://github.com/ggerganov/llama.cpp/pull/4490#issuecomment-1859055847
  3705. ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  3706. }
  3707. if (max_alibi_bias > 0.0f) {
  3708. // temporary branch until we figure out how to handle ggml_alibi through ggml_add
  3709. kq = ggml_scale(ctx, kq, kq_scale);
  3710. cb(kq, "kq_scaled", il);
  3711. if (max_alibi_bias > 0.0f) {
  3712. // TODO: n_head or n_head_kv
  3713. // TODO: K-shift is likely not working
  3714. // TODO: change to ggml_add
  3715. kq = ggml_alibi(ctx, kq, /*n_past*/ 0, n_head, max_alibi_bias);
  3716. cb(kq, "kq_scaled_alibi", il);
  3717. }
  3718. kq = ggml_add(ctx, kq, kq_mask);
  3719. cb(kq, "kq_masked", il);
  3720. kq = ggml_soft_max(ctx, kq);
  3721. cb(kq, "kq_soft_max", il);
  3722. } else {
  3723. kq = ggml_soft_max_ext(ctx, kq, kq_mask, kq_scale);
  3724. cb(kq, "kq_soft_max_ext", il);
  3725. }
  3726. // split cached v into n_head heads
  3727. struct ggml_tensor * v =
  3728. ggml_view_3d(ctx, kv.v_l[il],
  3729. n_kv, n_embd_head_v, n_head_kv,
  3730. ggml_element_size(kv.v_l[il])*n_ctx,
  3731. ggml_element_size(kv.v_l[il])*n_ctx*n_embd_head_v,
  3732. 0);
  3733. cb(v, "v", il);
  3734. struct ggml_tensor * kqv = ggml_mul_mat(ctx, v, kq);
  3735. cb(kqv, "kqv", il);
  3736. struct ggml_tensor * kqv_merged = ggml_permute(ctx, kqv, 0, 2, 1, 3);
  3737. cb(kqv_merged, "kqv_merged", il);
  3738. struct ggml_tensor * cur = ggml_cont_2d(ctx, kqv_merged, n_embd_head_k*n_head, n_tokens);
  3739. cb(cur, "kqv_merged_cont", il);
  3740. ggml_build_forward_expand(graph, cur);
  3741. cur = ggml_mul_mat(ctx, wo, cur);
  3742. if (wo_b) {
  3743. cb(cur, "kqv_wo", il);
  3744. }
  3745. if (wo_b) {
  3746. cur = ggml_add(ctx, cur, wo_b);
  3747. }
  3748. return cur;
  3749. }
  3750. static struct ggml_tensor * llm_build_kv(
  3751. struct ggml_context * ctx,
  3752. const llama_model & model,
  3753. const llama_hparams & hparams,
  3754. const llama_kv_cache & kv,
  3755. struct ggml_cgraph * graph,
  3756. struct ggml_tensor * wo,
  3757. struct ggml_tensor * wo_b,
  3758. struct ggml_tensor * k_cur,
  3759. struct ggml_tensor * v_cur,
  3760. struct ggml_tensor * q_cur,
  3761. struct ggml_tensor * kq_mask,
  3762. int64_t n_ctx,
  3763. int32_t n_tokens,
  3764. int32_t kv_head,
  3765. int32_t n_kv,
  3766. float max_alibi_bias,
  3767. float kq_scale,
  3768. const llm_build_cb & cb,
  3769. int il) {
  3770. // these nodes are added to the graph together so that they are not reordered
  3771. // by doing so, the number of splits in the graph is reduced
  3772. ggml_build_forward_expand(graph, q_cur);
  3773. ggml_build_forward_expand(graph, k_cur);
  3774. ggml_build_forward_expand(graph, v_cur);
  3775. llm_build_kv_store(ctx, hparams, kv, graph, k_cur, v_cur, n_ctx, n_tokens, kv_head, cb, il);
  3776. struct ggml_tensor * cur;
  3777. cur = llm_build_kqv(ctx, model, hparams, kv, graph,
  3778. wo, wo_b,
  3779. q_cur, kq_mask, n_ctx, n_tokens, n_kv, max_alibi_bias, kq_scale, cb, il);
  3780. cb(cur, "kqv_out", il);
  3781. return cur;
  3782. }
  3783. struct llm_build_context {
  3784. const llama_model & model;
  3785. const llama_context & lctx;
  3786. const llama_hparams & hparams;
  3787. const llama_cparams & cparams;
  3788. const llama_batch & batch;
  3789. const llama_kv_cache & kv_self;
  3790. const int64_t n_embd;
  3791. const int64_t n_layer;
  3792. const int64_t n_ctx; // user-specified context size (can be different from n_ctx_train)
  3793. const int64_t n_head;
  3794. const int64_t n_head_kv;
  3795. const int64_t n_embd_head_k;
  3796. const int64_t n_embd_k_gqa;
  3797. const int64_t n_embd_head_v;
  3798. const int64_t n_embd_v_gqa;
  3799. const int64_t n_expert;
  3800. const int64_t n_expert_used;
  3801. const float freq_base;
  3802. const float freq_scale;
  3803. const float ext_factor;
  3804. const float attn_factor;
  3805. const float beta_fast;
  3806. const float beta_slow;
  3807. const float norm_eps;
  3808. const float norm_rms_eps;
  3809. const int32_t n_tokens;
  3810. const int32_t n_kv; // size of KV cache to consider (n_kv <= n_ctx)
  3811. const int32_t kv_head; // index of where we store new KV data in the cache
  3812. const int32_t n_orig_ctx;
  3813. const bool do_rope_shift;
  3814. const llm_build_cb & cb;
  3815. std::vector<uint8_t> & buf_compute_meta;
  3816. struct ggml_context * ctx0 = nullptr;
  3817. // TODO: consider making the entire interface noexcept
  3818. llm_build_context(
  3819. llama_context & lctx,
  3820. const llama_batch & batch,
  3821. const llm_build_cb & cb,
  3822. bool worst_case) :
  3823. model (lctx.model),
  3824. lctx (lctx),
  3825. hparams (model.hparams),
  3826. cparams (lctx.cparams),
  3827. batch (batch),
  3828. kv_self (lctx.kv_self),
  3829. n_embd (hparams.n_embd),
  3830. n_layer (hparams.n_layer),
  3831. n_ctx (cparams.n_ctx),
  3832. n_head (hparams.n_head),
  3833. n_head_kv (hparams.n_head_kv),
  3834. n_embd_head_k (hparams.n_embd_head_k),
  3835. n_embd_k_gqa (hparams.n_embd_k_gqa()),
  3836. n_embd_head_v (hparams.n_embd_head_v),
  3837. n_embd_v_gqa (hparams.n_embd_v_gqa()),
  3838. n_expert (hparams.n_expert),
  3839. n_expert_used (hparams.n_expert_used),
  3840. freq_base (cparams.rope_freq_base),
  3841. freq_scale (cparams.rope_freq_scale),
  3842. ext_factor (cparams.yarn_ext_factor),
  3843. attn_factor (cparams.yarn_attn_factor),
  3844. beta_fast (cparams.yarn_beta_fast),
  3845. beta_slow (cparams.yarn_beta_slow),
  3846. norm_eps (hparams.f_norm_eps),
  3847. norm_rms_eps (hparams.f_norm_rms_eps),
  3848. n_tokens (batch.n_tokens),
  3849. n_kv (worst_case ? n_ctx : kv_self.n),
  3850. kv_head (worst_case ? n_ctx - n_tokens : kv_self.head),
  3851. n_orig_ctx (cparams.n_yarn_orig_ctx),
  3852. do_rope_shift (worst_case || kv_self.has_shift),
  3853. cb (cb),
  3854. buf_compute_meta (lctx.buf_compute_meta) {
  3855. // all initializations should be done in init()
  3856. }
  3857. void init() {
  3858. struct ggml_init_params params = {
  3859. /*.mem_size =*/ buf_compute_meta.size(),
  3860. /*.mem_buffer =*/ buf_compute_meta.data(),
  3861. /*.no_alloc =*/ true,
  3862. };
  3863. ctx0 = ggml_init(params);
  3864. }
  3865. void free() {
  3866. if (ctx0) {
  3867. ggml_free(ctx0);
  3868. ctx0 = nullptr;
  3869. }
  3870. }
  3871. struct ggml_cgraph * build_llama() {
  3872. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  3873. const int64_t n_embd_head = hparams.n_embd_head_v;
  3874. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  3875. GGML_ASSERT(n_embd_head == hparams.n_rot);
  3876. struct ggml_tensor * cur;
  3877. struct ggml_tensor * inpL;
  3878. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  3879. cb(inpL, "inp_embd", -1);
  3880. // inp_pos - contains the positions
  3881. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  3882. cb(inp_pos, "inp_pos", -1);
  3883. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  3884. 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);
  3885. cb(KQ_mask, "KQ_mask", -1);
  3886. // shift the entire K-cache if needed
  3887. if (do_rope_shift) {
  3888. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  3889. }
  3890. for (int il = 0; il < n_layer; ++il) {
  3891. struct ggml_tensor * inpSA = inpL;
  3892. // norm
  3893. cur = llm_build_norm(ctx0, inpL, hparams,
  3894. model.layers[il].attn_norm, NULL,
  3895. LLM_NORM_RMS, cb, il);
  3896. cb(cur, "attn_norm", il);
  3897. // self-attention
  3898. {
  3899. // compute Q and K and RoPE them
  3900. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  3901. cb(Qcur, "Qcur", il);
  3902. if (model.layers[il].bq) {
  3903. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  3904. cb(Qcur, "Qcur", il);
  3905. }
  3906. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  3907. cb(Kcur, "Kcur", il);
  3908. if (model.layers[il].bk) {
  3909. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  3910. cb(Kcur, "Kcur", il);
  3911. }
  3912. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  3913. cb(Vcur, "Vcur", il);
  3914. if (model.layers[il].bv) {
  3915. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  3916. cb(Vcur, "Vcur", il);
  3917. }
  3918. Qcur = ggml_rope_custom(
  3919. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  3920. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  3921. ext_factor, attn_factor, beta_fast, beta_slow
  3922. );
  3923. cb(Qcur, "Qcur", il);
  3924. Kcur = ggml_rope_custom(
  3925. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  3926. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  3927. ext_factor, attn_factor, beta_fast, beta_slow
  3928. );
  3929. cb(Kcur, "Kcur", il);
  3930. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  3931. model.layers[il].wo, model.layers[il].bo,
  3932. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  3933. cb(cur, "kqv_out", il);
  3934. }
  3935. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  3936. cb(ffn_inp, "ffn_inp", il);
  3937. // feed-forward network
  3938. if (model.layers[il].ffn_gate_inp == nullptr) {
  3939. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  3940. model.layers[il].ffn_norm, NULL,
  3941. LLM_NORM_RMS, cb, il);
  3942. cb(cur, "ffn_norm", il);
  3943. cur = llm_build_ffn(ctx0, cur,
  3944. model.layers[il].ffn_up, NULL,
  3945. model.layers[il].ffn_gate, NULL,
  3946. model.layers[il].ffn_down, NULL,
  3947. NULL,
  3948. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  3949. cb(cur, "ffn_out", il);
  3950. } else {
  3951. // MoE branch
  3952. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  3953. model.layers[il].ffn_norm, NULL,
  3954. LLM_NORM_RMS, cb, il);
  3955. cb(cur, "ffn_norm", il);
  3956. ggml_tensor * logits = ggml_mul_mat(ctx0, model.layers[il].ffn_gate_inp, cur); // [n_tokens, num_experts]
  3957. cb(logits, "ffn_moe_logits", il);
  3958. ggml_tensor * probs = ggml_soft_max(ctx0, logits); // [n_tokens, num_experts]
  3959. cb(probs, "ffn_moe_probs", il);
  3960. // select experts
  3961. ggml_tensor * selected_experts = ggml_top_k(ctx0, probs, n_expert_used); // [n_tokens, num_experts_per_tok]
  3962. cb(selected_experts->src[0], "ffn_moe_argsort", il);
  3963. ggml_tensor * weights = ggml_get_rows(ctx0,
  3964. ggml_reshape_3d(ctx0, probs, 1, n_expert, n_tokens), selected_experts);
  3965. cb(weights, "ffn_moe_weights", il);
  3966. weights = ggml_reshape_2d(ctx0, weights, n_expert_used, n_tokens); // [n_tokens, num_experts_per_tok]
  3967. ggml_tensor * weights_sum = ggml_sum_rows(ctx0, weights);
  3968. cb(weights_sum, "ffn_moe_weights_sum", il);
  3969. weights = ggml_div(ctx0, weights, weights_sum); // [n_tokens, num_experts_per_tok]
  3970. cb(weights, "ffn_moe_weights_norm", il);
  3971. // compute expert outputs
  3972. ggml_tensor * moe_out = nullptr;
  3973. for (int i = 0; i < n_expert_used; ++i) {
  3974. ggml_tensor * cur_expert;
  3975. ggml_tensor * cur_up = ggml_mul_mat_id(ctx0, model.layers[il].ffn_up_exp, n_expert, selected_experts, i, cur);
  3976. cb(cur_up, "ffn_moe_up", il);
  3977. ggml_tensor * cur_gate = ggml_mul_mat_id(ctx0, model.layers[il].ffn_gate_exp, n_expert, selected_experts, i, cur);
  3978. cb(cur_gate, "ffn_moe_gate", il);
  3979. cur_gate = ggml_silu(ctx0, cur_gate);
  3980. cb(cur_gate, "ffn_moe_silu", il);
  3981. cur_expert = ggml_mul(ctx0, cur_up, cur_gate); // [n_tokens, n_embd]
  3982. cb(cur_expert, "ffn_moe_gate_par", il);
  3983. cur_expert = ggml_mul_mat_id(ctx0, model.layers[il].ffn_down_exp, n_expert, selected_experts, i, cur_expert); // [n_tokens, n_embd]
  3984. cb(cur_expert, "ffn_moe_down", il);
  3985. cur_expert = ggml_mul(ctx0, cur_expert,
  3986. ggml_view_2d(ctx0, weights, 1, n_tokens, weights->nb[1], i*weights->nb[0]));
  3987. cb(cur_expert, "ffn_moe_weighted", il);
  3988. if (i == 0) {
  3989. moe_out = cur_expert;
  3990. } else {
  3991. moe_out = ggml_add(ctx0, moe_out, cur_expert);
  3992. cb(moe_out, "ffn_moe_out", il);
  3993. }
  3994. }
  3995. cur = moe_out;
  3996. }
  3997. cur = ggml_add(ctx0, cur, ffn_inp);
  3998. cb(cur, "l_out", il);
  3999. // input for next layer
  4000. inpL = cur;
  4001. }
  4002. cur = inpL;
  4003. cur = llm_build_norm(ctx0, cur, hparams,
  4004. model.output_norm, NULL,
  4005. LLM_NORM_RMS, cb, -1);
  4006. cb(cur, "result_norm", -1);
  4007. // lm_head
  4008. cur = ggml_mul_mat(ctx0, model.output, cur);
  4009. cb(cur, "result_output", -1);
  4010. ggml_build_forward_expand(gf, cur);
  4011. return gf;
  4012. }
  4013. struct ggml_cgraph * build_baichuan() {
  4014. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4015. const int64_t n_embd_head = hparams.n_embd_head_v;
  4016. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4017. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4018. struct ggml_tensor * cur;
  4019. struct ggml_tensor * inpL;
  4020. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4021. cb(inpL, "inp_embd", -1);
  4022. // inp_pos - contains the positions
  4023. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4024. cb(inp_pos, "inp_pos", -1);
  4025. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4026. 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);
  4027. cb(KQ_mask, "KQ_mask", -1);
  4028. // shift the entire K-cache if needed
  4029. if (do_rope_shift) {
  4030. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  4031. }
  4032. for (int il = 0; il < n_layer; ++il) {
  4033. struct ggml_tensor * inpSA = inpL;
  4034. cur = llm_build_norm(ctx0, inpL, hparams,
  4035. model.layers[il].attn_norm, NULL,
  4036. LLM_NORM_RMS, cb, il);
  4037. cb(cur, "attn_norm", il);
  4038. // self-attention
  4039. {
  4040. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4041. cb(Qcur, "Qcur", il);
  4042. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4043. cb(Kcur, "Kcur", il);
  4044. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4045. cb(Vcur, "Vcur", il);
  4046. switch (model.type) {
  4047. case MODEL_7B:
  4048. Qcur = ggml_rope_custom(
  4049. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  4050. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  4051. ext_factor, attn_factor, beta_fast, beta_slow
  4052. );
  4053. Kcur = ggml_rope_custom(
  4054. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  4055. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  4056. ext_factor, attn_factor, beta_fast, beta_slow
  4057. );
  4058. break;
  4059. case MODEL_13B:
  4060. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd/n_head, n_head, n_tokens);
  4061. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd/n_head, n_head, n_tokens);
  4062. break;
  4063. default:
  4064. GGML_ASSERT(false);
  4065. }
  4066. cb(Qcur, "Qcur", il);
  4067. cb(Kcur, "Kcur", il);
  4068. // apply ALiBi for 13B model
  4069. const float max_alibi_bias = model.type == MODEL_13B ? 8.0f : -1.0f;
  4070. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4071. model.layers[il].wo, NULL,
  4072. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, max_alibi_bias, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4073. cb(cur, "kqv_out", il);
  4074. }
  4075. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4076. cb(ffn_inp, "ffn_inp", il);
  4077. // feed-forward network
  4078. {
  4079. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4080. model.layers[il].ffn_norm, NULL,
  4081. LLM_NORM_RMS, cb, il);
  4082. cb(cur, "ffn_norm", il);
  4083. cur = llm_build_ffn(ctx0, cur,
  4084. model.layers[il].ffn_up, NULL,
  4085. model.layers[il].ffn_gate, NULL,
  4086. model.layers[il].ffn_down, NULL,
  4087. NULL,
  4088. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4089. cb(cur, "ffn_out", il);
  4090. }
  4091. cur = ggml_add(ctx0, cur, ffn_inp);
  4092. cb(cur, "l_out", il);
  4093. // input for next layer
  4094. inpL = cur;
  4095. }
  4096. cur = inpL;
  4097. cur = llm_build_norm(ctx0, cur, hparams,
  4098. model.output_norm, NULL,
  4099. LLM_NORM_RMS, cb, -1);
  4100. cb(cur, "result_norm", -1);
  4101. // lm_head
  4102. cur = ggml_mul_mat(ctx0, model.output, cur);
  4103. cb(cur, "result_output", -1);
  4104. ggml_build_forward_expand(gf, cur);
  4105. return gf;
  4106. }
  4107. struct ggml_cgraph * build_falcon() {
  4108. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4109. const int64_t n_embd_head = hparams.n_embd_head_v;
  4110. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4111. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4112. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4113. struct ggml_tensor * cur;
  4114. struct ggml_tensor * inpL;
  4115. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4116. cb(inpL, "inp_embd", -1);
  4117. // inp_pos - contains the positions
  4118. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4119. cb(inp_pos, "inp_pos", -1);
  4120. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4121. 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);
  4122. cb(KQ_mask, "KQ_mask", -1);
  4123. // shift the entire K-cache if needed
  4124. if (do_rope_shift) {
  4125. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  4126. }
  4127. for (int il = 0; il < n_layer; ++il) {
  4128. struct ggml_tensor * attn_norm;
  4129. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  4130. model.layers[il].attn_norm,
  4131. model.layers[il].attn_norm_b,
  4132. LLM_NORM, cb, il);
  4133. cb(attn_norm, "attn_norm", il);
  4134. // self-attention
  4135. {
  4136. if (model.layers[il].attn_norm_2) {
  4137. // Falcon-40B
  4138. cur = llm_build_norm(ctx0, inpL, hparams,
  4139. model.layers[il].attn_norm_2,
  4140. model.layers[il].attn_norm_2_b,
  4141. LLM_NORM, cb, il);
  4142. cb(cur, "attn_norm_2", il);
  4143. } else {
  4144. cur = attn_norm;
  4145. }
  4146. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4147. cb(cur, "wqkv", il);
  4148. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4149. 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)));
  4150. 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)));
  4151. cb(Qcur, "Qcur", il);
  4152. cb(Kcur, "Kcur", il);
  4153. cb(Vcur, "Vcur", il);
  4154. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4155. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  4156. // using mode = 2 for neox mode
  4157. Qcur = ggml_rope_custom(
  4158. ctx0, Qcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4159. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4160. );
  4161. cb(Qcur, "Qcur", il);
  4162. Kcur = ggml_rope_custom(
  4163. ctx0, Kcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4164. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4165. );
  4166. cb(Kcur, "Kcur", il);
  4167. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4168. model.layers[il].wo, NULL,
  4169. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4170. cb(cur, "kqv_out", il);
  4171. }
  4172. struct ggml_tensor * ffn_inp = cur;
  4173. // feed forward
  4174. {
  4175. cur = llm_build_ffn(ctx0, attn_norm, // !! use the attn norm, not the result
  4176. model.layers[il].ffn_up, NULL,
  4177. NULL, NULL,
  4178. model.layers[il].ffn_down, NULL,
  4179. NULL,
  4180. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4181. cb(cur, "ffn_out", il);
  4182. }
  4183. cur = ggml_add(ctx0, cur, ffn_inp);
  4184. cb(cur, "l_out", il);
  4185. cur = ggml_add(ctx0, cur, inpL);
  4186. cb(cur, "l_out", il);
  4187. // input for next layer
  4188. inpL = cur;
  4189. }
  4190. cur = inpL;
  4191. // norm
  4192. cur = llm_build_norm(ctx0, cur, hparams,
  4193. model.output_norm,
  4194. model.output_norm_b,
  4195. LLM_NORM, cb, -1);
  4196. cb(cur, "result_norm", -1);
  4197. cur = ggml_mul_mat(ctx0, model.output, cur);
  4198. cb(cur, "result_output", -1);
  4199. ggml_build_forward_expand(gf, cur);
  4200. return gf;
  4201. }
  4202. struct ggml_cgraph * build_starcoder() {
  4203. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4204. const int64_t n_embd_head = hparams.n_embd_head_v;
  4205. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4206. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4207. struct ggml_tensor * cur;
  4208. struct ggml_tensor * pos;
  4209. struct ggml_tensor * inpL;
  4210. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4211. cb(inpL, "inp_embd", -1);
  4212. // inp_pos - contains the positions
  4213. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4214. cb(inp_pos, "inp_pos", -1);
  4215. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4216. 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);
  4217. cb(KQ_mask, "KQ_mask", -1);
  4218. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  4219. cb(pos, "pos_embd", -1);
  4220. inpL = ggml_add(ctx0, inpL, pos);
  4221. cb(inpL, "inpL", -1);
  4222. for (int il = 0; il < n_layer; ++il) {
  4223. cur = llm_build_norm(ctx0, inpL, hparams,
  4224. model.layers[il].attn_norm,
  4225. model.layers[il].attn_norm_b,
  4226. LLM_NORM, cb, il);
  4227. cb(cur, "attn_norm", il);
  4228. // self-attention
  4229. {
  4230. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4231. cb(cur, "wqkv", il);
  4232. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4233. cb(cur, "bqkv", il);
  4234. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4235. 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)));
  4236. 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)));
  4237. cb(Qcur, "Qcur", il);
  4238. cb(Kcur, "Kcur", il);
  4239. cb(Vcur, "Vcur", il);
  4240. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4241. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4242. model.layers[il].wo, model.layers[il].bo,
  4243. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4244. cb(cur, "kqv_out", il);
  4245. }
  4246. // add the input
  4247. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  4248. cb(ffn_inp, "ffn_inp", il);
  4249. // FF
  4250. {
  4251. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4252. model.layers[il].ffn_norm,
  4253. model.layers[il].ffn_norm_b,
  4254. LLM_NORM, cb, il);
  4255. cb(cur, "ffn_norm", il);
  4256. cur = llm_build_ffn(ctx0, cur,
  4257. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  4258. NULL, NULL,
  4259. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  4260. NULL,
  4261. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4262. cb(cur, "ffn_out", il);
  4263. }
  4264. inpL = ggml_add(ctx0, cur, ffn_inp);
  4265. cb(inpL, "l_out", il);
  4266. }
  4267. cur = llm_build_norm(ctx0, inpL, hparams,
  4268. model.output_norm,
  4269. model.output_norm_b,
  4270. LLM_NORM, cb, -1);
  4271. cb(cur, "result_norm", -1);
  4272. cur = ggml_mul_mat(ctx0, model.output, cur);
  4273. cb(cur, "result_output", -1);
  4274. ggml_build_forward_expand(gf, cur);
  4275. return gf;
  4276. }
  4277. struct ggml_cgraph * build_persimmon() {
  4278. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4279. const int64_t n_embd_head = hparams.n_embd_head_v;
  4280. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4281. GGML_ASSERT(n_embd_head/2 == hparams.n_rot);
  4282. struct ggml_tensor * cur;
  4283. struct ggml_tensor * inpL;
  4284. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4285. cb(inpL, "inp_embd", -1);
  4286. // inp_pos - contains the positions
  4287. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4288. cb(inp_pos, "inp_pos", -1);
  4289. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4290. 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);
  4291. cb(KQ_mask, "KQ_mask", -1);
  4292. if (do_rope_shift) {
  4293. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  4294. }
  4295. for (int il = 0; il < n_layer; ++il) {
  4296. struct ggml_tensor * residual = inpL;
  4297. cur = llm_build_norm(ctx0, inpL, hparams,
  4298. model.layers[il].attn_norm,
  4299. model.layers[il].attn_norm_b,
  4300. LLM_NORM, cb, il);
  4301. cb(cur, "attn_norm", il);
  4302. // self attention
  4303. {
  4304. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4305. cb(cur, "wqkv", il);
  4306. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4307. cb(cur, "bqkv", il);
  4308. // split qkv
  4309. GGML_ASSERT(n_head_kv == n_head);
  4310. struct ggml_tensor * tmpqkv = ggml_reshape_4d(ctx0, cur, n_embd_head, 3, n_head, n_tokens);
  4311. cb(tmpqkv, "tmpqkv", il);
  4312. struct ggml_tensor * tmpqkv_perm = ggml_cont(ctx0, ggml_permute(ctx0, tmpqkv, 0, 3, 1, 2));
  4313. cb(tmpqkv_perm, "tmpqkv", il);
  4314. struct ggml_tensor * tmpq = ggml_view_3d(
  4315. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  4316. ggml_element_size(tmpqkv_perm) * n_embd_head,
  4317. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  4318. 0
  4319. );
  4320. cb(tmpq, "tmpq", il);
  4321. struct ggml_tensor * tmpk = ggml_view_3d(
  4322. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  4323. ggml_element_size(tmpqkv_perm) * n_embd_head,
  4324. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  4325. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens
  4326. );
  4327. cb(tmpk, "tmpk", il);
  4328. // Q/K Layernorm
  4329. tmpq = llm_build_norm(ctx0, tmpq, hparams,
  4330. model.layers[il].attn_q_norm,
  4331. model.layers[il].attn_q_norm_b,
  4332. LLM_NORM, cb, il);
  4333. cb(tmpq, "tmpq", il);
  4334. tmpk = llm_build_norm(ctx0, tmpk, hparams,
  4335. model.layers[il].attn_k_norm,
  4336. model.layers[il].attn_k_norm_b,
  4337. LLM_NORM, cb, il);
  4338. cb(tmpk, "tmpk", il);
  4339. // RoPE the first n_rot of q/k, pass the other half, and concat.
  4340. struct ggml_tensor * qrot = ggml_view_3d(
  4341. ctx0, tmpq, hparams.n_rot, n_head, n_tokens,
  4342. ggml_element_size(tmpq) * n_embd_head,
  4343. ggml_element_size(tmpq) * n_embd_head * n_head,
  4344. 0
  4345. );
  4346. cb(qrot, "qrot", il);
  4347. struct ggml_tensor * krot = ggml_view_3d(
  4348. ctx0, tmpk, hparams.n_rot, n_head, n_tokens,
  4349. ggml_element_size(tmpk) * n_embd_head,
  4350. ggml_element_size(tmpk) * n_embd_head * n_head,
  4351. 0
  4352. );
  4353. cb(krot, "krot", il);
  4354. // get the second half of tmpq, e.g tmpq[n_rot:, :, :]
  4355. struct ggml_tensor * qpass = ggml_view_3d(
  4356. ctx0, tmpq, hparams.n_rot, n_head, n_tokens,
  4357. ggml_element_size(tmpq) * n_embd_head,
  4358. ggml_element_size(tmpq) * n_embd_head * n_head,
  4359. ggml_element_size(tmpq) * hparams.n_rot
  4360. );
  4361. cb(qpass, "qpass", il);
  4362. struct ggml_tensor * kpass = ggml_view_3d(
  4363. ctx0, tmpk, hparams.n_rot, n_head, n_tokens,
  4364. ggml_element_size(tmpk) * n_embd_head,
  4365. ggml_element_size(tmpk) * n_embd_head * n_head,
  4366. ggml_element_size(tmpk) * hparams.n_rot
  4367. );
  4368. cb(kpass, "kpass", il);
  4369. struct ggml_tensor * qrotated = ggml_rope_custom(
  4370. ctx0, qrot, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4371. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4372. );
  4373. cb(qrotated, "qrotated", il);
  4374. struct ggml_tensor * krotated = ggml_rope_custom(
  4375. ctx0, krot, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4376. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4377. );
  4378. cb(krotated, "krotated", il);
  4379. // ggml currently only supports concatenation on dim=2
  4380. // so we need to permute qrot, qpass, concat, then permute back.
  4381. qrotated = ggml_cont(ctx0, ggml_permute(ctx0, qrotated, 2, 1, 0, 3));
  4382. cb(qrotated, "qrotated", il);
  4383. krotated = ggml_cont(ctx0, ggml_permute(ctx0, krotated, 2, 1, 0, 3));
  4384. cb(krotated, "krotated", il);
  4385. qpass = ggml_cont(ctx0, ggml_permute(ctx0, qpass, 2, 1, 0, 3));
  4386. cb(qpass, "qpass", il);
  4387. kpass = ggml_cont(ctx0, ggml_permute(ctx0, kpass, 2, 1, 0, 3));
  4388. cb(kpass, "kpass", il);
  4389. struct ggml_tensor * Qcur = ggml_concat(ctx0, qrotated, qpass);
  4390. cb(Qcur, "Qcur", il);
  4391. struct ggml_tensor * Kcur = ggml_concat(ctx0, krotated, kpass);
  4392. cb(Kcur, "Kcur", il);
  4393. struct ggml_tensor * Q = ggml_cont(ctx0, ggml_permute(ctx0, Qcur, 2, 1, 0, 3));
  4394. cb(Q, "Q", il);
  4395. Kcur = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 2, 1, 0, 3));
  4396. cb(Kcur, "Kcur", il);
  4397. struct ggml_tensor * Vcur = ggml_view_3d(
  4398. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  4399. ggml_element_size(tmpqkv_perm) * n_embd_head,
  4400. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  4401. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens * 2
  4402. );
  4403. cb(Vcur, "Vcur", il);
  4404. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4405. model.layers[il].wo, model.layers[il].bo,
  4406. Kcur, Vcur, Q, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4407. cb(cur, "kqv_out", il);
  4408. }
  4409. struct ggml_tensor * ffn_inp = ggml_add(ctx0, residual, cur);
  4410. cb(ffn_inp, "ffn_inp", il);
  4411. // feed-forward network
  4412. {
  4413. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4414. model.layers[il].ffn_norm,
  4415. model.layers[il].ffn_norm_b,
  4416. LLM_NORM, cb, il);
  4417. cb(cur, "ffn_norm", il);
  4418. cur = llm_build_ffn(ctx0, cur,
  4419. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  4420. NULL, NULL,
  4421. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  4422. NULL,
  4423. LLM_FFN_RELU_SQR, LLM_FFN_SEQ, cb, il);
  4424. cb(cur, "ffn_out", il);
  4425. }
  4426. cur = ggml_add(ctx0, cur, ffn_inp);
  4427. cb(cur, "l_out", il);
  4428. inpL = cur;
  4429. }
  4430. cur = inpL;
  4431. cur = llm_build_norm(ctx0, cur, hparams,
  4432. model.output_norm,
  4433. model.output_norm_b,
  4434. LLM_NORM, cb, -1);
  4435. cb(cur, "result_norm", -1);
  4436. cur = ggml_mul_mat(ctx0, model.output, cur);
  4437. cb(cur, "result_output", -1);
  4438. ggml_build_forward_expand(gf, cur);
  4439. return gf;
  4440. }
  4441. struct ggml_cgraph * build_refact() {
  4442. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4443. const int64_t n_embd_head = hparams.n_embd_head_v;
  4444. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4445. struct ggml_tensor * cur;
  4446. struct ggml_tensor * inpL;
  4447. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4448. cb(inpL, "inp_embd", -1);
  4449. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4450. 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);
  4451. cb(KQ_mask, "KQ_mask", -1);
  4452. for (int il = 0; il < n_layer; ++il) {
  4453. struct ggml_tensor * inpSA = inpL;
  4454. cur = llm_build_norm(ctx0, inpL, hparams,
  4455. model.layers[il].attn_norm, NULL,
  4456. LLM_NORM_RMS, cb, il);
  4457. cb(cur, "attn_norm", il);
  4458. // self-attention
  4459. {
  4460. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4461. cb(Qcur, "Qcur", il);
  4462. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4463. cb(Kcur, "Kcur", il);
  4464. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4465. cb(Vcur, "Vcur", il);
  4466. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  4467. cb(Kcur, "Kcur", il);
  4468. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4469. cb(Qcur, "Qcur", il);
  4470. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4471. model.layers[il].wo, NULL,
  4472. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, 8.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4473. cb(cur, "kqv_out", il);
  4474. }
  4475. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4476. cb(ffn_inp, "ffn_inp", il);
  4477. // feed-forward network
  4478. {
  4479. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4480. model.layers[il].ffn_norm, NULL,
  4481. LLM_NORM_RMS, cb, il);
  4482. cb(cur, "ffn_norm", il);
  4483. cur = llm_build_ffn(ctx0, cur,
  4484. model.layers[il].ffn_up, NULL,
  4485. model.layers[il].ffn_gate, NULL,
  4486. model.layers[il].ffn_down, NULL,
  4487. NULL,
  4488. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4489. cb(cur, "ffn_out", il);
  4490. }
  4491. cur = ggml_add(ctx0, cur, ffn_inp);
  4492. cb(cur, "l_out", il);
  4493. // input for next layer
  4494. inpL = cur;
  4495. }
  4496. cur = inpL;
  4497. cur = llm_build_norm(ctx0, cur, hparams,
  4498. model.output_norm, NULL,
  4499. LLM_NORM_RMS, cb, -1);
  4500. cb(cur, "result_norm", -1);
  4501. // lm_head
  4502. cur = ggml_mul_mat(ctx0, model.output, cur);
  4503. cb(cur, "result_output", -1);
  4504. ggml_build_forward_expand(gf, cur);
  4505. return gf;
  4506. }
  4507. struct ggml_cgraph * build_bloom() {
  4508. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4509. const int64_t n_embd_head = hparams.n_embd_head_v;
  4510. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4511. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4512. struct ggml_tensor * cur;
  4513. struct ggml_tensor * inpL;
  4514. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4515. cb(inpL, "inp_embd", -1);
  4516. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4517. 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);
  4518. cb(KQ_mask, "KQ_mask", -1);
  4519. inpL = llm_build_norm(ctx0, inpL, hparams,
  4520. model.tok_norm,
  4521. model.tok_norm_b,
  4522. LLM_NORM, cb, -1);
  4523. cb(inpL, "inp_norm", -1);
  4524. for (int il = 0; il < n_layer; ++il) {
  4525. cur = llm_build_norm(ctx0, inpL, hparams,
  4526. model.layers[il].attn_norm,
  4527. model.layers[il].attn_norm_b,
  4528. LLM_NORM, cb, il);
  4529. cb(cur, "attn_norm", il);
  4530. // self-attention
  4531. {
  4532. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4533. cb(cur, "wqkv", il);
  4534. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4535. cb(cur, "bqkv", il);
  4536. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4537. 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)));
  4538. 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)));
  4539. cb(Qcur, "Qcur", il);
  4540. cb(Kcur, "Kcur", il);
  4541. cb(Vcur, "Vcur", il);
  4542. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4543. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4544. model.layers[il].wo, model.layers[il].bo,
  4545. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, 8.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4546. cb(cur, "kqv_out", il);
  4547. }
  4548. // Add the input
  4549. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  4550. cb(ffn_inp, "ffn_inp", il);
  4551. // FF
  4552. {
  4553. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4554. model.layers[il].ffn_norm,
  4555. model.layers[il].ffn_norm_b,
  4556. LLM_NORM, cb, il);
  4557. cb(cur, "ffn_norm", il);
  4558. cur = llm_build_ffn(ctx0, cur,
  4559. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  4560. NULL, NULL,
  4561. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  4562. NULL,
  4563. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4564. cb(cur, "ffn_out", il);
  4565. }
  4566. inpL = ggml_add(ctx0, cur, ffn_inp);
  4567. cb(inpL, "l_out", il);
  4568. }
  4569. cur = llm_build_norm(ctx0, inpL, hparams,
  4570. model.output_norm,
  4571. model.output_norm_b,
  4572. LLM_NORM, cb, -1);
  4573. cb(cur, "result_norm", -1);
  4574. cur = ggml_mul_mat(ctx0, model.output, cur);
  4575. cb(cur, "result_output", -1);
  4576. ggml_build_forward_expand(gf, cur);
  4577. return gf;
  4578. }
  4579. struct ggml_cgraph * build_mpt() {
  4580. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4581. const int64_t n_embd_head = hparams.n_embd_head_v;
  4582. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4583. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4584. struct ggml_tensor * cur;
  4585. struct ggml_tensor * inpL;
  4586. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4587. cb(inpL, "inp_embd", -1);
  4588. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4589. 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);
  4590. cb(KQ_mask, "KQ_mask", -1);
  4591. for (int il = 0; il < n_layer; ++il) {
  4592. struct ggml_tensor * attn_norm;
  4593. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  4594. model.layers[il].attn_norm,
  4595. NULL,
  4596. LLM_NORM, cb, il);
  4597. cb(attn_norm, "attn_norm", il);
  4598. // self-attention
  4599. {
  4600. cur = attn_norm;
  4601. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4602. cb(cur, "wqkv", il);
  4603. if (hparams.f_clamp_kqv > 0.0f) {
  4604. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  4605. cb(cur, "wqkv_clamped", il);
  4606. }
  4607. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4608. 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)));
  4609. 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)));
  4610. cb(Qcur, "Qcur", il);
  4611. cb(Kcur, "Kcur", il);
  4612. cb(Vcur, "Vcur", il);
  4613. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4614. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4615. model.layers[il].wo, NULL,
  4616. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, hparams.f_max_alibi_bias, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4617. cb(cur, "kqv_out", il);
  4618. }
  4619. // Add the input
  4620. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  4621. cb(ffn_inp, "ffn_inp", il);
  4622. // feed forward
  4623. {
  4624. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4625. model.layers[il].ffn_norm,
  4626. NULL,
  4627. LLM_NORM, cb, il);
  4628. cb(cur, "ffn_norm", il);
  4629. cur = llm_build_ffn(ctx0, cur,
  4630. model.layers[il].ffn_up, NULL,
  4631. NULL, NULL,
  4632. model.layers[il].ffn_down, NULL,
  4633. model.layers[il].ffn_act,
  4634. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4635. cb(cur, "ffn_out", il);
  4636. }
  4637. cur = ggml_add(ctx0, cur, ffn_inp);
  4638. cb(cur, "l_out", il);
  4639. // input for next layer
  4640. inpL = cur;
  4641. }
  4642. cur = inpL;
  4643. cur = llm_build_norm(ctx0, cur, hparams,
  4644. model.output_norm,
  4645. NULL,
  4646. LLM_NORM, cb, -1);
  4647. cb(cur, "result_norm", -1);
  4648. cur = ggml_mul_mat(ctx0, model.output, cur);
  4649. cb(cur, "result_output", -1);
  4650. ggml_build_forward_expand(gf, cur);
  4651. return gf;
  4652. }
  4653. struct ggml_cgraph * build_stablelm() {
  4654. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  4655. const int64_t n_embd_head = hparams.n_embd_head_v;
  4656. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4657. struct ggml_tensor * cur;
  4658. struct ggml_tensor * inpL;
  4659. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4660. cb(inpL, "inp_embd", -1);
  4661. // inp_pos - contains the positions
  4662. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4663. cb(inp_pos, "inp_pos", -1);
  4664. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4665. 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);
  4666. cb(KQ_mask, "KQ_mask", -1);
  4667. // shift the entire K-cache if needed
  4668. if (do_rope_shift) {
  4669. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  4670. }
  4671. for (int il = 0; il < n_layer; ++il) {
  4672. struct ggml_tensor * inpSA = inpL;
  4673. // norm
  4674. cur = llm_build_norm(ctx0, inpL, hparams,
  4675. model.layers[il].attn_norm,
  4676. model.layers[il].attn_norm_b,
  4677. LLM_NORM, cb, il);
  4678. cb(cur, "attn_norm", il);
  4679. // self-attention
  4680. {
  4681. // compute Q and K and RoPE them
  4682. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4683. cb(Qcur, "Qcur", il);
  4684. if (model.layers[il].bq) {
  4685. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  4686. cb(Qcur, "Qcur", il);
  4687. }
  4688. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4689. cb(Kcur, "Kcur", il);
  4690. if (model.layers[il].bk) {
  4691. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  4692. cb(Kcur, "Kcur", il);
  4693. }
  4694. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4695. cb(Vcur, "Vcur", il);
  4696. if (model.layers[il].bv) {
  4697. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  4698. cb(Vcur, "Vcur", il);
  4699. }
  4700. Qcur = ggml_rope_custom(
  4701. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  4702. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  4703. ext_factor, attn_factor, beta_fast, beta_slow
  4704. );
  4705. cb(Qcur, "Qcur", il);
  4706. Kcur = ggml_rope_custom(
  4707. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  4708. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  4709. ext_factor, attn_factor, beta_fast, beta_slow
  4710. );
  4711. cb(Kcur, "Kcur", il);
  4712. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4713. model.layers[il].wo, NULL,
  4714. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4715. cb(cur, "kqv_out", il);
  4716. }
  4717. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4718. cb(ffn_inp, "ffn_inp", il);
  4719. // feed-forward network
  4720. {
  4721. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4722. model.layers[il].ffn_norm,
  4723. model.layers[il].ffn_norm_b,
  4724. LLM_NORM, cb, il);
  4725. cb(cur, "ffn_norm", il);
  4726. cur = llm_build_ffn(ctx0, cur,
  4727. model.layers[il].ffn_up, NULL,
  4728. model.layers[il].ffn_gate, NULL,
  4729. model.layers[il].ffn_down, NULL,
  4730. NULL,
  4731. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4732. cb(cur, "ffn_out", il);
  4733. }
  4734. cur = ggml_add(ctx0, cur, ffn_inp);
  4735. cb(cur, "l_out", il);
  4736. // input for next layer
  4737. inpL = cur;
  4738. }
  4739. cur = inpL;
  4740. cur = llm_build_norm(ctx0, cur, hparams,
  4741. model.output_norm,
  4742. model.output_norm_b,
  4743. LLM_NORM, cb, -1);
  4744. cb(cur, "result_norm", -1);
  4745. // lm_head
  4746. cur = ggml_mul_mat(ctx0, model.output, cur);
  4747. cb(cur, "result_output", -1);
  4748. ggml_build_forward_expand(gf, cur);
  4749. return gf;
  4750. }
  4751. struct ggml_cgraph * build_qwen() {
  4752. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4753. const int64_t n_embd_head = hparams.n_embd_head_v;
  4754. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4755. struct ggml_tensor * cur;
  4756. struct ggml_tensor * inpL;
  4757. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4758. cb(inpL, "inp_embd", -1);
  4759. // inp_pos - contains the positions
  4760. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4761. cb(inp_pos, "inp_pos", -1);
  4762. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4763. 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);
  4764. cb(KQ_mask, "KQ_mask", -1);
  4765. // shift the entire K-cache if needed
  4766. if (do_rope_shift) {
  4767. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  4768. }
  4769. for (int il = 0; il < n_layer; ++il) {
  4770. struct ggml_tensor * inpSA = inpL;
  4771. cur = llm_build_norm(ctx0, inpL, hparams,
  4772. model.layers[il].attn_norm, NULL,
  4773. LLM_NORM_RMS, cb, il);
  4774. cb(cur, "attn_norm", il);
  4775. // self-attention
  4776. {
  4777. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4778. cb(cur, "wqkv", il);
  4779. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4780. cb(cur, "bqkv", il);
  4781. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4782. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  4783. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 2*sizeof(float)*(n_embd)));
  4784. cb(Qcur, "Qcur", il);
  4785. cb(Kcur, "Kcur", il);
  4786. cb(Vcur, "Vcur", il);
  4787. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4788. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  4789. // using mode = 2 for neox mode
  4790. Qcur = ggml_rope_custom(
  4791. ctx0, Qcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4792. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4793. );
  4794. cb(Qcur, "Qcur", il);
  4795. Kcur = ggml_rope_custom(
  4796. ctx0, Kcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4797. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4798. );
  4799. cb(Kcur, "Kcur", il);
  4800. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4801. model.layers[il].wo, NULL,
  4802. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4803. cb(cur, "kqv_out", il);
  4804. }
  4805. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4806. cb(ffn_inp, "ffn_inp", il);
  4807. // feed-forward forward
  4808. {
  4809. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4810. model.layers[il].ffn_norm, NULL,
  4811. LLM_NORM_RMS, cb, il);
  4812. cb(cur, "ffn_norm", il);
  4813. cur = llm_build_ffn(ctx0, cur,
  4814. model.layers[il].ffn_up, NULL,
  4815. model.layers[il].ffn_gate, NULL,
  4816. model.layers[il].ffn_down, NULL,
  4817. NULL,
  4818. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4819. cb(cur, "ffn_out", il);
  4820. }
  4821. cur = ggml_add(ctx0, cur, ffn_inp);
  4822. cb(cur, "l_out", il);
  4823. // input for next layer
  4824. inpL = cur;
  4825. }
  4826. cur = inpL;
  4827. cur = llm_build_norm(ctx0, cur, hparams,
  4828. model.output_norm, NULL,
  4829. LLM_NORM_RMS, cb, -1);
  4830. cb(cur, "result_norm", -1);
  4831. // lm_head
  4832. cur = ggml_mul_mat(ctx0, model.output, cur);
  4833. cb(cur, "result_output", -1);
  4834. ggml_build_forward_expand(gf, cur);
  4835. return gf;
  4836. }
  4837. struct ggml_cgraph * build_qwen2() {
  4838. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4839. const int64_t n_embd_head = hparams.n_embd_head_v;
  4840. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4841. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4842. struct ggml_tensor * cur;
  4843. struct ggml_tensor * inpL;
  4844. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4845. cb(inpL, "inp_embd", -1);
  4846. // inp_pos - contains the positions
  4847. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4848. cb(inp_pos, "inp_pos", -1);
  4849. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4850. 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);
  4851. cb(KQ_mask, "KQ_mask", -1);
  4852. // shift the entire K-cache if needed
  4853. if (do_rope_shift) {
  4854. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  4855. }
  4856. for (int il = 0; il < n_layer; ++il) {
  4857. struct ggml_tensor * inpSA = inpL;
  4858. // norm
  4859. cur = llm_build_norm(ctx0, inpL, hparams,
  4860. model.layers[il].attn_norm, NULL,
  4861. LLM_NORM_RMS, cb, il);
  4862. cb(cur, "attn_norm", il);
  4863. // self-attention
  4864. {
  4865. // compute Q and K and RoPE them
  4866. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4867. cb(Qcur, "Qcur", il);
  4868. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  4869. cb(Qcur, "Qcur", il);
  4870. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4871. cb(Kcur, "Kcur", il);
  4872. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  4873. cb(Kcur, "Kcur", il);
  4874. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4875. cb(Vcur, "Vcur", il);
  4876. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  4877. cb(Vcur, "Vcur", il);
  4878. // these nodes are added to the graph together so that they are not reordered
  4879. // by doing so, the number of splits in the graph is reduced
  4880. ggml_build_forward_expand(gf, Qcur);
  4881. ggml_build_forward_expand(gf, Kcur);
  4882. ggml_build_forward_expand(gf, Vcur);
  4883. Qcur = ggml_rope_custom(
  4884. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  4885. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  4886. ext_factor, attn_factor, beta_fast, beta_slow
  4887. );
  4888. cb(Qcur, "Qcur", il);
  4889. Kcur = ggml_rope_custom(
  4890. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  4891. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  4892. ext_factor, attn_factor, beta_fast, beta_slow
  4893. );
  4894. cb(Kcur, "Kcur", il);
  4895. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4896. model.layers[il].wo, model.layers[il].bo,
  4897. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4898. cb(cur, "kqv_out", il);
  4899. }
  4900. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4901. cb(ffn_inp, "ffn_inp", il);
  4902. // feed-forward network
  4903. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4904. model.layers[il].ffn_norm, NULL,
  4905. LLM_NORM_RMS, cb, il);
  4906. cb(cur, "ffn_norm", il);
  4907. cur = llm_build_ffn(ctx0, cur,
  4908. model.layers[il].ffn_up, NULL,
  4909. model.layers[il].ffn_gate, NULL,
  4910. model.layers[il].ffn_down, NULL,
  4911. NULL,
  4912. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4913. cb(cur, "ffn_out", il);
  4914. cur = ggml_add(ctx0, cur, ffn_inp);
  4915. cb(cur, "l_out", il);
  4916. // input for next layer
  4917. inpL = cur;
  4918. }
  4919. cur = inpL;
  4920. cur = llm_build_norm(ctx0, cur, hparams,
  4921. model.output_norm, NULL,
  4922. LLM_NORM_RMS, cb, -1);
  4923. cb(cur, "result_norm", -1);
  4924. // lm_head
  4925. cur = ggml_mul_mat(ctx0, model.output, cur);
  4926. cb(cur, "result_output", -1);
  4927. ggml_build_forward_expand(gf, cur);
  4928. return gf;
  4929. }
  4930. struct ggml_cgraph * build_phi2() {
  4931. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4932. const int64_t n_embd_head = hparams.n_embd_head_v;
  4933. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4934. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4935. struct ggml_tensor * cur;
  4936. struct ggml_tensor * attn_norm_output;
  4937. struct ggml_tensor * ffn_output;
  4938. struct ggml_tensor * inpL;
  4939. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  4940. cb(inpL, "inp_embd", -1);
  4941. // inp_pos - contains the positions
  4942. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  4943. cb(inp_pos, "inp_pos", -1);
  4944. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4945. 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);
  4946. cb(KQ_mask, "KQ_mask", -1);
  4947. // shift the entire K-cache if needed
  4948. if (do_rope_shift) {
  4949. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  4950. }
  4951. for (int il = 0; il < n_layer; ++il) {
  4952. attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  4953. model.layers[il].attn_norm,
  4954. model.layers[il].attn_norm_b,
  4955. LLM_NORM, cb, il);
  4956. cb(attn_norm_output, "attn_norm", il);
  4957. // self-attention
  4958. {
  4959. struct ggml_tensor * Qcur = nullptr;
  4960. struct ggml_tensor * Kcur = nullptr;
  4961. struct ggml_tensor * Vcur = nullptr;
  4962. if (model.layers[il].wqkv) {
  4963. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, attn_norm_output);
  4964. cb(cur, "wqkv", il);
  4965. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4966. cb(cur, "bqkv", il);
  4967. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4968. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  4969. 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)));
  4970. } else {
  4971. Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  4972. Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  4973. Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  4974. }
  4975. cb(Qcur, "Qcur", il);
  4976. cb(Kcur, "Kcur", il);
  4977. cb(Vcur, "Vcur", il);
  4978. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4979. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  4980. Qcur = ggml_rope_custom(
  4981. ctx0, Qcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4982. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4983. );
  4984. cb(Qcur, "Qcur", il);
  4985. // with phi2, we scale the Q to avoid precision issues
  4986. // ref: https://github.com/ml-explore/mlx-examples/blob/08e862336ade809bc37d1035f94b359e7d1a5152/phi2/phi2.py#L64-L66
  4987. Qcur = ggml_scale(ctx0, Qcur, 1.0f/sqrtf(float(n_embd_head)));
  4988. cb(Qcur, "Qcur", il);
  4989. Kcur = ggml_rope_custom(
  4990. ctx0, Kcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4991. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4992. );
  4993. cb(Kcur, "Kcur", il);
  4994. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  4995. model.layers[il].wo, model.layers[il].bo,
  4996. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f, cb, il);
  4997. cb(cur, "kqv_out", il);
  4998. }
  4999. // FF
  5000. {
  5001. ffn_output = llm_build_ffn(ctx0, attn_norm_output,
  5002. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5003. NULL, NULL,
  5004. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5005. NULL,
  5006. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5007. cb(ffn_output, "ffn_out", il);
  5008. }
  5009. cur = ggml_add(ctx0, cur, ffn_output);
  5010. cb(cur, "l_out", il);
  5011. cur = ggml_add(ctx0, cur, inpL);
  5012. cb(cur, "l_out", il);
  5013. inpL = cur;
  5014. }
  5015. cur = llm_build_norm(ctx0, inpL, hparams,
  5016. model.output_norm,
  5017. model.output_norm_b,
  5018. LLM_NORM, cb, -1);
  5019. cb(cur, "result_norm", -1);
  5020. cur = ggml_mul_mat(ctx0, model.output, cur);
  5021. cb(cur, "result_output_no_bias", -1);
  5022. cur = ggml_add(ctx0, cur, model.output_b);
  5023. cb(cur, "result_output", -1);
  5024. ggml_build_forward_expand(gf, cur);
  5025. return gf;
  5026. }
  5027. struct ggml_cgraph * build_plamo() {
  5028. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  5029. const int64_t n_embd_head = hparams.n_embd_head_v;
  5030. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5031. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5032. struct ggml_tensor * cur;
  5033. struct ggml_tensor * inpL;
  5034. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5035. cb(inpL, "inp_embd", -1);
  5036. // inp_pos - contains the positions
  5037. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5038. cb(inp_pos, "inp_pos", -1);
  5039. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5040. 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);
  5041. cb(KQ_mask, "KQ_mask", -1);
  5042. // shift the entire K-cache if needed
  5043. if (do_rope_shift) {
  5044. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  5045. }
  5046. for (int il = 0; il < n_layer; ++il) {
  5047. // norm
  5048. cur = llm_build_norm(ctx0, inpL, hparams,
  5049. model.layers[il].attn_norm, NULL,
  5050. LLM_NORM_RMS, cb, il);
  5051. cb(cur, "attn_norm", il);
  5052. struct ggml_tensor * attention_norm = cur;
  5053. // self-attention
  5054. {
  5055. // compute Q and K and RoPE them
  5056. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5057. cb(Qcur, "Qcur", il);
  5058. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5059. cb(Kcur, "Kcur", il);
  5060. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5061. cb(Vcur, "Vcur", il);
  5062. Qcur = ggml_rope_custom(
  5063. ctx0, ggml_reshape_3d(ctx0, Qcur, hparams.n_rot, n_head, n_tokens), inp_pos,
  5064. n_embd_head, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5065. ext_factor, attn_factor, beta_fast, beta_slow);
  5066. cb(Qcur, "Qcur", il);
  5067. Kcur = ggml_rope_custom(
  5068. ctx0, ggml_reshape_3d(ctx0, Kcur, hparams.n_rot, n_head_kv, n_tokens), inp_pos,
  5069. n_embd_head, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5070. ext_factor, attn_factor, beta_fast, beta_slow);
  5071. cb(Kcur, "Kcur", il);
  5072. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5073. model.layers[il].wo, NULL,
  5074. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5075. cb(cur, "kqv_out", il);
  5076. }
  5077. struct ggml_tensor * sa_out = cur;
  5078. cur = attention_norm;
  5079. // feed-forward network
  5080. {
  5081. cur = llm_build_ffn(ctx0, cur,
  5082. model.layers[il].ffn_up, NULL,
  5083. model.layers[il].ffn_gate, NULL,
  5084. model.layers[il].ffn_down, NULL,
  5085. NULL,
  5086. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5087. cb(cur, "ffn_out", il);
  5088. }
  5089. cur = ggml_add(ctx0, cur, sa_out);
  5090. cb(cur, "l_out", il);
  5091. cur = ggml_add(ctx0, cur, inpL);
  5092. cb(cur, "l_out", il);
  5093. // input for next layer
  5094. inpL = cur;
  5095. }
  5096. cur = inpL;
  5097. cur = llm_build_norm(ctx0, cur, hparams,
  5098. model.output_norm, NULL,
  5099. LLM_NORM_RMS, cb, -1);
  5100. cb(cur, "result_norm", -1);
  5101. // lm_head
  5102. cur = ggml_mul_mat(ctx0, model.output, cur);
  5103. cb(cur, "result_output", -1);
  5104. ggml_build_forward_expand(gf, cur);
  5105. return gf;
  5106. }
  5107. struct ggml_cgraph * build_gpt2() {
  5108. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5109. const int64_t n_embd_head = hparams.n_embd_head_v;
  5110. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5111. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5112. struct ggml_tensor * cur;
  5113. struct ggml_tensor * pos;
  5114. struct ggml_tensor * inpL;
  5115. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5116. cb(inpL, "inp_embd", -1);
  5117. // inp_pos - contains the positions
  5118. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5119. cb(inp_pos, "inp_pos", -1);
  5120. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5121. 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);
  5122. cb(KQ_mask, "KQ_mask", -1);
  5123. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  5124. cb(pos, "pos_embd", -1);
  5125. inpL = ggml_add(ctx0, inpL, pos);
  5126. cb(inpL, "inpL", -1);
  5127. for (int il = 0; il < n_layer; ++il) {
  5128. cur = llm_build_norm(ctx0, inpL, hparams,
  5129. model.layers[il].attn_norm,
  5130. model.layers[il].attn_norm_b,
  5131. LLM_NORM, cb, il);
  5132. cb(cur, "attn_norm", il);
  5133. // self-attention
  5134. {
  5135. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5136. cb(cur, "wqkv", il);
  5137. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5138. cb(cur, "bqkv", il);
  5139. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5140. 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)));
  5141. 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)));
  5142. cb(Qcur, "Qcur", il);
  5143. cb(Kcur, "Kcur", il);
  5144. cb(Vcur, "Vcur", il);
  5145. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5146. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5147. model.layers[il].wo, model.layers[il].bo,
  5148. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5149. cb(cur, "kqv_out", il);
  5150. }
  5151. // add the input
  5152. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5153. cb(ffn_inp, "ffn_inp", il);
  5154. // FF
  5155. {
  5156. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5157. model.layers[il].ffn_norm,
  5158. model.layers[il].ffn_norm_b,
  5159. LLM_NORM, cb, il);
  5160. cb(cur, "ffn_norm", il);
  5161. cur = llm_build_ffn(ctx0, cur,
  5162. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5163. NULL, NULL,
  5164. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5165. NULL,
  5166. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5167. cb(cur, "ffn_out", il);
  5168. }
  5169. inpL = ggml_add(ctx0, cur, ffn_inp);
  5170. cb(inpL, "l_out", il);
  5171. }
  5172. cur = llm_build_norm(ctx0, inpL, hparams,
  5173. model.output_norm,
  5174. model.output_norm_b,
  5175. LLM_NORM, cb, -1);
  5176. cb(cur, "result_norm", -1);
  5177. cur = ggml_mul_mat(ctx0, model.output, cur);
  5178. cb(cur, "result_output", -1);
  5179. ggml_build_forward_expand(gf, cur);
  5180. return gf;
  5181. }
  5182. struct ggml_cgraph * build_codeshell() {
  5183. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5184. const int64_t n_embd_head = hparams.n_embd_head_v;
  5185. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5186. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5187. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5188. struct ggml_tensor * cur;
  5189. struct ggml_tensor * inpL;
  5190. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, lctx.inp_tokens, lctx.inp_embd, cb);
  5191. cb(inpL, "inp_embd", -1);
  5192. // inp_pos - contains the positions
  5193. struct ggml_tensor * inp_pos = ggml_view_1d(ctx0, lctx.inp_pos, n_tokens, 0);
  5194. cb(inp_pos, "inp_pos", -1);
  5195. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5196. 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);
  5197. cb(KQ_mask, "KQ_mask", -1);
  5198. // shift the entire K-cache if needed
  5199. if (do_rope_shift) {
  5200. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, lctx.inp_K_shift, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  5201. }
  5202. for (int il = 0; il < n_layer; ++il) {
  5203. cur = llm_build_norm(ctx0, inpL, hparams,
  5204. model.layers[il].attn_norm,
  5205. model.layers[il].attn_norm_b,
  5206. LLM_NORM, cb, il);
  5207. cb(cur, "attn_norm", il);
  5208. // self-attention
  5209. {
  5210. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5211. cb(cur, "wqkv", il);
  5212. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5213. cb(cur, "bqkv", il);
  5214. struct ggml_tensor * tmpq = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5215. 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)));
  5216. 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)));
  5217. cb(tmpq, "tmpq", il);
  5218. cb(tmpk, "tmpk", il);
  5219. cb(Vcur, "Vcur", il);
  5220. struct ggml_tensor * Qcur = ggml_rope_custom(
  5221. ctx0, ggml_reshape_3d(ctx0, tmpq, n_embd_head, n_head, n_tokens), inp_pos,
  5222. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5223. ext_factor, attn_factor, beta_fast, beta_slow
  5224. );
  5225. cb(Qcur, "Qcur", il);
  5226. struct ggml_tensor * Kcur = ggml_rope_custom(
  5227. ctx0, ggml_reshape_3d(ctx0, tmpk, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5228. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5229. ext_factor, attn_factor, beta_fast, beta_slow
  5230. );
  5231. cb(Kcur, "Kcur", il);
  5232. cur = llm_build_kv(ctx0, model, hparams, kv_self, gf,
  5233. model.layers[il].wo, model.layers[il].bo,
  5234. Kcur, Vcur, Qcur, KQ_mask, n_ctx, n_tokens, kv_head, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5235. cb(cur, "kqv_out", il);
  5236. }
  5237. // add the input
  5238. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5239. cb(ffn_inp, "ffn_inp", il);
  5240. // FF
  5241. {
  5242. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5243. model.layers[il].ffn_norm,
  5244. model.layers[il].ffn_norm_b,
  5245. LLM_NORM, cb, il);
  5246. cb(cur, "ffn_norm", il);
  5247. cur = llm_build_ffn(ctx0, cur,
  5248. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5249. NULL, NULL,
  5250. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5251. NULL,
  5252. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5253. cb(cur, "ffn_out", il);
  5254. }
  5255. inpL = ggml_add(ctx0, cur, ffn_inp);
  5256. cb(inpL, "l_out", il);
  5257. }
  5258. cur = llm_build_norm(ctx0, inpL, hparams,
  5259. model.output_norm,
  5260. model.output_norm_b,
  5261. LLM_NORM, cb, -1);
  5262. cb(cur, "result_norm", -1);
  5263. cur = ggml_mul_mat(ctx0, model.output, cur);
  5264. cb(cur, "result_output", -1);
  5265. ggml_build_forward_expand(gf, cur);
  5266. return gf;
  5267. }
  5268. };
  5269. static struct ggml_cgraph * llama_build_graph(
  5270. llama_context & lctx,
  5271. const llama_batch & batch) {
  5272. const auto & model = lctx.model;
  5273. // check if we should build the worst-case graph (for memory measurement)
  5274. const bool worst_case = ggml_tallocr_is_measure(lctx.alloc);
  5275. // this callback allows us to apply custom logic to each tensor (e.g. ggml-alloc, offloading, etc.)
  5276. llm_build_cb cb = [&](struct ggml_tensor * cur, const char * name, int il) {
  5277. if (il >= 0) {
  5278. ggml_format_name(cur, "%s-%d", name, il);
  5279. } else {
  5280. ggml_set_name(cur, name);
  5281. }
  5282. if (!lctx.cparams.offload_kqv) {
  5283. if (strcmp(name, "kqv_merged_cont") == 0) {
  5284. // all nodes between the KV store and the attention output are run on the CPU
  5285. ggml_backend_sched_set_node_backend(lctx.sched, cur, lctx.backend_cpu);
  5286. }
  5287. }
  5288. };
  5289. struct ggml_cgraph * result = NULL;
  5290. struct llm_build_context llm(lctx, batch, cb, worst_case);
  5291. //
  5292. // set input data
  5293. //
  5294. if (!ggml_tallocr_is_measure(lctx.alloc)) {
  5295. if (batch.token) {
  5296. const int64_t n_tokens = batch.n_tokens;
  5297. ggml_backend_tensor_set(lctx.inp_tokens, batch.token, 0, n_tokens*ggml_element_size(lctx.inp_tokens));
  5298. }
  5299. if (batch.embd) {
  5300. const int64_t n_embd = llm.n_embd;
  5301. const int64_t n_tokens = batch.n_tokens;
  5302. ggml_backend_tensor_set(lctx.inp_embd, batch.embd, 0, n_tokens*n_embd*ggml_element_size(lctx.inp_embd));
  5303. }
  5304. if (batch.pos) {
  5305. const int64_t n_tokens = batch.n_tokens;
  5306. ggml_backend_tensor_set(lctx.inp_pos, batch.pos, 0, n_tokens*ggml_element_size(lctx.inp_pos));
  5307. }
  5308. {
  5309. const int64_t n_kv = llm.n_kv;
  5310. const int64_t n_tokens = batch.n_tokens;
  5311. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_KQ_mask->buffer));
  5312. float * data = (float *) lctx.inp_KQ_mask->data;
  5313. for (int h = 0; h < 1; ++h) {
  5314. for (int j = 0; j < n_tokens; ++j) {
  5315. const llama_pos pos = batch.pos[j];
  5316. const llama_seq_id seq_id = batch.seq_id[j][0];
  5317. for (int i = 0; i < n_kv; ++i) {
  5318. float f;
  5319. if (!lctx.kv_self.cells[i].has_seq_id(seq_id) || lctx.kv_self.cells[i].pos > pos) {
  5320. f = -INFINITY;
  5321. } else {
  5322. f = 0;
  5323. }
  5324. data[h*(n_kv*n_tokens) + j*n_kv + i] = f;
  5325. }
  5326. }
  5327. }
  5328. }
  5329. if (llm.do_rope_shift) {
  5330. const int64_t n_ctx = llm.n_ctx;
  5331. GGML_ASSERT(ggml_backend_buffer_is_host(lctx.inp_K_shift->buffer));
  5332. int32_t * data = (int32_t *) lctx.inp_K_shift->data;
  5333. for (int i = 0; i < n_ctx; ++i) {
  5334. data[i] = lctx.kv_self.cells[i].delta;
  5335. }
  5336. }
  5337. }
  5338. llm.init();
  5339. switch (model.arch) {
  5340. case LLM_ARCH_LLAMA:
  5341. {
  5342. result = llm.build_llama();
  5343. } break;
  5344. case LLM_ARCH_BAICHUAN:
  5345. {
  5346. result = llm.build_baichuan();
  5347. } break;
  5348. case LLM_ARCH_FALCON:
  5349. {
  5350. result = llm.build_falcon();
  5351. } break;
  5352. case LLM_ARCH_STARCODER:
  5353. {
  5354. result = llm.build_starcoder();
  5355. } break;
  5356. case LLM_ARCH_PERSIMMON:
  5357. {
  5358. result = llm.build_persimmon();
  5359. } break;
  5360. case LLM_ARCH_REFACT:
  5361. {
  5362. result = llm.build_refact();
  5363. } break;
  5364. case LLM_ARCH_BLOOM:
  5365. {
  5366. result = llm.build_bloom();
  5367. } break;
  5368. case LLM_ARCH_MPT:
  5369. {
  5370. result = llm.build_mpt();
  5371. } break;
  5372. case LLM_ARCH_STABLELM:
  5373. {
  5374. result = llm.build_stablelm();
  5375. } break;
  5376. case LLM_ARCH_QWEN:
  5377. {
  5378. result = llm.build_qwen();
  5379. } break;
  5380. case LLM_ARCH_QWEN2:
  5381. {
  5382. result = llm.build_qwen2();
  5383. } break;
  5384. case LLM_ARCH_PHI2:
  5385. {
  5386. result = llm.build_phi2();
  5387. } break;
  5388. case LLM_ARCH_PLAMO:
  5389. {
  5390. result = llm.build_plamo();
  5391. } break;
  5392. case LLM_ARCH_GPT2:
  5393. {
  5394. result = llm.build_gpt2();
  5395. } break;
  5396. case LLM_ARCH_CODESHELL:
  5397. {
  5398. result = llm.build_codeshell();
  5399. } break;
  5400. default:
  5401. GGML_ASSERT(false);
  5402. }
  5403. llm.free();
  5404. return result;
  5405. }
  5406. // decode a batch of tokens by evaluating the transformer
  5407. //
  5408. // - lctx: llama context
  5409. // - batch: batch to evaluate
  5410. //
  5411. // return 0 on success
  5412. // return positive int on warning
  5413. // return negative int on error
  5414. //
  5415. static int llama_decode_internal(
  5416. llama_context & lctx,
  5417. llama_batch batch) {
  5418. const uint32_t n_tokens = batch.n_tokens;
  5419. if (n_tokens == 0) {
  5420. LLAMA_LOG_ERROR("%s: n_tokens == 0", __func__);
  5421. return -1;
  5422. }
  5423. const auto & model = lctx.model;
  5424. const auto & hparams = model.hparams;
  5425. const auto & cparams = lctx.cparams;
  5426. const auto n_batch = cparams.n_batch;
  5427. GGML_ASSERT(n_tokens <= n_batch);
  5428. int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  5429. GGML_ASSERT((!batch.token && batch.embd) || (batch.token && !batch.embd)); // NOLINT
  5430. const int64_t t_start_us = ggml_time_us();
  5431. #ifdef GGML_USE_MPI
  5432. // TODO: needs fix after #3228
  5433. GGML_ASSERT(false && "not implemented");
  5434. //ggml_mpi_eval_init(lctx.ctx_mpi, &n_tokens, &n_past, &n_threads);
  5435. #endif
  5436. GGML_ASSERT(n_threads > 0);
  5437. auto & kv_self = lctx.kv_self;
  5438. const int64_t n_embd = hparams.n_embd;
  5439. const int64_t n_vocab = hparams.n_vocab;
  5440. // helpers for smoother batch API transition
  5441. // after deprecating the llama_eval calls, these will be removed
  5442. std::vector<llama_pos> pos;
  5443. std::vector<int32_t> n_seq_id;
  5444. std::vector<llama_seq_id *> seq_id_arr;
  5445. std::vector<std::vector<llama_seq_id>> seq_id;
  5446. if (batch.pos == nullptr) {
  5447. pos.resize(n_tokens);
  5448. for (uint32_t i = 0; i < n_tokens; i++) {
  5449. pos[i] = batch.all_pos_0 + i*batch.all_pos_1;
  5450. }
  5451. batch.pos = pos.data();
  5452. }
  5453. if (batch.seq_id == nullptr) {
  5454. n_seq_id.resize(n_tokens);
  5455. seq_id.resize(n_tokens);
  5456. seq_id_arr.resize(n_tokens);
  5457. for (uint32_t i = 0; i < n_tokens; i++) {
  5458. n_seq_id[i] = 1;
  5459. seq_id[i].resize(1);
  5460. seq_id[i][0] = batch.all_seq_id;
  5461. seq_id_arr[i] = seq_id[i].data();
  5462. }
  5463. batch.n_seq_id = n_seq_id.data();
  5464. batch.seq_id = seq_id_arr.data();
  5465. }
  5466. // if we have enough unused cells before the current head ->
  5467. // better to start searching from the beginning of the cache, hoping to fill it
  5468. if (kv_self.head > kv_self.used + 2*n_tokens) {
  5469. kv_self.head = 0;
  5470. }
  5471. if (!llama_kv_cache_find_slot(kv_self, batch)) {
  5472. return 1;
  5473. }
  5474. // a heuristic, to avoid attending the full cache if it is not yet utilized
  5475. // after enough generations, the benefit from this heuristic disappears
  5476. // if we start defragmenting the cache, the benefit from this will be more important
  5477. kv_self.n = std::min((int32_t) cparams.n_ctx, std::max(32, GGML_PAD(llama_kv_cache_cell_max(kv_self), 32)));
  5478. //kv_self.n = llama_kv_cache_cell_max(kv_self);
  5479. //printf("kv_self.n = %5d, kv_self.used = %5d, kv_self.head = %5d\n", kv_self.n, kv_self.used, kv_self.head);
  5480. ggml_backend_sched_reset(lctx.sched);
  5481. ggml_backend_sched_set_eval_callback(lctx.sched, lctx.cparams.cb_eval, lctx.cparams.cb_eval_user_data);
  5482. ggml_cgraph * gf = llama_build_graph(lctx, batch);
  5483. // the output is always the last tensor in the graph
  5484. struct ggml_tensor * res = gf->nodes[gf->n_nodes - 1];
  5485. GGML_ASSERT(strcmp(res->name, "result_output") == 0);
  5486. // the embeddings could be the second to last tensor, or the third to last tensor
  5487. struct ggml_tensor * embeddings = gf->nodes[gf->n_nodes - 2];
  5488. if (strcmp(embeddings->name, "result_norm") != 0) {
  5489. embeddings = gf->nodes[gf->n_nodes - 3];
  5490. GGML_ASSERT(strcmp(embeddings->name, "result_norm") == 0);
  5491. }
  5492. // 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);
  5493. // for big prompts, if BLAS is enabled, it is better to use only one thread
  5494. // otherwise, the threads are spin-lock waiting for the BLAS calls and are degrading the performance
  5495. // TODO: this is mostly important for Apple Silicon where CBLAS is still performing very well
  5496. // we still need some threads to process all non-mul_mat ops, but not too much to avoid interfering
  5497. // with the BLAS calls. need a better solution
  5498. if (n_tokens >= 32 && ggml_cpu_has_blas() && !ggml_cpu_has_gpublas()) {
  5499. n_threads = std::min(4, n_threads);
  5500. }
  5501. const bool fully_offloaded = model.n_gpu_layers >= (int) hparams.n_layer + 1;
  5502. if (ggml_cpu_has_cublas() && fully_offloaded) {
  5503. n_threads = 1;
  5504. }
  5505. #ifdef GGML_USE_MPI
  5506. const int64_t n_layer = hparams.n_layer;
  5507. ggml_mpi_graph_compute_pre(lctx.ctx_mpi, gf, n_layer);
  5508. #endif
  5509. #ifdef GGML_USE_METAL
  5510. if (ggml_backend_is_metal(lctx.backend_metal)) {
  5511. ggml_backend_metal_set_n_cb(lctx.backend_metal, n_threads);
  5512. }
  5513. #endif
  5514. if (lctx.backend_cpu != nullptr) {
  5515. ggml_backend_cpu_set_n_threads(lctx.backend_cpu, n_threads);
  5516. }
  5517. ggml_backend_sched_graph_compute(lctx.sched, gf);
  5518. // fprintf(stderr, "splits: %d\n", ggml_backend_sched_get_n_splits(lctx.sched));
  5519. #ifdef GGML_USE_MPI
  5520. ggml_mpi_graph_compute_post(lctx.ctx_mpi, gf, n_layer);
  5521. #endif
  5522. // update the kv ring buffer
  5523. {
  5524. if (kv_self.has_shift) {
  5525. kv_self.has_shift = false;
  5526. for (uint32_t i = 0; i < kv_self.size; ++i) {
  5527. kv_self.cells[i].delta = 0;
  5528. }
  5529. }
  5530. kv_self.head += n_tokens;
  5531. // Ensure kv cache head points to a valid index.
  5532. if (kv_self.head >= kv_self.size) {
  5533. kv_self.head = 0;
  5534. }
  5535. }
  5536. #ifdef GGML_PERF
  5537. // print timing information per ggml operation (for debugging purposes)
  5538. // requires GGML_PERF to be defined
  5539. ggml_graph_print(gf);
  5540. #endif
  5541. // plot the computation graph in dot format (for debugging purposes)
  5542. //if (n_past%100 == 0) {
  5543. // ggml_graph_dump_dot(gf, NULL, "llama.dot");
  5544. //}
  5545. // extract logits
  5546. // TODO: do not compute and extract logits if only embeddings are needed
  5547. // need to update the graphs to skip "result_output"
  5548. {
  5549. auto & logits_out = lctx.logits;
  5550. #ifndef NDEBUG
  5551. auto & logits_valid = lctx.logits_valid;
  5552. logits_valid.clear();
  5553. logits_valid.resize(n_tokens);
  5554. logits_out.clear();
  5555. #endif
  5556. ggml_backend_t res_backend = ggml_backend_sched_get_node_backend(lctx.sched, res);
  5557. GGML_ASSERT(res_backend != nullptr);
  5558. if (batch.logits) {
  5559. logits_out.resize(n_vocab * n_tokens);
  5560. for (uint32_t i = 0; i < n_tokens; i++) {
  5561. if (batch.logits[i] == 0) {
  5562. continue;
  5563. }
  5564. ggml_backend_tensor_get_async(res_backend, res, logits_out.data() + (n_vocab*i), (n_vocab*i)*sizeof(float), n_vocab*sizeof(float));
  5565. #ifndef NDEBUG
  5566. logits_valid[i] = true;
  5567. #endif
  5568. }
  5569. } else if (lctx.logits_all) {
  5570. logits_out.resize(n_vocab * n_tokens);
  5571. ggml_backend_tensor_get_async(res_backend, res, logits_out.data(), 0, n_vocab*n_tokens*sizeof(float));
  5572. #ifndef NDEBUG
  5573. std::fill(logits_valid.begin(), logits_valid.end(), true);
  5574. #endif
  5575. } else {
  5576. logits_out.resize(n_vocab);
  5577. ggml_backend_tensor_get_async(res_backend, res, logits_out.data(), (n_vocab*(n_tokens - 1))*sizeof(float), n_vocab*sizeof(float));
  5578. #ifndef NDEBUG
  5579. logits_valid[0] = true;
  5580. #endif
  5581. }
  5582. ggml_backend_synchronize(res_backend);
  5583. }
  5584. // extract embeddings
  5585. if (!lctx.embedding.empty()) {
  5586. auto & embedding_out = lctx.embedding;
  5587. embedding_out.resize(n_embd);
  5588. ggml_backend_t embeddings_backend = ggml_backend_sched_get_node_backend(lctx.sched, embeddings);
  5589. ggml_backend_tensor_get_async(embeddings_backend, embeddings, embedding_out.data(), (n_embd*(n_tokens - 1))*sizeof(float), n_embd*sizeof(float));
  5590. ggml_backend_synchronize(embeddings_backend);
  5591. }
  5592. // measure the performance only for the single-token evals
  5593. if (n_tokens == 1) {
  5594. lctx.t_eval_us += ggml_time_us() - t_start_us;
  5595. lctx.n_eval++;
  5596. }
  5597. else if (n_tokens > 1) {
  5598. lctx.t_p_eval_us += ggml_time_us() - t_start_us;
  5599. lctx.n_p_eval += n_tokens;
  5600. }
  5601. // get a more accurate load time, upon first eval
  5602. // TODO: fix this
  5603. if (!lctx.has_evaluated_once) {
  5604. lctx.t_load_us = ggml_time_us() - lctx.t_start_us;
  5605. lctx.has_evaluated_once = true;
  5606. }
  5607. return 0;
  5608. }
  5609. //
  5610. // tokenizer
  5611. //
  5612. static enum llama_vocab_type llama_vocab_get_type(const llama_vocab & vocab) {
  5613. return vocab.type;
  5614. }
  5615. static bool llama_is_normal_token(const llama_vocab & vocab, llama_token id) {
  5616. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL;
  5617. }
  5618. static bool llama_is_unknown_token(const llama_vocab & vocab, llama_token id) {
  5619. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_UNKNOWN;
  5620. }
  5621. static bool llama_is_control_token(const llama_vocab & vocab, llama_token id) {
  5622. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_CONTROL;
  5623. }
  5624. static bool llama_is_byte_token(const llama_vocab & vocab, llama_token id) {
  5625. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_BYTE;
  5626. }
  5627. static bool llama_is_user_defined_token(const llama_vocab& vocab, llama_token id) {
  5628. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_USER_DEFINED;
  5629. }
  5630. static uint8_t llama_token_to_byte(const llama_vocab& vocab, llama_token id) {
  5631. GGML_ASSERT(llama_is_byte_token(vocab, id));
  5632. const auto& token_data = vocab.id_to_token.at(id);
  5633. switch (llama_vocab_get_type(vocab)) {
  5634. case LLAMA_VOCAB_TYPE_SPM: {
  5635. auto buf = token_data.text.substr(3, 2);
  5636. return strtol(buf.c_str(), NULL, 16);
  5637. }
  5638. case LLAMA_VOCAB_TYPE_BPE: {
  5639. GGML_ASSERT(false);
  5640. return unicode_to_bytes_bpe(token_data.text);
  5641. }
  5642. default:
  5643. GGML_ASSERT(false);
  5644. }
  5645. }
  5646. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch) {
  5647. static const char * hex = "0123456789ABCDEF";
  5648. switch (llama_vocab_get_type(vocab)) {
  5649. case LLAMA_VOCAB_TYPE_SPM: {
  5650. const char buf[7] = { '<', '0', 'x', hex[ch >> 4], hex[ch & 15], '>', 0 };
  5651. return vocab.token_to_id.at(buf);
  5652. }
  5653. case LLAMA_VOCAB_TYPE_BPE: {
  5654. return vocab.token_to_id.at(bytes_to_unicode_bpe(ch));
  5655. }
  5656. default:
  5657. GGML_ASSERT(false);
  5658. }
  5659. }
  5660. static void llama_escape_whitespace(std::string & text) {
  5661. replace_all(text, " ", "\xe2\x96\x81");
  5662. }
  5663. static void llama_unescape_whitespace(std::string & word) {
  5664. replace_all(word, "\xe2\x96\x81", " ");
  5665. }
  5666. struct llm_symbol {
  5667. using index = int;
  5668. index prev;
  5669. index next;
  5670. const char * text;
  5671. size_t n;
  5672. };
  5673. static_assert(std::is_trivially_copyable<llm_symbol>::value, "llm_symbol is not trivially copyable");
  5674. // SPM tokenizer
  5675. // original implementation:
  5676. // https://github.com/ggerganov/llama.cpp/commit/074bea2eb1f1349a0118239c4152914aecaa1be4
  5677. struct llm_bigram_spm {
  5678. struct comparator {
  5679. bool operator()(llm_bigram_spm & l, llm_bigram_spm & r) {
  5680. return (l.score < r.score) || (l.score == r.score && l.left > r.left);
  5681. }
  5682. };
  5683. using queue_storage = std::vector<llm_bigram_spm>;
  5684. using queue = std::priority_queue<llm_bigram_spm, queue_storage, comparator>;
  5685. llm_symbol::index left;
  5686. llm_symbol::index right;
  5687. float score;
  5688. size_t size;
  5689. };
  5690. struct llm_tokenizer_spm {
  5691. llm_tokenizer_spm(const llama_vocab & vocab): vocab(vocab) {}
  5692. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  5693. // split string into utf8 chars
  5694. int index = 0;
  5695. size_t offs = 0;
  5696. while (offs < text.size()) {
  5697. llm_symbol sym;
  5698. size_t len = utf8_len(text[offs]);
  5699. sym.text = text.c_str() + offs;
  5700. sym.n = std::min(len, text.size() - offs);
  5701. offs += sym.n;
  5702. sym.prev = index - 1;
  5703. sym.next = offs == text.size() ? -1 : index + 1;
  5704. index++;
  5705. symbols.emplace_back(sym);
  5706. }
  5707. // seed the work queue with all possible 2-character tokens.
  5708. for (size_t i = 1; i < symbols.size(); ++i) {
  5709. try_add_bigram(i - 1, i);
  5710. }
  5711. // keep substituting the highest frequency pairs for as long as we can.
  5712. while (!work_queue.empty()) {
  5713. auto bigram = work_queue.top();
  5714. work_queue.pop();
  5715. auto & left_sym = symbols[bigram.left];
  5716. auto & right_sym = symbols[bigram.right];
  5717. // if one of the symbols already got merged, skip it.
  5718. if (left_sym.n == 0 || right_sym.n == 0 ||
  5719. left_sym.n + right_sym.n != bigram.size) {
  5720. continue;
  5721. }
  5722. // merge the right sym into the left one
  5723. left_sym.n += right_sym.n;
  5724. right_sym.n = 0;
  5725. //LLAMA_LOG_INFO("left = '%*s' size = %zu\n", (int) left_sym.n, left_sym.text, bigram.size);
  5726. // remove the right sym from the chain
  5727. left_sym.next = right_sym.next;
  5728. if (right_sym.next >= 0) {
  5729. symbols[right_sym.next].prev = bigram.left;
  5730. }
  5731. // find more substitutions
  5732. try_add_bigram(left_sym.prev, bigram.left);
  5733. try_add_bigram(bigram.left, left_sym.next);
  5734. }
  5735. for (int i = 0; i != -1; i = symbols[i].next) {
  5736. auto & symbol = symbols[i];
  5737. resegment(symbol, output);
  5738. }
  5739. }
  5740. private:
  5741. void resegment(llm_symbol & symbol, std::vector<llama_vocab::id> & output) {
  5742. auto text = std::string(symbol.text, symbol.n);
  5743. auto token = vocab.token_to_id.find(text);
  5744. // Do we need to support is_unused?
  5745. if (token != vocab.token_to_id.end()) {
  5746. output.push_back((*token).second);
  5747. return;
  5748. }
  5749. const auto p = rev_merge.find(text);
  5750. if (p == rev_merge.end()) {
  5751. // output any symbols that did not form tokens as bytes.
  5752. for (int j = 0; j < (int)symbol.n; ++j) {
  5753. llama_vocab::id token_id = llama_byte_to_token(vocab, symbol.text[j]);
  5754. output.push_back(token_id);
  5755. }
  5756. return;
  5757. }
  5758. resegment(symbols[p->second.first], output);
  5759. resegment(symbols[p->second.second], output);
  5760. }
  5761. void try_add_bigram(int left, int right) {
  5762. if (left == -1 || right == -1) {
  5763. return;
  5764. }
  5765. const std::string text = std::string(symbols[left].text, symbols[left].n + symbols[right].n);
  5766. auto token = vocab.token_to_id.find(text);
  5767. if (token == vocab.token_to_id.end()) {
  5768. return;
  5769. }
  5770. if (static_cast<size_t>((*token).second) >= vocab.id_to_token.size()) {
  5771. return;
  5772. }
  5773. const auto & tok_data = vocab.id_to_token[(*token).second];
  5774. llm_bigram_spm bigram;
  5775. bigram.left = left;
  5776. bigram.right = right;
  5777. bigram.score = tok_data.score;
  5778. bigram.size = text.size();
  5779. work_queue.push(bigram);
  5780. // Do we need to support is_unused?
  5781. rev_merge[text] = std::make_pair(left, right);
  5782. }
  5783. const llama_vocab & vocab;
  5784. std::vector<llm_symbol> symbols;
  5785. llm_bigram_spm::queue work_queue;
  5786. std::map<std::string, std::pair<int, int>> rev_merge;
  5787. };
  5788. // BPE tokenizer
  5789. // adapted from https://github.com/cmp-nct/ggllm.cpp [MIT License]
  5790. // tried to simplify unicode stuff, so most likely does not work 100% correctly!
  5791. // TODO: there are a lot of common parts between spm and bpe tokenizers, should be refactored and reused
  5792. struct llm_bigram_bpe {
  5793. struct comparator {
  5794. bool operator()(const llm_bigram_bpe & l, const llm_bigram_bpe & r) const {
  5795. return l.rank > r.rank || (l.rank == r.rank && l.left > r.left);
  5796. }
  5797. };
  5798. using queue_storage = std::vector<llm_bigram_bpe>;
  5799. using queue = std::priority_queue<llm_bigram_bpe, queue_storage, comparator>;
  5800. llm_symbol::index left;
  5801. llm_symbol::index right;
  5802. std::string text;
  5803. int rank;
  5804. size_t size;
  5805. };
  5806. struct llm_tokenizer_bpe {
  5807. llm_tokenizer_bpe(const llama_vocab & vocab): vocab(vocab) {}
  5808. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  5809. int final_prev_index = -1;
  5810. auto word_collection = bpe_gpt2_preprocess(text);
  5811. symbols_final.clear();
  5812. for (auto & word : word_collection) {
  5813. work_queue = llm_bigram_bpe::queue();
  5814. symbols.clear();
  5815. int index = 0;
  5816. size_t offset = 0;
  5817. while (offset < word.size()) {
  5818. llm_symbol sym;
  5819. size_t char_len = std::min(word.size() - offset, (size_t) ::utf8_len(word[offset]));
  5820. sym.text = word.c_str() + offset;
  5821. sym.n = char_len;
  5822. offset += sym.n;
  5823. sym.prev = index - 1;
  5824. sym.next = offset == word.size() ? -1 : index + 1;
  5825. index++;
  5826. symbols.emplace_back(sym);
  5827. }
  5828. for (size_t i = 1; i < symbols.size(); ++i) {
  5829. add_new_bigram(i - 1, i);
  5830. }
  5831. // build token(s)
  5832. while (!work_queue.empty()) {
  5833. auto bigram = work_queue.top();
  5834. work_queue.pop();
  5835. auto & left_symbol = symbols[bigram.left];
  5836. auto & right_symbol = symbols[bigram.right];
  5837. if (left_symbol.n == 0 || right_symbol.n == 0) {
  5838. continue;
  5839. }
  5840. std::string left_token = std::string(left_symbol.text, left_symbol.n);
  5841. std::string right_token = std::string(right_symbol.text, right_symbol.n);
  5842. if (left_token + right_token != bigram.text) {
  5843. continue; // Skip this bigram if it's outdated
  5844. }
  5845. // merge the right sym into the left one
  5846. left_symbol.n += right_symbol.n;
  5847. right_symbol.n = 0;
  5848. // remove the right sym from the chain
  5849. left_symbol.next = right_symbol.next;
  5850. if (right_symbol.next >= 0) {
  5851. symbols[right_symbol.next].prev = bigram.left;
  5852. }
  5853. add_new_bigram(left_symbol.prev, bigram.left); // left side of current symbol
  5854. add_new_bigram(bigram.left, left_symbol.next); // right side of current symbol
  5855. }
  5856. // add the fnished tokens to the final list keeping correct order for next and prev
  5857. for (auto & sym : symbols) {
  5858. if (sym.n > 0) {
  5859. sym.prev = final_prev_index;
  5860. sym.next = -1;
  5861. if (final_prev_index != -1) {
  5862. symbols_final[final_prev_index].next = symbols_final.size();
  5863. }
  5864. symbols_final.emplace_back(sym);
  5865. final_prev_index = symbols_final.size() - 1;
  5866. }
  5867. }
  5868. }
  5869. symbols = symbols_final;
  5870. if (!symbols.empty()) {
  5871. for (int i = 0; i != -1; i = symbols[i].next) {
  5872. auto & symbol = symbols[i];
  5873. if (symbol.n == 0) {
  5874. continue;
  5875. }
  5876. const std::string str = std::string(symbol.text, symbol.n);
  5877. const auto token = vocab.token_to_id.find(str);
  5878. if (token == vocab.token_to_id.end()) {
  5879. for (auto j = str.begin(); j != str.end(); ++j) {
  5880. std::string byte_str(1, *j);
  5881. auto token_multibyte = vocab.token_to_id.find(byte_str);
  5882. if (token_multibyte == vocab.token_to_id.end()) {
  5883. throw std::runtime_error("ERROR: byte not found in vocab");
  5884. }
  5885. output.push_back((*token_multibyte).second);
  5886. }
  5887. } else {
  5888. output.push_back((*token).second);
  5889. }
  5890. }
  5891. }
  5892. }
  5893. private:
  5894. void add_new_bigram(int left, int right) {
  5895. if (left == -1 || right == -1) {
  5896. return;
  5897. }
  5898. std::string left_token = std::string(symbols[left].text, symbols[left].n);
  5899. std::string right_token = std::string(symbols[right].text, symbols[right].n);
  5900. int rank_found = -1;
  5901. rank_found = vocab.find_bpe_rank(left_token, right_token);
  5902. if (rank_found < 0) {
  5903. return;
  5904. }
  5905. llm_bigram_bpe bigram;
  5906. bigram.left = left;
  5907. bigram.right = right;
  5908. bigram.text = left_token + right_token;
  5909. bigram.size = left_token.size() + right_token.size();
  5910. bigram.rank = rank_found;
  5911. work_queue.push(bigram);
  5912. }
  5913. std::vector<std::string> bpe_gpt2_preprocess(const std::string & text) {
  5914. std::vector<std::string> bpe_words;
  5915. std::vector<std::string> bpe_encoded_words;
  5916. std::string token = "";
  5917. // GPT2 system regex: 's|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+
  5918. bool collecting_numeric = false;
  5919. bool collecting_letter = false;
  5920. bool collecting_special = false;
  5921. bool collecting_whitespace_lookahead = false;
  5922. bool collecting = false;
  5923. std::vector<std::string> text_utf;
  5924. text_utf.reserve(text.size());
  5925. bpe_words.reserve(text.size());
  5926. bpe_encoded_words.reserve(text.size());
  5927. auto cps = codepoints_from_utf8(text);
  5928. for (size_t i = 0; i < cps.size(); ++i)
  5929. text_utf.emplace_back(codepoint_to_utf8(cps[i]));
  5930. for (int i = 0; i < (int)text_utf.size(); i++) {
  5931. const std::string & utf_char = text_utf[i];
  5932. bool split_condition = false;
  5933. int bytes_remain = text_utf.size() - i;
  5934. // forward backward lookups
  5935. const std::string & utf_char_next = (i + 1 < (int)text_utf.size()) ? text_utf[i + 1] : "";
  5936. const std::string & utf_char_next_next = (i + 2 < (int)text_utf.size()) ? text_utf[i + 2] : "";
  5937. // handling contractions
  5938. if (!split_condition && bytes_remain >= 2) {
  5939. // 's|'t|'m|'d
  5940. if (utf_char == "\'" && (utf_char_next == "s" || utf_char_next == "t" || utf_char_next == "m" || utf_char_next == "d")) {
  5941. split_condition = true;
  5942. }
  5943. if (split_condition) {
  5944. if (token.size()) {
  5945. bpe_words.emplace_back(token); // push previous content as token
  5946. }
  5947. token = utf_char + utf_char_next;
  5948. bpe_words.emplace_back(token);
  5949. token = "";
  5950. i++;
  5951. continue;
  5952. }
  5953. }
  5954. if (!split_condition && bytes_remain >= 3) {
  5955. // 're|'ve|'ll
  5956. if (utf_char == "\'" && (
  5957. (utf_char_next == "r" && utf_char_next_next == "e") ||
  5958. (utf_char_next == "v" && utf_char_next_next == "e") ||
  5959. (utf_char_next == "l" && utf_char_next_next == "l"))
  5960. ) {
  5961. split_condition = true;
  5962. }
  5963. if (split_condition) {
  5964. // current token + next token can be defined
  5965. if (token.size()) {
  5966. bpe_words.emplace_back(token); // push previous content as token
  5967. }
  5968. token = utf_char + utf_char_next + utf_char_next_next;
  5969. bpe_words.emplace_back(token); // the contraction
  5970. token = "";
  5971. i += 2;
  5972. continue;
  5973. }
  5974. }
  5975. if (!split_condition && !collecting) {
  5976. if (codepoint_type(utf_char) == CODEPOINT_TYPE_LETTER || (!token.size() && utf_char == " " && codepoint_type(utf_char_next) == CODEPOINT_TYPE_LETTER)) {
  5977. collecting_letter = true;
  5978. collecting = true;
  5979. }
  5980. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_DIGIT || (!token.size() && utf_char == " " && codepoint_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  5981. collecting_numeric = true;
  5982. collecting = true;
  5983. }
  5984. else if (
  5985. ((codepoint_type(utf_char) != CODEPOINT_TYPE_LETTER && codepoint_type(utf_char) != CODEPOINT_TYPE_DIGIT) && (codepoint_type(utf_char) != CODEPOINT_TYPE_WHITESPACE)) ||
  5986. (!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)
  5987. ) {
  5988. collecting_special = true;
  5989. collecting = true;
  5990. }
  5991. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_WHITESPACE && codepoint_type(utf_char_next) == CODEPOINT_TYPE_WHITESPACE) {
  5992. collecting_whitespace_lookahead = true;
  5993. collecting = true;
  5994. }
  5995. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_WHITESPACE) {
  5996. split_condition = true;
  5997. }
  5998. }
  5999. else if (!split_condition && collecting) {
  6000. if (collecting_letter && codepoint_type(utf_char) != CODEPOINT_TYPE_LETTER) {
  6001. split_condition = true;
  6002. }
  6003. else if (collecting_numeric && codepoint_type(utf_char) != CODEPOINT_TYPE_DIGIT) {
  6004. split_condition = true;
  6005. }
  6006. 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)) {
  6007. split_condition = true;
  6008. }
  6009. else if (collecting_whitespace_lookahead && (codepoint_type(utf_char_next) == CODEPOINT_TYPE_LETTER || codepoint_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  6010. split_condition = true;
  6011. }
  6012. }
  6013. if (utf_char_next == "") {
  6014. split_condition = true; // final
  6015. token += utf_char;
  6016. }
  6017. if (split_condition) {
  6018. if (token.size()) {
  6019. bpe_words.emplace_back(token);
  6020. }
  6021. token = utf_char;
  6022. collecting = false;
  6023. collecting_letter = false;
  6024. collecting_numeric = false;
  6025. collecting_special = false;
  6026. collecting_whitespace_lookahead = false;
  6027. }
  6028. else {
  6029. token += utf_char;
  6030. }
  6031. }
  6032. for (std::string & word : bpe_words) {
  6033. std::string encoded_token = "";
  6034. for (char & c : word) {
  6035. encoded_token += bytes_to_unicode_bpe(c);
  6036. }
  6037. bpe_encoded_words.emplace_back(encoded_token);
  6038. }
  6039. return bpe_encoded_words;
  6040. }
  6041. const llama_vocab & vocab;
  6042. std::vector<llm_symbol> symbols;
  6043. std::vector<llm_symbol> symbols_final;
  6044. llm_bigram_bpe::queue work_queue;
  6045. };
  6046. typedef enum FRAGMENT_BUFFER_VARIANT_TYPE{
  6047. FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN,
  6048. FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT
  6049. } FRAGMENT_BUFFER_VARIANT_TYPE;
  6050. struct fragment_buffer_variant{
  6051. fragment_buffer_variant(llama_vocab::id _token)
  6052. :
  6053. type(FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN),
  6054. token(_token),
  6055. raw_text(_dummy),
  6056. offset(0),
  6057. length(0){}
  6058. fragment_buffer_variant(const std::string & _raw_text, int64_t _offset, int64_t _length)
  6059. :
  6060. type(FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT),
  6061. token((llama_vocab::id)-1),
  6062. raw_text(_raw_text),
  6063. offset(_offset),
  6064. length(_length){
  6065. GGML_ASSERT( _offset >= 0 );
  6066. GGML_ASSERT( _length >= 1 );
  6067. GGML_ASSERT( offset + length <= raw_text.length() );
  6068. }
  6069. const FRAGMENT_BUFFER_VARIANT_TYPE type;
  6070. const llama_vocab::id token;
  6071. const std::string _dummy;
  6072. const std::string & raw_text;
  6073. const uint64_t offset;
  6074. const uint64_t length;
  6075. };
  6076. // #define PRETOKENIZERDEBUG
  6077. static void tokenizer_st_partition(const llama_vocab & vocab, std::forward_list<fragment_buffer_variant> & buffer)
  6078. {
  6079. // for each special token
  6080. for (const auto & st: vocab.special_tokens_cache) {
  6081. const auto & special_token = st.first;
  6082. const auto & special_id = st.second;
  6083. // for each text fragment
  6084. std::forward_list<fragment_buffer_variant>::iterator it = buffer.begin();
  6085. while (it != buffer.end()) {
  6086. auto & fragment = (*it);
  6087. // if a fragment is text ( not yet processed )
  6088. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  6089. auto * raw_text = &(fragment.raw_text);
  6090. auto raw_text_base_offset = fragment.offset;
  6091. auto raw_text_base_length = fragment.length;
  6092. // loop over the text
  6093. while (true) {
  6094. // find the first occurrence of a given special token in this fragment
  6095. // passing offset argument only limit the "search area" but match coordinates
  6096. // are still relative to the source full raw_text
  6097. auto match = raw_text->find(special_token, raw_text_base_offset);
  6098. // no occurrences found, stop processing this fragment for a given special token
  6099. if (match == std::string::npos) break;
  6100. // check if match is within bounds of offset <-> length
  6101. if (match + special_token.length() > raw_text_base_offset + raw_text_base_length) break;
  6102. #ifdef PRETOKENIZERDEBUG
  6103. 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());
  6104. #endif
  6105. auto source = std::distance(buffer.begin(), it);
  6106. // if match is further than base offset
  6107. // then we have some text to the left of it
  6108. if (match > raw_text_base_offset) {
  6109. // left
  6110. const int64_t left_reminder_offset = raw_text_base_offset + 0;
  6111. const int64_t left_reminder_length = match - raw_text_base_offset;
  6112. buffer.emplace_after(it, (*raw_text), left_reminder_offset, left_reminder_length);
  6113. #ifdef PRETOKENIZERDEBUG
  6114. 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());
  6115. #endif
  6116. it++;
  6117. }
  6118. // special token
  6119. buffer.emplace_after(it, special_id);
  6120. it++;
  6121. // right
  6122. if (match + special_token.length() < raw_text_base_offset + raw_text_base_length) {
  6123. const int64_t right_reminder_offset = match + special_token.length();
  6124. const int64_t right_reminder_length = raw_text_base_length - ((match - raw_text_base_offset) + special_token.length());
  6125. buffer.emplace_after(it, (*raw_text), right_reminder_offset, right_reminder_length);
  6126. #ifdef PRETOKENIZERDEBUG
  6127. 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());
  6128. #endif
  6129. it++;
  6130. if (source == 0) {
  6131. buffer.erase_after(buffer.before_begin());
  6132. } else {
  6133. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  6134. }
  6135. // repeat for the right side
  6136. raw_text_base_offset = right_reminder_offset;
  6137. raw_text_base_length = right_reminder_length;
  6138. #ifdef PRETOKENIZERDEBUG
  6139. 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());
  6140. #endif
  6141. } else {
  6142. if (source == 0) {
  6143. buffer.erase_after(buffer.before_begin());
  6144. } else {
  6145. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  6146. }
  6147. break;
  6148. }
  6149. }
  6150. }
  6151. it++;
  6152. }
  6153. }
  6154. }
  6155. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special) {
  6156. std::vector<llama_vocab::id> output;
  6157. // OG tokenizer behavior:
  6158. //
  6159. // tokenizer.encode('', add_bos=True) returns [1]
  6160. // tokenizer.encode('', add_bos=False) returns []
  6161. if (bos && vocab.special_bos_id != -1) {
  6162. output.push_back(vocab.special_bos_id);
  6163. }
  6164. if (raw_text.empty()) {
  6165. return output;
  6166. }
  6167. std::forward_list<fragment_buffer_variant> fragment_buffer;
  6168. fragment_buffer.emplace_front( raw_text, 0, raw_text.length() );
  6169. if (special) tokenizer_st_partition( vocab, fragment_buffer );
  6170. switch (vocab.type) {
  6171. case LLAMA_VOCAB_TYPE_SPM:
  6172. {
  6173. for (const auto & fragment: fragment_buffer)
  6174. {
  6175. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT)
  6176. {
  6177. // without adding this leading whitespace, we do not get the same results as the original tokenizer
  6178. // TODO: It's likely possible to get rid of this string copy entirely
  6179. // by modifying llm_tokenizer_x to operate with string offsets like pre-tokenizer
  6180. // and passing 'add space prefix' as bool argument
  6181. //
  6182. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  6183. if (&fragment == &fragment_buffer.front()) {
  6184. raw_text = " " + raw_text; // prefix with space if the first token is not special
  6185. }
  6186. #ifdef PRETOKENIZERDEBUG
  6187. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  6188. #endif
  6189. llm_tokenizer_spm tokenizer(vocab);
  6190. llama_escape_whitespace(raw_text);
  6191. tokenizer.tokenize(raw_text, output);
  6192. }
  6193. else // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  6194. {
  6195. output.push_back(fragment.token);
  6196. }
  6197. }
  6198. } break;
  6199. case LLAMA_VOCAB_TYPE_BPE:
  6200. {
  6201. for (const auto & fragment: fragment_buffer)
  6202. {
  6203. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT)
  6204. {
  6205. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  6206. #ifdef PRETOKENIZERDEBUG
  6207. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  6208. #endif
  6209. llm_tokenizer_bpe tokenizer(vocab);
  6210. tokenizer.tokenize(raw_text, output);
  6211. }
  6212. else // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  6213. {
  6214. output.push_back(fragment.token);
  6215. }
  6216. }
  6217. } break;
  6218. }
  6219. return output;
  6220. }
  6221. //
  6222. // grammar - internal
  6223. //
  6224. struct llama_partial_utf8 {
  6225. uint32_t value; // bit value so far (unshifted)
  6226. int n_remain; // num bytes remaining; -1 indicates invalid sequence
  6227. };
  6228. struct llama_grammar {
  6229. const std::vector<std::vector<llama_grammar_element>> rules;
  6230. std::vector<std::vector<const llama_grammar_element *>> stacks;
  6231. // buffer for partially generated UTF-8 sequence from accepted tokens
  6232. llama_partial_utf8 partial_utf8;
  6233. };
  6234. struct llama_grammar_candidate {
  6235. size_t index;
  6236. const uint32_t * code_points;
  6237. llama_partial_utf8 partial_utf8;
  6238. };
  6239. // Decodes a UTF-8 string which may end in an incomplete sequence. Adds a terminating 0 for use as
  6240. // pointer. If an invalid sequence is encountered, returns `llama_partial_utf8.n_remain == -1`.
  6241. static std::pair<std::vector<uint32_t>, llama_partial_utf8> decode_utf8(
  6242. const std::string & src,
  6243. llama_partial_utf8 partial_start) {
  6244. static const int lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 3, 4 };
  6245. const char * pos = src.c_str();
  6246. std::vector<uint32_t> code_points;
  6247. // common english strings have the same number of codepoints and bytes. `+ 1` for the terminating 0.
  6248. code_points.reserve(src.size() + 1);
  6249. uint32_t value = partial_start.value;
  6250. int n_remain = partial_start.n_remain;
  6251. // continue previous decode, if applicable
  6252. while (*pos != 0 && n_remain > 0) {
  6253. uint8_t next_byte = static_cast<uint8_t>(*pos);
  6254. if ((next_byte >> 6) != 2) {
  6255. // invalid sequence, abort
  6256. code_points.push_back(0);
  6257. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, -1 });
  6258. }
  6259. value = (value << 6) + (next_byte & 0x3F);
  6260. ++pos;
  6261. --n_remain;
  6262. }
  6263. if (partial_start.n_remain > 0 && n_remain == 0) {
  6264. code_points.push_back(value);
  6265. }
  6266. // decode any subsequent utf-8 sequences, which may end in an incomplete one
  6267. while (*pos != 0) {
  6268. uint8_t first_byte = static_cast<uint8_t>(*pos);
  6269. uint8_t highbits = first_byte >> 4;
  6270. n_remain = lookup[highbits] - 1;
  6271. if (n_remain < 0) {
  6272. // invalid sequence, abort
  6273. code_points.clear();
  6274. code_points.push_back(0);
  6275. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, n_remain });
  6276. }
  6277. uint8_t mask = (1 << (7 - n_remain)) - 1;
  6278. value = first_byte & mask;
  6279. ++pos;
  6280. while (*pos != 0 && n_remain > 0) {
  6281. value = (value << 6) + (static_cast<uint8_t>(*pos) & 0x3F);
  6282. ++pos;
  6283. --n_remain;
  6284. }
  6285. if (n_remain == 0) {
  6286. code_points.push_back(value);
  6287. }
  6288. }
  6289. code_points.push_back(0);
  6290. return std::make_pair(std::move(code_points), llama_partial_utf8{ value, n_remain });
  6291. }
  6292. // returns true iff pos points to the end of one of the definitions of a rule
  6293. static bool llama_grammar_is_end_of_sequence(const llama_grammar_element * pos) {
  6294. switch (pos->type) {
  6295. case LLAMA_GRETYPE_END: return true; // NOLINT
  6296. case LLAMA_GRETYPE_ALT: return true; // NOLINT
  6297. default: return false;
  6298. }
  6299. }
  6300. // returns true iff chr satisfies the char range at pos (regular or inverse range)
  6301. // asserts that pos is pointing to a char range element
  6302. static std::pair<bool, const llama_grammar_element *> llama_grammar_match_char(
  6303. const llama_grammar_element * pos,
  6304. const uint32_t chr) {
  6305. bool found = false;
  6306. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  6307. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT); // NOLINT
  6308. do {
  6309. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  6310. // inclusive range, e.g. [a-z]
  6311. found = found || (pos->value <= chr && chr <= pos[1].value);
  6312. pos += 2;
  6313. } else {
  6314. // exact char match, e.g. [a] or "a"
  6315. found = found || pos->value == chr;
  6316. pos += 1;
  6317. }
  6318. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  6319. return std::make_pair(found == is_positive_char, pos);
  6320. }
  6321. // returns true iff some continuation of the given partial UTF-8 sequence could satisfy the char
  6322. // range at pos (regular or inverse range)
  6323. // asserts that pos is pointing to a char range element
  6324. static bool llama_grammar_match_partial_char(
  6325. const llama_grammar_element * pos,
  6326. const llama_partial_utf8 partial_utf8) {
  6327. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  6328. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT);
  6329. uint32_t partial_value = partial_utf8.value;
  6330. int n_remain = partial_utf8.n_remain;
  6331. // invalid sequence or 7-bit char split across 2 bytes (overlong)
  6332. if (n_remain < 0 || (n_remain == 1 && partial_value < 2)) {
  6333. return false;
  6334. }
  6335. // range of possible code points this partial UTF-8 sequence could complete to
  6336. uint32_t low = partial_value << (n_remain * 6);
  6337. uint32_t high = low | ((1 << (n_remain * 6)) - 1);
  6338. if (low == 0) {
  6339. if (n_remain == 2) {
  6340. low = 1 << 11;
  6341. } else if (n_remain == 3) {
  6342. low = 1 << 16;
  6343. }
  6344. }
  6345. do {
  6346. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  6347. // inclusive range, e.g. [a-z]
  6348. if (pos->value <= high && low <= pos[1].value) {
  6349. return is_positive_char;
  6350. }
  6351. pos += 2;
  6352. } else {
  6353. // exact char match, e.g. [a] or "a"
  6354. if (low <= pos->value && pos->value <= high) {
  6355. return is_positive_char;
  6356. }
  6357. pos += 1;
  6358. }
  6359. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  6360. return !is_positive_char;
  6361. }
  6362. // transforms a grammar pushdown stack into N possible stacks, all ending
  6363. // at a character range (terminal element)
  6364. static void llama_grammar_advance_stack(
  6365. const std::vector<std::vector<llama_grammar_element>> & rules,
  6366. const std::vector<const llama_grammar_element *> & stack,
  6367. std::vector<std::vector<const llama_grammar_element *>> & new_stacks) {
  6368. if (stack.empty()) {
  6369. new_stacks.emplace_back(stack);
  6370. return;
  6371. }
  6372. const llama_grammar_element * pos = stack.back();
  6373. switch (pos->type) {
  6374. case LLAMA_GRETYPE_RULE_REF: {
  6375. const size_t rule_id = static_cast<size_t>(pos->value);
  6376. const llama_grammar_element * subpos = rules[rule_id].data();
  6377. do {
  6378. // init new stack without the top (pos)
  6379. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  6380. if (!llama_grammar_is_end_of_sequence(pos + 1)) {
  6381. // if this rule ref is followed by another element, add that to stack
  6382. new_stack.push_back(pos + 1);
  6383. }
  6384. if (!llama_grammar_is_end_of_sequence(subpos)) {
  6385. // if alternate is nonempty, add to stack
  6386. new_stack.push_back(subpos);
  6387. }
  6388. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  6389. while (!llama_grammar_is_end_of_sequence(subpos)) {
  6390. // scan to end of alternate def
  6391. subpos++;
  6392. }
  6393. if (subpos->type == LLAMA_GRETYPE_ALT) {
  6394. // there's another alternate def of this rule to process
  6395. subpos++;
  6396. } else {
  6397. break;
  6398. }
  6399. } while (true);
  6400. break;
  6401. }
  6402. case LLAMA_GRETYPE_CHAR:
  6403. case LLAMA_GRETYPE_CHAR_NOT:
  6404. new_stacks.emplace_back(stack);
  6405. break;
  6406. default:
  6407. // end of alternate (LLAMA_GRETYPE_END, LLAMA_GRETYPE_ALT) or middle of char range
  6408. // (LLAMA_GRETYPE_CHAR_ALT, LLAMA_GRETYPE_CHAR_RNG_UPPER); stack should never be left on
  6409. // those
  6410. GGML_ASSERT(false);
  6411. }
  6412. }
  6413. // takes a set of possible pushdown stacks on a grammar, which are required to
  6414. // be positioned at a character range (see `llama_grammar_advance_stack`), and
  6415. // produces the N possible stacks if the given char is accepted at those
  6416. // positions
  6417. static std::vector<std::vector<const llama_grammar_element *>> llama_grammar_accept(
  6418. const std::vector<std::vector<llama_grammar_element>> & rules,
  6419. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  6420. const uint32_t chr) {
  6421. std::vector<std::vector<const llama_grammar_element *>> new_stacks;
  6422. for (const auto & stack : stacks) {
  6423. if (stack.empty()) {
  6424. continue;
  6425. }
  6426. auto match = llama_grammar_match_char(stack.back(), chr);
  6427. if (match.first) {
  6428. const llama_grammar_element * pos = match.second;
  6429. // update top of stack to next element, if any
  6430. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  6431. if (!llama_grammar_is_end_of_sequence(pos)) {
  6432. new_stack.push_back(pos);
  6433. }
  6434. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  6435. }
  6436. }
  6437. return new_stacks;
  6438. }
  6439. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  6440. const std::vector<std::vector<llama_grammar_element>> & rules,
  6441. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  6442. const std::vector<llama_grammar_candidate> & candidates);
  6443. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates_for_stack(
  6444. const std::vector<std::vector<llama_grammar_element>> & rules,
  6445. const std::vector<const llama_grammar_element *> & stack,
  6446. const std::vector<llama_grammar_candidate> & candidates) {
  6447. std::vector<llama_grammar_candidate> rejects;
  6448. if (stack.empty()) {
  6449. for (const auto & tok : candidates) {
  6450. if (*tok.code_points != 0 || tok.partial_utf8.n_remain != 0) {
  6451. rejects.push_back(tok);
  6452. }
  6453. }
  6454. return rejects;
  6455. }
  6456. const llama_grammar_element * stack_pos = stack.back();
  6457. std::vector<llama_grammar_candidate> next_candidates;
  6458. for (const auto & tok : candidates) {
  6459. if (*tok.code_points == 0) {
  6460. // reached end of full codepoints in token, reject iff it ended in a partial sequence
  6461. // that cannot satisfy this position in grammar
  6462. if (tok.partial_utf8.n_remain != 0 &&
  6463. !llama_grammar_match_partial_char(stack_pos, tok.partial_utf8)) {
  6464. rejects.push_back(tok);
  6465. }
  6466. } else if (llama_grammar_match_char(stack_pos, *tok.code_points).first) {
  6467. next_candidates.push_back({ tok.index, tok.code_points + 1, tok.partial_utf8 });
  6468. } else {
  6469. rejects.push_back(tok);
  6470. }
  6471. }
  6472. const auto * stack_pos_after = llama_grammar_match_char(stack_pos, 0).second;
  6473. // update top of stack to next element, if any
  6474. std::vector<const llama_grammar_element *> stack_after(stack.begin(), stack.end() - 1);
  6475. if (!llama_grammar_is_end_of_sequence(stack_pos_after)) {
  6476. stack_after.push_back(stack_pos_after);
  6477. }
  6478. std::vector<std::vector<const llama_grammar_element *>> next_stacks;
  6479. llama_grammar_advance_stack(rules, stack_after, next_stacks);
  6480. auto next_rejects = llama_grammar_reject_candidates(rules, next_stacks, next_candidates);
  6481. for (const auto & tok : next_rejects) {
  6482. rejects.push_back({ tok.index, tok.code_points - 1, tok.partial_utf8 });
  6483. }
  6484. return rejects;
  6485. }
  6486. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  6487. const std::vector<std::vector<llama_grammar_element>> & rules,
  6488. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  6489. const std::vector<llama_grammar_candidate> & candidates) {
  6490. GGML_ASSERT(!stacks.empty()); // REVIEW
  6491. if (candidates.empty()) {
  6492. return std::vector<llama_grammar_candidate>();
  6493. }
  6494. auto rejects = llama_grammar_reject_candidates_for_stack(rules, stacks.front(), candidates);
  6495. for (size_t i = 1, size = stacks.size(); i < size; ++i) {
  6496. rejects = llama_grammar_reject_candidates_for_stack(rules, stacks[i], rejects);
  6497. }
  6498. return rejects;
  6499. }
  6500. //
  6501. // grammar - external
  6502. //
  6503. struct llama_grammar * llama_grammar_init(
  6504. const llama_grammar_element ** rules,
  6505. size_t n_rules,
  6506. size_t start_rule_index) {
  6507. const llama_grammar_element * pos;
  6508. // copy rule definitions into vectors
  6509. std::vector<std::vector<llama_grammar_element>> vec_rules(n_rules);
  6510. for (size_t i = 0; i < n_rules; i++) {
  6511. for (pos = rules[i]; pos->type != LLAMA_GRETYPE_END; pos++) {
  6512. vec_rules[i].push_back(*pos);
  6513. }
  6514. vec_rules[i].push_back({LLAMA_GRETYPE_END, 0});
  6515. }
  6516. // loop over alternates of start rule to build initial stacks
  6517. std::vector<std::vector<const llama_grammar_element *>> stacks;
  6518. pos = rules[start_rule_index];
  6519. do {
  6520. std::vector<const llama_grammar_element *> stack;
  6521. if (!llama_grammar_is_end_of_sequence(pos)) {
  6522. // if alternate is nonempty, add to stack
  6523. stack.push_back(pos);
  6524. }
  6525. llama_grammar_advance_stack(vec_rules, stack, stacks);
  6526. while (!llama_grammar_is_end_of_sequence(pos)) {
  6527. // scan to end of alternate def
  6528. pos++;
  6529. }
  6530. if (pos->type == LLAMA_GRETYPE_ALT) {
  6531. // there's another alternate def of this rule to process
  6532. pos++;
  6533. } else {
  6534. break;
  6535. }
  6536. } while (true);
  6537. return new llama_grammar{ std::move(vec_rules), std::move(stacks), {} };
  6538. }
  6539. void llama_grammar_free(struct llama_grammar * grammar) {
  6540. delete grammar;
  6541. }
  6542. struct llama_grammar * llama_grammar_copy(const struct llama_grammar * grammar) {
  6543. llama_grammar * result = new llama_grammar{ grammar->rules, grammar->stacks, grammar->partial_utf8 };
  6544. // redirect elements in stacks to point to new rules
  6545. for (size_t is = 0; is < result->stacks.size(); is++) {
  6546. for (size_t ie = 0; ie < result->stacks[is].size(); ie++) {
  6547. for (size_t ir0 = 0; ir0 < grammar->rules.size(); ir0++) {
  6548. for (size_t ir1 = 0; ir1 < grammar->rules[ir0].size(); ir1++) {
  6549. if (grammar->stacks[is][ie] == &grammar->rules[ir0][ir1]) {
  6550. result->stacks[is][ie] = &result->rules[ir0][ir1];
  6551. }
  6552. }
  6553. }
  6554. }
  6555. }
  6556. return result;
  6557. }
  6558. //
  6559. // sampling
  6560. //
  6561. void llama_set_rng_seed(struct llama_context * ctx, uint32_t seed) {
  6562. if (seed == LLAMA_DEFAULT_SEED) {
  6563. seed = time(NULL);
  6564. }
  6565. ctx->rng.seed(seed);
  6566. }
  6567. void llama_sample_softmax(struct llama_context * ctx, llama_token_data_array * candidates) {
  6568. GGML_ASSERT(candidates->size > 0);
  6569. const int64_t t_start_sample_us = ggml_time_us();
  6570. // Sort the logits in descending order
  6571. if (!candidates->sorted) {
  6572. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  6573. return a.logit > b.logit;
  6574. });
  6575. candidates->sorted = true;
  6576. }
  6577. float max_l = candidates->data[0].logit;
  6578. float cum_sum = 0.0f;
  6579. for (size_t i = 0; i < candidates->size; ++i) {
  6580. float p = expf(candidates->data[i].logit - max_l);
  6581. candidates->data[i].p = p;
  6582. cum_sum += p;
  6583. }
  6584. for (size_t i = 0; i < candidates->size; ++i) {
  6585. candidates->data[i].p /= cum_sum;
  6586. }
  6587. if (ctx) {
  6588. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6589. }
  6590. }
  6591. void llama_sample_top_k(struct llama_context * ctx, llama_token_data_array * candidates, int32_t k, size_t min_keep) {
  6592. const int64_t t_start_sample_us = ggml_time_us();
  6593. k = std::max(k, (int) min_keep);
  6594. k = std::min(k, (int) candidates->size);
  6595. // Sort scores in descending order
  6596. if (!candidates->sorted) {
  6597. auto comp = [](const llama_token_data & a, const llama_token_data & b) {
  6598. return a.logit > b.logit;
  6599. };
  6600. if (k == (int) candidates->size) {
  6601. std::sort(candidates->data, candidates->data + candidates->size, comp);
  6602. } else {
  6603. std::partial_sort(candidates->data, candidates->data + k, candidates->data + candidates->size, comp);
  6604. }
  6605. candidates->sorted = true;
  6606. }
  6607. candidates->size = k;
  6608. if (ctx) {
  6609. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6610. }
  6611. }
  6612. void llama_sample_top_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  6613. if (p >= 1.0f) {
  6614. return;
  6615. }
  6616. llama_sample_softmax(ctx, candidates);
  6617. const int64_t t_start_sample_us = ggml_time_us();
  6618. // Compute the cumulative probabilities
  6619. float cum_sum = 0.0f;
  6620. size_t last_idx = candidates->size;
  6621. for (size_t i = 0; i < candidates->size; ++i) {
  6622. cum_sum += candidates->data[i].p;
  6623. // Check if the running sum is at least p or if we have kept at least min_keep tokens
  6624. // we set the last index to i+1 to indicate that the current iterate should be included in the set
  6625. if (cum_sum >= p && i + 1 >= min_keep) {
  6626. last_idx = i + 1;
  6627. break;
  6628. }
  6629. }
  6630. // Resize the output vector to keep only the top-p tokens
  6631. candidates->size = last_idx;
  6632. if (ctx) {
  6633. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6634. }
  6635. }
  6636. void llama_sample_min_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  6637. if (p <= 0.0f || !candidates->size) {
  6638. return;
  6639. }
  6640. llama_sample_softmax(ctx, candidates);
  6641. const int64_t t_start_sample_us = ggml_time_us();
  6642. float scale = candidates->data[0].p; // scale by max prob
  6643. size_t i = 1; // first token always matches
  6644. for (; i < candidates->size; ++i) {
  6645. if (candidates->data[i].p < p * scale && i >= min_keep) {
  6646. break; // prob too small
  6647. }
  6648. }
  6649. // Resize the output vector to keep only the matching tokens
  6650. candidates->size = i;
  6651. if (ctx) {
  6652. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6653. }
  6654. }
  6655. void llama_sample_tail_free(struct llama_context * ctx, llama_token_data_array * candidates, float z, size_t min_keep) {
  6656. if (z >= 1.0f || candidates->size <= 2) {
  6657. return;
  6658. }
  6659. llama_sample_softmax(nullptr, candidates);
  6660. const int64_t t_start_sample_us = ggml_time_us();
  6661. // Compute the first and second derivatives
  6662. std::vector<float> first_derivatives(candidates->size - 1);
  6663. std::vector<float> second_derivatives(candidates->size - 2);
  6664. for (size_t i = 0; i < first_derivatives.size(); ++i) {
  6665. first_derivatives[i] = candidates->data[i].p - candidates->data[i + 1].p;
  6666. }
  6667. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  6668. second_derivatives[i] = first_derivatives[i] - first_derivatives[i + 1];
  6669. }
  6670. // Calculate absolute value of second derivatives
  6671. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  6672. second_derivatives[i] = std::abs(second_derivatives[i]);
  6673. }
  6674. // Normalize the second derivatives
  6675. {
  6676. const float second_derivatives_sum = std::accumulate(second_derivatives.begin(), second_derivatives.end(), 0.0f);
  6677. if (second_derivatives_sum > 1e-6f) {
  6678. for (float & value : second_derivatives) {
  6679. value /= second_derivatives_sum;
  6680. }
  6681. } else {
  6682. for (float & value : second_derivatives) {
  6683. value = 1.0f / second_derivatives.size();
  6684. }
  6685. }
  6686. }
  6687. float cum_sum = 0.0f;
  6688. size_t last_idx = candidates->size;
  6689. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  6690. cum_sum += second_derivatives[i];
  6691. // Check if the running sum is greater than z or if we have kept at least min_keep tokens
  6692. if (cum_sum > z && i >= min_keep) {
  6693. last_idx = i;
  6694. break;
  6695. }
  6696. }
  6697. // Resize the output vector to keep only the tokens above the tail location
  6698. candidates->size = last_idx;
  6699. if (ctx) {
  6700. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6701. }
  6702. }
  6703. void llama_sample_typical(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  6704. // Reference implementation:
  6705. // https://github.com/huggingface/transformers/compare/main...cimeister:typical-sampling:typical-pr
  6706. if (p >= 1.0f) {
  6707. return;
  6708. }
  6709. // Compute the softmax of logits and calculate entropy
  6710. llama_sample_softmax(nullptr, candidates);
  6711. const int64_t t_start_sample_us = ggml_time_us();
  6712. float entropy = 0.0f;
  6713. for (size_t i = 0; i < candidates->size; ++i) {
  6714. entropy += -candidates->data[i].p * logf(candidates->data[i].p);
  6715. }
  6716. // Compute the absolute difference between negative log probability and entropy for each candidate
  6717. std::vector<float> shifted_scores;
  6718. for (size_t i = 0; i < candidates->size; ++i) {
  6719. float shifted_score = fabsf(-logf(candidates->data[i].p) - entropy);
  6720. shifted_scores.push_back(shifted_score);
  6721. }
  6722. // Sort tokens based on the shifted_scores and their corresponding indices
  6723. std::vector<size_t> indices(candidates->size);
  6724. std::iota(indices.begin(), indices.end(), 0);
  6725. std::sort(indices.begin(), indices.end(), [&](size_t a, size_t b) {
  6726. return shifted_scores[a] < shifted_scores[b];
  6727. });
  6728. // Compute the cumulative probabilities
  6729. float cum_sum = 0.0f;
  6730. size_t last_idx = indices.size();
  6731. for (size_t i = 0; i < indices.size(); ++i) {
  6732. size_t idx = indices[i];
  6733. cum_sum += candidates->data[idx].p;
  6734. // Check if the running sum is greater than typical or if we have kept at least min_keep tokens
  6735. if (cum_sum > p && i >= min_keep - 1) {
  6736. last_idx = i + 1;
  6737. break;
  6738. }
  6739. }
  6740. // Resize the output vector to keep only the locally typical tokens
  6741. std::vector<llama_token_data> new_candidates;
  6742. for (size_t i = 0; i < last_idx; ++i) {
  6743. size_t idx = indices[i];
  6744. new_candidates.push_back(candidates->data[idx]);
  6745. }
  6746. // Replace the data in candidates with the new_candidates data
  6747. std::copy(new_candidates.begin(), new_candidates.end(), candidates->data);
  6748. candidates->size = new_candidates.size();
  6749. candidates->sorted = false;
  6750. if (ctx) {
  6751. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6752. }
  6753. }
  6754. void llama_sample_entropy(struct llama_context * ctx, llama_token_data_array * candidates_p, float min_temp, float max_temp, float exponent_val) {
  6755. const int64_t t_start_sample_us = ggml_time_us();
  6756. // no need to do anything if there is only one (or zero) candidates
  6757. if(candidates_p->size <= 1) {
  6758. return;
  6759. }
  6760. // Calculate maximum possible entropy
  6761. float max_entropy = -logf(1.0f / candidates_p->size);
  6762. llama_sample_softmax(nullptr, candidates_p);
  6763. // Calculate entropy of the softmax probabilities
  6764. float entropy = 0.0f;
  6765. for (size_t i = 0; i < candidates_p->size; ++i) {
  6766. float prob = candidates_p->data[i].p;
  6767. if (prob > 0.0f) { // Ensure no log(0)
  6768. entropy -= prob * logf(prob);
  6769. }
  6770. }
  6771. // Normalize the entropy (max_entropy cannot be 0 here because we checked candidates_p->size != 1 above)
  6772. float normalized_entropy = entropy / max_entropy;
  6773. // Map the normalized entropy to the desired temperature range using the power function
  6774. float dyn_temp = min_temp + (max_temp - min_temp) * powf(normalized_entropy, exponent_val);
  6775. #ifdef DEBUG
  6776. LLAMA_LOG_INFO("Your text maxtemp value is: %f\n", max_temp);
  6777. LLAMA_LOG_INFO("Entropy: %f\n", entropy);
  6778. LLAMA_LOG_INFO("Max Possible Entropy: %f\n", max_entropy);
  6779. LLAMA_LOG_INFO("Normalized Entropy: %f\n", normalized_entropy);
  6780. LLAMA_LOG_INFO("Exponent: %f\n", exponent_val);
  6781. LLAMA_LOG_INFO("Dynamic Temperature (dyn_temp): %f\n", dyn_temp);
  6782. #endif
  6783. // Apply the dynamically calculated temperature scaling
  6784. for (size_t i = 0; i < candidates_p->size; ++i) {
  6785. candidates_p->data[i].logit /= dyn_temp;
  6786. }
  6787. // Re-compute softmax probabilities after scaling logits with dynamic temperature
  6788. double max_l_double = candidates_p->data[0].logit;
  6789. double cum_sum_double = 0.0;
  6790. for (size_t i = 0; i < candidates_p->size; ++i) {
  6791. double p = exp(candidates_p->data[i].logit - max_l_double);
  6792. candidates_p->data[i].p = p; // Store the scaled probability
  6793. cum_sum_double += p;
  6794. }
  6795. for (size_t i = 0; i < candidates_p->size; ++i) {
  6796. candidates_p->data[i].p /= cum_sum_double; // Re-normalize the probabilities
  6797. }
  6798. #ifdef DEBUG
  6799. // Print the updated top 25 probabilities after temperature scaling
  6800. LLAMA_LOG_INFO("\nUpdated Top 25 Probabilities After Dynamic Temperature Scaling (in percentages):\n");
  6801. for (size_t i = 0; i < 25 && i < candidates_p->size; ++i) {
  6802. LLAMA_LOG_INFO("Token %zu: %f%%\n", i + 1, candidates_p->data[i].p * 100.0f);
  6803. }
  6804. #endif
  6805. if (ctx) {
  6806. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6807. }
  6808. }
  6809. void llama_sample_temp(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  6810. const int64_t t_start_sample_us = ggml_time_us();
  6811. for (size_t i = 0; i < candidates_p->size; ++i) {
  6812. candidates_p->data[i].logit /= temp;
  6813. }
  6814. if (ctx) {
  6815. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6816. }
  6817. }
  6818. void llama_sample_temperature(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  6819. llama_sample_temp(ctx, candidates_p, temp);
  6820. }
  6821. void llama_sample_repetition_penalties(
  6822. struct llama_context * ctx,
  6823. llama_token_data_array * candidates,
  6824. const llama_token * last_tokens,
  6825. size_t penalty_last_n,
  6826. float penalty_repeat,
  6827. float penalty_freq,
  6828. float penalty_present) {
  6829. if (penalty_last_n == 0 || (penalty_repeat == 1.0f && penalty_freq == 0.0f && penalty_present == 0.0f)) {
  6830. return;
  6831. }
  6832. const int64_t t_start_sample_us = ggml_time_us();
  6833. // Create a frequency map to count occurrences of each token in last_tokens
  6834. std::unordered_map<llama_token, int> token_count;
  6835. for (size_t i = 0; i < penalty_last_n; ++i) {
  6836. token_count[last_tokens[i]]++;
  6837. }
  6838. // Apply frequency and presence penalties to the candidates
  6839. for (size_t i = 0; i < candidates->size; ++i) {
  6840. const auto token_iter = token_count.find(candidates->data[i].id);
  6841. if (token_iter == token_count.end()) {
  6842. continue;
  6843. }
  6844. const int count = token_iter->second;
  6845. // 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.
  6846. // This is common fix for this problem, which is to multiply by the penalty instead of dividing.
  6847. if (candidates->data[i].logit <= 0) {
  6848. candidates->data[i].logit *= penalty_repeat;
  6849. } else {
  6850. candidates->data[i].logit /= penalty_repeat;
  6851. }
  6852. candidates->data[i].logit -= float(count) * penalty_freq + float(count > 0) * penalty_present;
  6853. }
  6854. candidates->sorted = false;
  6855. if (ctx) {
  6856. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6857. }
  6858. }
  6859. void llama_sample_grammar(struct llama_context * ctx, llama_token_data_array * candidates, const struct llama_grammar * grammar) {
  6860. GGML_ASSERT(ctx);
  6861. const int64_t t_start_sample_us = ggml_time_us();
  6862. bool allow_eos = false;
  6863. for (const auto & stack : grammar->stacks) {
  6864. if (stack.empty()) {
  6865. allow_eos = true;
  6866. break;
  6867. }
  6868. }
  6869. const llama_token eos = llama_token_eos(&ctx->model);
  6870. std::vector<std::pair<std::vector<uint32_t>, llama_partial_utf8>> candidates_decoded;
  6871. candidates_decoded.reserve(candidates->size);
  6872. std::vector<llama_grammar_candidate> candidates_grammar;
  6873. candidates_grammar.reserve(candidates->size);
  6874. for (size_t i = 0; i < candidates->size; ++i) {
  6875. const llama_token id = candidates->data[i].id;
  6876. const std::string piece = llama_token_to_piece(ctx, id);
  6877. if (id == eos) {
  6878. if (!allow_eos) {
  6879. candidates->data[i].logit = -INFINITY;
  6880. }
  6881. } else if (piece.empty() || piece[0] == 0) {
  6882. candidates->data[i].logit = -INFINITY;
  6883. } else {
  6884. candidates_decoded.push_back(decode_utf8(piece, grammar->partial_utf8));
  6885. candidates_grammar.push_back({ i, candidates_decoded.back().first.data(), candidates_decoded.back().second });
  6886. }
  6887. }
  6888. const auto rejects = llama_grammar_reject_candidates(grammar->rules, grammar->stacks, candidates_grammar);
  6889. for (const auto & reject : rejects) {
  6890. candidates->data[reject.index].logit = -INFINITY;
  6891. }
  6892. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6893. }
  6894. static void llama_log_softmax(float * array, size_t size) {
  6895. float max_l = *std::max_element(array, array + size);
  6896. float sum = 0.f;
  6897. for (size_t i = 0; i < size; ++i) {
  6898. float p = expf(array[i] - max_l);
  6899. sum += p;
  6900. array[i] = p;
  6901. }
  6902. for (size_t i = 0; i < size; ++i) {
  6903. array[i] = logf(array[i] / sum);
  6904. }
  6905. }
  6906. void llama_sample_apply_guidance(
  6907. struct llama_context * ctx,
  6908. float * logits,
  6909. float * logits_guidance,
  6910. float scale) {
  6911. GGML_ASSERT(ctx);
  6912. const auto t_start_sample_us = ggml_time_us();
  6913. const auto n_vocab = llama_n_vocab(llama_get_model(ctx));
  6914. llama_log_softmax(logits, n_vocab);
  6915. llama_log_softmax(logits_guidance, n_vocab);
  6916. for (int i = 0; i < n_vocab; ++i) {
  6917. auto & l = logits[i];
  6918. const auto & g = logits_guidance[i];
  6919. l = scale * (l - g) + g;
  6920. }
  6921. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6922. }
  6923. void llama_sample_classifier_free_guidance(
  6924. struct llama_context * ctx,
  6925. llama_token_data_array * candidates,
  6926. struct llama_context * guidance_ctx,
  6927. float scale) {
  6928. GGML_ASSERT(ctx);
  6929. int64_t t_start_sample_us;
  6930. t_start_sample_us = ggml_time_us();
  6931. const size_t n_vocab = llama_n_vocab(llama_get_model(ctx));
  6932. GGML_ASSERT(n_vocab == candidates->size);
  6933. GGML_ASSERT(!candidates->sorted);
  6934. std::vector<float> logits_base(n_vocab);
  6935. for (size_t i = 0; i < n_vocab; ++i) {
  6936. logits_base[i] = candidates->data[i].logit;
  6937. }
  6938. float * logits_guidance = llama_get_logits(guidance_ctx);
  6939. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6940. llama_sample_apply_guidance(ctx, logits_base.data(), logits_guidance, scale);
  6941. t_start_sample_us = ggml_time_us();
  6942. for (size_t i = 0; i < n_vocab; ++i) {
  6943. candidates->data[i].logit = logits_base[i];
  6944. }
  6945. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6946. }
  6947. llama_token llama_sample_token_mirostat(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, int32_t m, float * mu) {
  6948. GGML_ASSERT(ctx);
  6949. auto N = float(llama_n_vocab(llama_get_model(ctx)));
  6950. int64_t t_start_sample_us;
  6951. t_start_sample_us = ggml_time_us();
  6952. llama_sample_softmax(nullptr, candidates);
  6953. // Estimate s_hat using the most probable m tokens
  6954. float s_hat = 0.0;
  6955. float sum_ti_bi = 0.0;
  6956. float sum_ti_sq = 0.0;
  6957. for (size_t i = 0; i < size_t(m - 1) && i < candidates->size - 1; ++i) {
  6958. float t_i = logf(float(i + 2) / float(i + 1));
  6959. float b_i = logf(candidates->data[i].p / candidates->data[i + 1].p);
  6960. sum_ti_bi += t_i * b_i;
  6961. sum_ti_sq += t_i * t_i;
  6962. }
  6963. s_hat = sum_ti_bi / sum_ti_sq;
  6964. // Compute k from the estimated s_hat and target surprise value
  6965. float epsilon_hat = s_hat - 1;
  6966. float k = powf((epsilon_hat * powf(2, *mu)) / (1 - powf(N, -epsilon_hat)), 1 / s_hat);
  6967. // Sample the next word X using top-k sampling
  6968. llama_sample_top_k(nullptr, candidates, int(k), 1);
  6969. if (ctx) {
  6970. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6971. }
  6972. llama_token X = llama_sample_token(ctx, candidates);
  6973. t_start_sample_us = ggml_time_us();
  6974. // Compute error as the difference between observed surprise and target surprise value
  6975. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  6976. return candidate.id == X;
  6977. }));
  6978. float observed_surprise = -log2f(candidates->data[X_idx].p);
  6979. float e = observed_surprise - tau;
  6980. // Update mu using the learning rate and error
  6981. *mu = *mu - eta * e;
  6982. if (ctx) {
  6983. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6984. }
  6985. return X;
  6986. }
  6987. llama_token llama_sample_token_mirostat_v2(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, float * mu) {
  6988. int64_t t_start_sample_us;
  6989. t_start_sample_us = ggml_time_us();
  6990. llama_sample_softmax(ctx, candidates);
  6991. // Truncate the words with surprise values greater than mu
  6992. candidates->size = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  6993. return -log2f(candidate.p) > *mu;
  6994. }));
  6995. if (candidates->size == 0) {
  6996. candidates->size = 1;
  6997. }
  6998. if (ctx) {
  6999. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7000. }
  7001. // Normalize the probabilities of the remaining words
  7002. llama_sample_softmax(ctx, candidates);
  7003. // Sample the next word X from the remaining words
  7004. llama_token X = llama_sample_token(ctx, candidates);
  7005. t_start_sample_us = ggml_time_us();
  7006. // Compute error as the difference between observed surprise and target surprise value
  7007. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  7008. return candidate.id == X;
  7009. }));
  7010. float observed_surprise = -log2f(candidates->data[X_idx].p);
  7011. float e = observed_surprise - tau;
  7012. // Update mu using the learning rate and error
  7013. *mu = *mu - eta * e;
  7014. if (ctx) {
  7015. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7016. }
  7017. return X;
  7018. }
  7019. llama_token llama_sample_token_greedy(struct llama_context * ctx, llama_token_data_array * candidates) {
  7020. const int64_t t_start_sample_us = ggml_time_us();
  7021. // Find max element
  7022. auto * max_iter = std::max_element(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  7023. return a.logit < b.logit;
  7024. });
  7025. llama_token result = max_iter->id;
  7026. if (ctx) {
  7027. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7028. ctx->n_sample++;
  7029. }
  7030. return result;
  7031. }
  7032. llama_token llama_sample_token(struct llama_context * ctx, llama_token_data_array * candidates) {
  7033. GGML_ASSERT(ctx);
  7034. const int64_t t_start_sample_us = ggml_time_us();
  7035. llama_sample_softmax(nullptr, candidates);
  7036. std::vector<float> probs;
  7037. probs.reserve(candidates->size);
  7038. for (size_t i = 0; i < candidates->size; ++i) {
  7039. probs.push_back(candidates->data[i].p);
  7040. }
  7041. std::discrete_distribution<> dist(probs.begin(), probs.end());
  7042. auto & rng = ctx->rng;
  7043. int idx = dist(rng);
  7044. llama_token result = candidates->data[idx].id;
  7045. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7046. ctx->n_sample++;
  7047. return result;
  7048. }
  7049. void llama_grammar_accept_token(struct llama_context * ctx, struct llama_grammar * grammar, llama_token token) {
  7050. const int64_t t_start_sample_us = ggml_time_us();
  7051. if (token == llama_token_eos(&ctx->model)) {
  7052. for (const auto & stack : grammar->stacks) {
  7053. if (stack.empty()) {
  7054. return;
  7055. }
  7056. }
  7057. GGML_ASSERT(false);
  7058. }
  7059. const std::string piece = llama_token_to_piece(ctx, token);
  7060. // Note terminating 0 in decoded string
  7061. const auto decoded = decode_utf8(piece, grammar->partial_utf8);
  7062. const auto & code_points = decoded.first;
  7063. for (auto it = code_points.begin(), end = code_points.end() - 1; it != end; ++it) {
  7064. grammar->stacks = llama_grammar_accept(grammar->rules, grammar->stacks, *it);
  7065. }
  7066. grammar->partial_utf8 = decoded.second;
  7067. GGML_ASSERT(!grammar->stacks.empty());
  7068. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7069. }
  7070. //
  7071. // Beam search
  7072. //
  7073. struct llama_beam {
  7074. std::vector<llama_token> tokens;
  7075. float p; // Cumulative beam probability (renormalized relative to all beams)
  7076. bool eob; // Initialize end-of-beam to false. Callback sets this to true.
  7077. // Sort beams by probability. In case of ties, prefer beams at eob.
  7078. bool operator<(const llama_beam & rhs) const {
  7079. return std::make_pair(p, eob) < std::make_pair(rhs.p, rhs.eob);
  7080. }
  7081. // Shift off first n tokens and discard them.
  7082. void shift_tokens(const size_t n) {
  7083. if (n) {
  7084. std::copy(tokens.begin() + n, tokens.end(), tokens.begin());
  7085. tokens.resize(tokens.size() - n);
  7086. }
  7087. }
  7088. llama_beam_view view() const { return {tokens.data(), tokens.size(), p, eob}; }
  7089. };
  7090. // A struct for calculating logit-related info.
  7091. struct llama_logit_info {
  7092. const float * const logits;
  7093. const int n_vocab;
  7094. const float max_l;
  7095. const float normalizer;
  7096. struct sum_exp {
  7097. float max_l;
  7098. float operator()(float sum, float l) const { return sum + std::exp(l - max_l); }
  7099. };
  7100. llama_logit_info(llama_context * ctx)
  7101. : logits(llama_get_logits(ctx))
  7102. , n_vocab(llama_n_vocab(llama_get_model(ctx)))
  7103. , max_l(*std::max_element(logits, logits + n_vocab))
  7104. , normalizer(1.0f / std::accumulate(logits, logits + n_vocab, 0.0f, sum_exp{max_l}))
  7105. { }
  7106. llama_token_data get_token_data(const llama_token token_id) const {
  7107. constexpr auto p = std::numeric_limits<float>::quiet_NaN(); // never used
  7108. return {token_id, logits[token_id], p};
  7109. }
  7110. // Return top k token_data by logit.
  7111. std::vector<llama_token_data> top_k(size_t k) {
  7112. std::vector<llama_token_data> min_heap; // min-heap by logit
  7113. const llama_token k_min = std::min(static_cast<llama_token>(k), n_vocab);
  7114. min_heap.reserve(k_min);
  7115. for (llama_token token_id = 0 ; token_id < k_min ; ++token_id) {
  7116. min_heap.push_back(get_token_data(token_id));
  7117. }
  7118. auto comp = [](const llama_token_data & a, const llama_token_data & b) { return a.logit > b.logit; };
  7119. std::make_heap(min_heap.begin(), min_heap.end(), comp);
  7120. for (llama_token token_id = k_min ; token_id < n_vocab ; ++token_id) {
  7121. if (min_heap.front().logit < logits[token_id]) {
  7122. std::pop_heap(min_heap.begin(), min_heap.end(), comp);
  7123. min_heap.back().id = token_id;
  7124. min_heap.back().logit = logits[token_id];
  7125. std::push_heap(min_heap.begin(), min_heap.end(), comp);
  7126. }
  7127. }
  7128. return min_heap;
  7129. }
  7130. float probability_from_logit(float logit) const {
  7131. return normalizer * std::exp(logit - max_l);
  7132. }
  7133. };
  7134. struct llama_beam_search_data {
  7135. llama_context * ctx;
  7136. size_t n_beams;
  7137. int n_past;
  7138. int n_predict;
  7139. std::vector<llama_beam> beams;
  7140. std::vector<llama_beam> next_beams;
  7141. // Re-calculated on each loop iteration
  7142. size_t common_prefix_length;
  7143. // Used to communicate to/from callback on beams state.
  7144. std::vector<llama_beam_view> beam_views;
  7145. llama_beam_search_data(llama_context * ctx, size_t n_beams, int n_past, int n_predict)
  7146. : ctx(ctx)
  7147. , n_beams(n_beams)
  7148. , n_past(n_past)
  7149. , n_predict(n_predict)
  7150. , beam_views(n_beams) {
  7151. beams.reserve(n_beams);
  7152. next_beams.reserve(n_beams);
  7153. }
  7154. // Collapse beams to a single beam given by index.
  7155. void collapse_beams(const size_t beam_idx) {
  7156. if (0u < beam_idx) {
  7157. std::swap(beams[0], beams[beam_idx]);
  7158. }
  7159. beams.resize(1);
  7160. }
  7161. // Min-heaps are used to efficiently collect the top-k elements (k=n_beams).
  7162. // The repetitive patterns below reflect the 2 stages of heaps:
  7163. // * Gather elements until the vector is full, then call std::make_heap() on it.
  7164. // * If the heap is full and a new element is found that should be included, pop the
  7165. // least element to the back(), replace it with the new, then push it into the heap.
  7166. void fill_next_beams_by_top_probabilities(llama_beam & beam) {
  7167. // Min-heaps use a greater-than comparator.
  7168. const auto comp = [](const llama_beam & a, const llama_beam & b) { return a.p > b.p; };
  7169. if (beam.eob) {
  7170. // beam is at end-of-sentence, so just copy it to next_beams if its probability is high enough.
  7171. if (next_beams.size() < n_beams) {
  7172. next_beams.push_back(std::move(beam));
  7173. if (next_beams.size() == n_beams) {
  7174. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  7175. }
  7176. } else if (next_beams.front().p < beam.p) {
  7177. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  7178. next_beams.back() = std::move(beam);
  7179. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  7180. }
  7181. } else {
  7182. // beam is not at end-of-sentence, so branch with next top_k tokens.
  7183. if (!beam.tokens.empty()) {
  7184. llama_decode(ctx, llama_batch_get_one(beam.tokens.data(), beam.tokens.size(), n_past, 0));
  7185. }
  7186. llama_logit_info logit_info(ctx);
  7187. std::vector<llama_token_data> next_tokens = logit_info.top_k(n_beams);
  7188. size_t i=0;
  7189. if (next_beams.size() < n_beams) {
  7190. for (; next_beams.size() < n_beams ; ++i) {
  7191. llama_beam next_beam = beam;
  7192. next_beam.tokens.push_back(next_tokens[i].id);
  7193. next_beam.p *= logit_info.probability_from_logit(next_tokens[i].logit);
  7194. next_beams.push_back(std::move(next_beam));
  7195. }
  7196. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  7197. } else {
  7198. for (; next_beams.front().p == 0.0f ; ++i) {
  7199. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  7200. next_beams.back() = beam;
  7201. next_beams.back().tokens.push_back(next_tokens[i].id);
  7202. next_beams.back().p *= logit_info.probability_from_logit(next_tokens[i].logit);
  7203. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  7204. }
  7205. }
  7206. for (; i < n_beams ; ++i) {
  7207. const float next_p = beam.p * logit_info.probability_from_logit(next_tokens[i].logit);
  7208. if (next_beams.front().p < next_p) {
  7209. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  7210. next_beams.back() = beam;
  7211. next_beams.back().tokens.push_back(next_tokens[i].id);
  7212. next_beams.back().p = next_p;
  7213. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  7214. }
  7215. }
  7216. }
  7217. }
  7218. // Find common_prefix_length based on beams.
  7219. // Requires beams is not empty.
  7220. size_t find_common_prefix_length() {
  7221. size_t common_prefix_length = beams[0].tokens.size();
  7222. for (size_t i = 1 ; i < beams.size() ; ++i) {
  7223. common_prefix_length = std::min(common_prefix_length, beams[i].tokens.size());
  7224. for (size_t j = 0 ; j < common_prefix_length ; ++j) {
  7225. if (beams[0].tokens[j] != beams[i].tokens[j]) {
  7226. common_prefix_length = j;
  7227. break;
  7228. }
  7229. }
  7230. }
  7231. return common_prefix_length;
  7232. }
  7233. // Construct beams_state to send back to caller via the callback function.
  7234. // Side effect: set common_prefix_length = find_common_prefix_length();
  7235. llama_beams_state get_beams_state(const bool last_call) {
  7236. for (size_t i = 0 ; i < beams.size() ; ++i) {
  7237. beam_views[i] = beams[i].view();
  7238. }
  7239. common_prefix_length = find_common_prefix_length();
  7240. return {beam_views.data(), beams.size(), common_prefix_length, last_call};
  7241. }
  7242. // Loop:
  7243. // * while i < n_predict, AND
  7244. // * any of the beams have not yet reached end-of-beam (eob), AND
  7245. // * the highest probability beam(s) (plural in case of ties) are not at end-of-sentence
  7246. // (since all other beam probabilities can only decrease)
  7247. void loop(const llama_beam_search_callback_fn_t callback, void * const callback_data) {
  7248. beams.push_back({{}, 1.0f, false}); // Start with one empty beam w/ probability = 1.0 and !eob.
  7249. const auto not_eob = [](const llama_beam & beam) { return !beam.eob; };
  7250. for (int i = 0 ; i < n_predict && std::any_of(beams.begin(),beams.end(),not_eob) &&
  7251. !beams[top_beam_index()].eob ; ++i) {
  7252. callback(callback_data, get_beams_state(false)); // Sets common_prefix_length
  7253. update_beams_from_beam_views(); // Update values (p,eob) that callback may have changed.
  7254. if (common_prefix_length) {
  7255. llama_decode(ctx, llama_batch_get_one(beams[0].tokens.data(), common_prefix_length, n_past, 0));
  7256. n_past += common_prefix_length;
  7257. }
  7258. // Zero-out next_beam probabilities to place them last in following min-heap.
  7259. std::for_each(next_beams.begin(), next_beams.end(), [](llama_beam & beam) { beam.p = 0.0f; });
  7260. for (llama_beam & beam : beams) {
  7261. beam.shift_tokens(common_prefix_length);
  7262. fill_next_beams_by_top_probabilities(beam);
  7263. }
  7264. // next_beams become the beams of next/final iteration. Swap them to re-use memory.
  7265. beams.swap(next_beams);
  7266. renormalize_beam_probabilities(beams);
  7267. }
  7268. collapse_beams(top_beam_index());
  7269. callback(callback_data, get_beams_state(true));
  7270. }
  7271. // As beams grow, the cumulative probabilities decrease.
  7272. // Renormalize them to avoid floating point underflow.
  7273. static void renormalize_beam_probabilities(std::vector<llama_beam> & beams) {
  7274. const auto sum_p = [](float sum, llama_beam & beam) { return sum + beam.p; };
  7275. const float inv_sum = 1.0f / std::accumulate(beams.begin(), beams.end(), 0.0f, sum_p);
  7276. std::for_each(beams.begin(), beams.end(), [=](llama_beam & beam) { beam.p *= inv_sum; });
  7277. }
  7278. // Assumes beams is non-empty. Uses llama_beam::operator<() for ordering.
  7279. size_t top_beam_index() {
  7280. return std::max_element(beams.begin(), beams.end()) - beams.begin();
  7281. }
  7282. // Copy (p,eob) for each beam which may have been changed by the callback.
  7283. void update_beams_from_beam_views() {
  7284. for (size_t i = 0 ; i < beams.size() ; ++i) {
  7285. beams[i].p = beam_views[i].p;
  7286. beams[i].eob = beam_views[i].eob;
  7287. }
  7288. }
  7289. };
  7290. void llama_beam_search(llama_context * ctx,
  7291. llama_beam_search_callback_fn_t callback, void * callback_data,
  7292. size_t n_beams, int n_past, int n_predict) {
  7293. assert(ctx);
  7294. const int64_t t_start_sample_us = ggml_time_us();
  7295. llama_beam_search_data beam_search_data(ctx, n_beams, n_past, n_predict);
  7296. beam_search_data.loop(callback, callback_data);
  7297. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7298. ctx->n_sample++;
  7299. }
  7300. //
  7301. // quantization
  7302. //
  7303. struct quantize_state_internal {
  7304. const llama_model & model;
  7305. const llama_model_quantize_params * params;
  7306. int n_attention_wv = 0;
  7307. int n_ffn_down = 0;
  7308. int n_ffn_gate = 0;
  7309. int n_ffn_up = 0;
  7310. int i_attention_wv = 0;
  7311. int i_ffn_down = 0;
  7312. int i_ffn_gate = 0;
  7313. int i_ffn_up = 0;
  7314. int n_k_quantized = 0;
  7315. int n_fallback = 0;
  7316. bool has_imatrix = false;
  7317. quantize_state_internal(const llama_model & model, const llama_model_quantize_params * params)
  7318. : model(model)
  7319. , params(params)
  7320. {}
  7321. };
  7322. static void llama_convert_tensor_internal(
  7323. struct ggml_tensor * tensor, std::vector<no_init<float>> & output, std::vector<std::thread> & workers,
  7324. const size_t nelements, const int nthread
  7325. ) {
  7326. if (output.size() < nelements) {
  7327. output.resize(nelements);
  7328. }
  7329. float * f32_output = (float *) output.data();
  7330. ggml_type_traits_t qtype;
  7331. if (ggml_is_quantized(tensor->type)) {
  7332. qtype = ggml_internal_get_type_traits(tensor->type);
  7333. if (qtype.to_float == NULL) {
  7334. throw std::runtime_error(format("type %s unsupported for integer quantization: no dequantization available", ggml_type_name(tensor->type)));
  7335. }
  7336. } else if (tensor->type != GGML_TYPE_F16) {
  7337. throw std::runtime_error(format("cannot dequantize/convert tensor type %s", ggml_type_name(tensor->type)));
  7338. }
  7339. if (nthread < 2) {
  7340. if (tensor->type == GGML_TYPE_F16) {
  7341. ggml_fp16_to_fp32_row((ggml_fp16_t *)tensor->data, f32_output, nelements);
  7342. } else if (ggml_is_quantized(tensor->type)) {
  7343. qtype.to_float(tensor->data, f32_output, nelements);
  7344. } else {
  7345. GGML_ASSERT(false); // unreachable
  7346. }
  7347. return;
  7348. }
  7349. size_t block_size = tensor->type == GGML_TYPE_F16 ? 1 : (size_t)ggml_blck_size(tensor->type);
  7350. size_t block_size_bytes = ggml_type_size(tensor->type);
  7351. GGML_ASSERT(nelements % block_size == 0);
  7352. size_t nblocks = nelements / block_size;
  7353. size_t blocks_per_thread = nblocks / nthread;
  7354. size_t spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count
  7355. size_t in_buff_offs = 0;
  7356. size_t out_buff_offs = 0;
  7357. for (int tnum = 0; tnum < nthread; tnum++) {
  7358. size_t thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread
  7359. size_t thr_elems = thr_blocks * block_size; // number of elements for this thread
  7360. size_t thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread
  7361. auto compute = [qtype] (ggml_type typ, uint8_t * inbuf, float * outbuf, int nels) {
  7362. if (typ == GGML_TYPE_F16) {
  7363. ggml_fp16_to_fp32_row((ggml_fp16_t *)inbuf, outbuf, nels);
  7364. } else {
  7365. qtype.to_float(inbuf, outbuf, nels);
  7366. }
  7367. };
  7368. workers.emplace_back(compute, tensor->type, (uint8_t *) tensor->data + in_buff_offs, f32_output + out_buff_offs, thr_elems);
  7369. in_buff_offs += thr_block_bytes;
  7370. out_buff_offs += thr_elems;
  7371. }
  7372. for (auto & w : workers) { w.join(); }
  7373. workers.clear();
  7374. }
  7375. static ggml_type get_k_quant_type(quantize_state_internal & qs, ggml_type new_type, const ggml_tensor * tensor, llama_ftype ftype) {
  7376. const std::string name = ggml_get_name(tensor);
  7377. // TODO: avoid hardcoded tensor names - use the TN_* constants
  7378. const llm_arch arch = qs.model.arch;
  7379. const auto tn = LLM_TN(arch);
  7380. auto use_more_bits = [](int i_layer, int num_layers) -> bool {
  7381. return i_layer < num_layers/8 || i_layer >= 7*num_layers/8 || (i_layer - num_layers/8)%3 == 2;
  7382. };
  7383. const int n_expert = std::max(1, (int)qs.model.hparams.n_expert);
  7384. auto layer_info = [n_expert] (int i_layer, int n_layer, const char * name) {
  7385. if (n_expert > 1) {
  7386. // Believe it or not, "experts" in the FFN of Mixtral-8x7B are not consecutive, but iccasionally randomly
  7387. // sprinkled in the model. Hence, simply dividing i_ffn_down by n_expert does not work
  7388. // for getting the current layer as I initially thought, and we need to resort to parsing the
  7389. // tensor name.
  7390. n_layer /= n_expert;
  7391. if (sscanf(name, "blk.%d.", &i_layer) != 1) {
  7392. throw std::runtime_error(format("Failed to determine layer for tensor %s", name));
  7393. }
  7394. if (i_layer < 0 || i_layer >= n_layer) {
  7395. throw std::runtime_error(format("Bad layer %d for tensor %s. Must be in [0, %d)", i_layer, name, n_layer));
  7396. }
  7397. }
  7398. return std::make_pair(i_layer, n_layer);
  7399. };
  7400. if (name == tn(LLM_TENSOR_OUTPUT, "weight")) {
  7401. int nx = tensor->ne[0];
  7402. if (arch == LLM_ARCH_FALCON || nx % QK_K != 0) {
  7403. new_type = GGML_TYPE_Q8_0;
  7404. }
  7405. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS) {
  7406. new_type = GGML_TYPE_Q5_K;
  7407. }
  7408. else if (new_type != GGML_TYPE_Q8_0) {
  7409. new_type = GGML_TYPE_Q6_K;
  7410. }
  7411. } else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS) {
  7412. if (name.find("attn_v.weight") != std::string::npos) {
  7413. if (qs.model.hparams.n_gqa() >= 4 || qs.model.hparams.n_expert >= 4) new_type = GGML_TYPE_Q4_K;
  7414. else new_type = GGML_TYPE_Q2_K;
  7415. ++qs.i_attention_wv;
  7416. }
  7417. else if (name.find("ffn_down") != std::string::npos) {
  7418. if (qs.i_ffn_down < qs.n_ffn_down/8) new_type = GGML_TYPE_Q2_K;
  7419. ++qs.i_ffn_down;
  7420. }
  7421. else if (name == "token_embd.weight") new_type = GGML_TYPE_Q2_K;
  7422. } else if (name.find("attn_v.weight") != std::string::npos) {
  7423. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) {
  7424. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  7425. }
  7426. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && qs.model.hparams.n_gqa() >= 4) {
  7427. new_type = GGML_TYPE_Q4_K;
  7428. }
  7429. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  7430. new_type = qs.i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  7431. }
  7432. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  7433. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
  7434. use_more_bits(qs.i_attention_wv, qs.n_attention_wv)) new_type = GGML_TYPE_Q6_K;
  7435. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && qs.i_attention_wv < 4) new_type = GGML_TYPE_Q5_K;
  7436. else if (QK_K == 64 && (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S) &&
  7437. (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;
  7438. if (qs.model.type == MODEL_70B) {
  7439. // In the 70B model we have 8 heads sharing the same attn_v weights. As a result, the attn_v.weight tensor is
  7440. // 8x smaller compared to attn_q.weight. Hence, we can get a nice boost in quantization accuracy with
  7441. // nearly negligible increase in model size by quantizing this tensor with more bits:
  7442. if (new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K) new_type = GGML_TYPE_Q5_K;
  7443. }
  7444. if (qs.model.hparams.n_expert == 8) {
  7445. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  7446. // TODO: explore better strategies
  7447. new_type = GGML_TYPE_Q8_0;
  7448. }
  7449. ++qs.i_attention_wv;
  7450. } else if (name.find("attn_k.weight") != std::string::npos) {
  7451. if (qs.model.hparams.n_expert == 8) {
  7452. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  7453. // TODO: explore better strategies
  7454. new_type = GGML_TYPE_Q8_0;
  7455. }
  7456. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_XS) {
  7457. new_type = GGML_TYPE_Q2_K;
  7458. }
  7459. } else if (name.find("ffn_down") != std::string::npos) {
  7460. auto info = layer_info(qs.i_ffn_down, qs.n_ffn_down, name.c_str());
  7461. int i_layer = info.first, n_layer = info.second;
  7462. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  7463. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_XS) {
  7464. if (i_layer < n_layer/8) new_type = GGML_TYPE_Q4_K;
  7465. }
  7466. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  7467. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q5_K
  7468. : arch != LLM_ARCH_FALCON || use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q4_K
  7469. : GGML_TYPE_Q3_K;
  7470. }
  7471. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) {
  7472. new_type = arch == LLM_ARCH_FALCON ? GGML_TYPE_Q4_K : GGML_TYPE_Q5_K;
  7473. }
  7474. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  7475. if (arch == LLM_ARCH_FALCON) {
  7476. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q6_K :
  7477. use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  7478. } else {
  7479. if (use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  7480. }
  7481. }
  7482. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M && use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  7483. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && arch != LLM_ARCH_FALCON && i_layer < n_layer/8) {
  7484. new_type = GGML_TYPE_Q5_K;
  7485. }
  7486. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_0 || ftype == LLAMA_FTYPE_MOSTLY_Q5_0)
  7487. && qs.has_imatrix && i_layer < n_layer/8) {
  7488. // Guard against craziness in the first few ffn_down layers that can happen even with imatrix for Q4_0/Q5_0.
  7489. // We only do it when an imatrix is provided because a) we want to make sure that one can always get the
  7490. // same quantization as before imatrix stuff, and b) Q4_1/Q5_1 do go crazy on ffn_down without an imatrix.
  7491. new_type = ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ? GGML_TYPE_Q4_1 : GGML_TYPE_Q5_1;
  7492. }
  7493. ++qs.i_ffn_down;
  7494. } else if (name.find("attn_output.weight") != std::string::npos) {
  7495. if (arch != LLM_ARCH_FALCON) {
  7496. if (qs.model.hparams.n_expert == 8) {
  7497. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_XS ||
  7498. ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M ||
  7499. ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  7500. new_type = GGML_TYPE_Q5_K;
  7501. }
  7502. } else {
  7503. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K ) new_type = GGML_TYPE_Q3_K;
  7504. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) new_type = GGML_TYPE_Q4_K;
  7505. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  7506. }
  7507. } else {
  7508. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  7509. }
  7510. }
  7511. else if (name.find("attn_qkv.weight") != std::string::npos) {
  7512. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  7513. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) new_type = GGML_TYPE_Q5_K;
  7514. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) new_type = GGML_TYPE_Q6_K;
  7515. }
  7516. else if (name.find("ffn_gate") != std::string::npos) {
  7517. auto info = layer_info(qs.i_ffn_gate, qs.n_ffn_gate, name.c_str());
  7518. int i_layer = info.first, n_layer = info.second;
  7519. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_XS && !use_more_bits(i_layer, n_layer)) {
  7520. new_type = GGML_TYPE_Q2_K;
  7521. }
  7522. ++qs.i_ffn_gate;
  7523. }
  7524. else if (name.find("ffn_up") != std::string::npos) {
  7525. auto info = layer_info(qs.i_ffn_up, qs.n_ffn_up, name.c_str());
  7526. int i_layer = info.first, n_layer = info.second;
  7527. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_XS && !use_more_bits(i_layer, n_layer)) {
  7528. new_type = GGML_TYPE_Q2_K;
  7529. }
  7530. ++qs.i_ffn_up;
  7531. }
  7532. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  7533. //}
  7534. // IK: let's remove this, else Q2_K is almost the same as Q3_K_S
  7535. //else if (name.find("ffn_gate") != std::string::npos || name.find("ffn_up") != std::string::npos) {
  7536. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  7537. //}
  7538. // This can be used to reduce the size of the Q5_K_S model.
  7539. // The associated PPL increase is fully in line with the size reduction
  7540. //else {
  7541. // if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_S) new_type = GGML_TYPE_Q4_K;
  7542. //}
  7543. bool convert_incompatible_tensor = false;
  7544. if (new_type == GGML_TYPE_Q2_K || new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K ||
  7545. new_type == GGML_TYPE_Q5_K || new_type == GGML_TYPE_Q6_K ||
  7546. new_type == GGML_TYPE_IQ2_XS || new_type == GGML_TYPE_IQ2_XXS) {
  7547. int nx = tensor->ne[0];
  7548. int ny = tensor->ne[1];
  7549. if (nx % QK_K != 0) {
  7550. 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));
  7551. convert_incompatible_tensor = true;
  7552. } else {
  7553. ++qs.n_k_quantized;
  7554. }
  7555. }
  7556. if (convert_incompatible_tensor) {
  7557. switch (new_type) {
  7558. case GGML_TYPE_IQ2_XXS:
  7559. case GGML_TYPE_IQ2_XS:
  7560. case GGML_TYPE_Q2_K: new_type = GGML_TYPE_Q4_0; break;
  7561. case GGML_TYPE_Q3_K: new_type = GGML_TYPE_Q4_1; break;
  7562. case GGML_TYPE_Q4_K: new_type = GGML_TYPE_Q5_0; break;
  7563. case GGML_TYPE_Q5_K: new_type = GGML_TYPE_Q5_1; break;
  7564. case GGML_TYPE_Q6_K: new_type = GGML_TYPE_Q8_0; break;
  7565. default: throw std::runtime_error("\nUnsupported tensor size encountered\n");
  7566. }
  7567. LLAMA_LOG_WARN(" - using fallback quantization %s\n", ggml_type_name(new_type));
  7568. ++qs.n_fallback;
  7569. }
  7570. return new_type;
  7571. }
  7572. static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) {
  7573. ggml_type quantized_type;
  7574. llama_ftype ftype = params->ftype;
  7575. switch (params->ftype) {
  7576. case LLAMA_FTYPE_MOSTLY_Q4_0: quantized_type = GGML_TYPE_Q4_0; break;
  7577. case LLAMA_FTYPE_MOSTLY_Q4_1: quantized_type = GGML_TYPE_Q4_1; break;
  7578. case LLAMA_FTYPE_MOSTLY_Q5_0: quantized_type = GGML_TYPE_Q5_0; break;
  7579. case LLAMA_FTYPE_MOSTLY_Q5_1: quantized_type = GGML_TYPE_Q5_1; break;
  7580. case LLAMA_FTYPE_MOSTLY_Q8_0: quantized_type = GGML_TYPE_Q8_0; break;
  7581. case LLAMA_FTYPE_MOSTLY_F16: quantized_type = GGML_TYPE_F16; break;
  7582. case LLAMA_FTYPE_ALL_F32: quantized_type = GGML_TYPE_F32; break;
  7583. // K-quants
  7584. case LLAMA_FTYPE_MOSTLY_Q2_K_S:
  7585. case LLAMA_FTYPE_MOSTLY_Q2_K: quantized_type = GGML_TYPE_Q2_K; break;
  7586. case LLAMA_FTYPE_MOSTLY_Q3_K_XS:
  7587. case LLAMA_FTYPE_MOSTLY_Q3_K_S:
  7588. case LLAMA_FTYPE_MOSTLY_Q3_K_M:
  7589. case LLAMA_FTYPE_MOSTLY_Q3_K_L: quantized_type = GGML_TYPE_Q3_K; break;
  7590. case LLAMA_FTYPE_MOSTLY_Q4_K_S:
  7591. case LLAMA_FTYPE_MOSTLY_Q4_K_M: quantized_type = GGML_TYPE_Q4_K; break;
  7592. case LLAMA_FTYPE_MOSTLY_Q5_K_S:
  7593. case LLAMA_FTYPE_MOSTLY_Q5_K_M: quantized_type = GGML_TYPE_Q5_K; break;
  7594. case LLAMA_FTYPE_MOSTLY_Q6_K: quantized_type = GGML_TYPE_Q6_K; break;
  7595. case LLAMA_FTYPE_MOSTLY_IQ2_XXS:quantized_type = GGML_TYPE_IQ2_XXS; break;
  7596. case LLAMA_FTYPE_MOSTLY_IQ2_XS :quantized_type = GGML_TYPE_IQ2_XS; break;
  7597. default: throw std::runtime_error(format("invalid output file type %d\n", ftype));
  7598. }
  7599. int nthread = params->nthread;
  7600. if (nthread <= 0) {
  7601. nthread = std::thread::hardware_concurrency();
  7602. }
  7603. // mmap consistently increases speed Linux, and also increases speed on Windows with
  7604. // hot cache. It may cause a slowdown on macOS, possibly related to free memory.
  7605. #if defined(__linux__) || defined(_WIN32)
  7606. constexpr bool use_mmap = true;
  7607. #else
  7608. constexpr bool use_mmap = false;
  7609. #endif
  7610. llama_model_loader ml(fname_inp, use_mmap, NULL);
  7611. ml.init_mapping(false); // no prefetching?
  7612. llama_model model;
  7613. llm_load_arch(ml, model);
  7614. llm_load_hparams(ml, model);
  7615. struct quantize_state_internal qs(model, params);
  7616. if (params->only_copy) {
  7617. ftype = model.ftype;
  7618. }
  7619. const std::unordered_map<std::string, std::vector<float>> * imatrix_data = nullptr;
  7620. if (params->imatrix) {
  7621. imatrix_data = static_cast<const std::unordered_map<std::string, std::vector<float>>*>(params->imatrix);
  7622. if (imatrix_data) {
  7623. LLAMA_LOG_INFO("================================ Have weights data with %d entries\n",int(imatrix_data->size()));
  7624. qs.has_imatrix = true;
  7625. }
  7626. }
  7627. const size_t align = GGUF_DEFAULT_ALIGNMENT;
  7628. struct gguf_context * ctx_out = gguf_init_empty();
  7629. // copy the KV pairs from the input file
  7630. gguf_set_kv (ctx_out, ml.ctx_gguf);
  7631. gguf_set_val_u32(ctx_out, "general.quantization_version", GGML_QNT_VERSION);
  7632. gguf_set_val_u32(ctx_out, "general.file_type", ftype);
  7633. for (int i = 0; i < ml.n_tensors; ++i) {
  7634. struct ggml_tensor * meta = ml.get_tensor_meta(i);
  7635. const std::string name = ggml_get_name(meta);
  7636. // TODO: avoid hardcoded tensor names - use the TN_* constants
  7637. if (name.find("attn_v.weight") != std::string::npos || name.find("attn_qkv.weight") != std::string::npos) {
  7638. ++qs.n_attention_wv;
  7639. }
  7640. else if (name.find("ffn_down") != std::string::npos) {
  7641. ++qs.n_ffn_down;
  7642. }
  7643. else if (name.find("ffn_gate") != std::string::npos) {
  7644. ++qs.n_ffn_gate;
  7645. }
  7646. else if (name.find("ffn_up") != std::string::npos) {
  7647. ++qs.n_ffn_up;
  7648. }
  7649. }
  7650. if (qs.n_attention_wv != qs.n_ffn_down || (uint32_t)qs.n_attention_wv != model.hparams.n_layer) {
  7651. LLAMA_LOG_WARN("%s ============ Strange model: n_attention_wv = %d, n_ffn_down = %d, hparams.n_layer = %d\n",
  7652. __func__, qs.n_attention_wv, qs.n_ffn_down, model.hparams.n_layer);
  7653. }
  7654. size_t total_size_org = 0;
  7655. size_t total_size_new = 0;
  7656. std::vector<int64_t> hist_all(1 << 4, 0);
  7657. std::vector<std::thread> workers;
  7658. workers.reserve(nthread);
  7659. std::mutex mutex;
  7660. int idx = 0;
  7661. std::vector<no_init<uint8_t>> read_data;
  7662. std::vector<no_init<uint8_t>> work;
  7663. std::vector<no_init<float>> f32_conv_buf;
  7664. // populate the original tensors so we get an initial meta data
  7665. for (int i = 0; i < ml.n_tensors; ++i) {
  7666. struct ggml_tensor * meta = ml.get_tensor_meta(i);
  7667. gguf_add_tensor(ctx_out, meta);
  7668. }
  7669. std::ofstream fout(fname_out, std::ios::binary);
  7670. fout.exceptions(std::ofstream::failbit); // fail fast on write errors
  7671. const size_t meta_size = gguf_get_meta_size(ctx_out);
  7672. LLAMA_LOG_INFO("%s: meta size = %zu bytes\n", __func__, meta_size);
  7673. // placeholder for the meta data
  7674. ::zeros(fout, meta_size);
  7675. for (int i = 0; i < ml.n_tensors; ++i) {
  7676. struct ggml_tensor * tensor = ml.get_tensor_meta(i);
  7677. const std::string name = ggml_get_name(tensor);
  7678. if (!ml.use_mmap) {
  7679. if (read_data.size() < ggml_nbytes(tensor)) {
  7680. read_data.resize(ggml_nbytes(tensor));
  7681. }
  7682. tensor->data = read_data.data();
  7683. }
  7684. ml.load_data_for(tensor);
  7685. LLAMA_LOG_INFO("[%4d/%4d] %36s - [%s], type = %6s, ",
  7686. ++idx, ml.n_tensors,
  7687. ggml_get_name(tensor),
  7688. llama_format_tensor_shape(tensor).c_str(),
  7689. ggml_type_name(tensor->type));
  7690. // This used to be a regex, but <regex> has an extreme cost to compile times.
  7691. bool quantize = name.rfind("weight") == name.size() - 6; // ends with 'weight'?
  7692. // quantize only 2D tensors
  7693. quantize &= (ggml_n_dims(tensor) == 2);
  7694. quantize &= params->quantize_output_tensor || name != "output.weight";
  7695. quantize &= !params->only_copy;
  7696. // do not quantize expert gating tensors
  7697. quantize &= name.find("ffn_gate_inp.weight") == std::string::npos;
  7698. enum ggml_type new_type;
  7699. void * new_data;
  7700. size_t new_size;
  7701. if (quantize) {
  7702. new_type = quantized_type;
  7703. if (!params->pure) {
  7704. new_type = get_k_quant_type(qs, new_type, tensor, ftype);
  7705. }
  7706. // If we've decided to quantize to the same type the tensor is already
  7707. // in then there's nothing to do.
  7708. quantize = tensor->type != new_type;
  7709. }
  7710. if (!quantize) {
  7711. new_type = tensor->type;
  7712. new_data = tensor->data;
  7713. new_size = ggml_nbytes(tensor);
  7714. LLAMA_LOG_INFO("size = %8.3f MB\n", ggml_nbytes(tensor)/1024.0/1024.0);
  7715. } else {
  7716. const size_t nelements = ggml_nelements(tensor);
  7717. const float * imatrix = nullptr;
  7718. if (imatrix_data) {
  7719. auto it = imatrix_data->find(tensor->name);
  7720. if (it == imatrix_data->end()) {
  7721. LLAMA_LOG_INFO("\n====== %s: did not find weights for %s\n", __func__, tensor->name);
  7722. } else {
  7723. if (it->second.size() == (size_t)tensor->ne[0]) {
  7724. imatrix = it->second.data();
  7725. } else {
  7726. LLAMA_LOG_INFO("\n====== %s: imatrix size %d is different from tensor size %d for %s\n", __func__,
  7727. int(it->second.size()), int(tensor->ne[0]), tensor->name);
  7728. }
  7729. }
  7730. }
  7731. if ((new_type == GGML_TYPE_IQ2_XXS ||
  7732. new_type == GGML_TYPE_IQ2_XS ||
  7733. (new_type == GGML_TYPE_Q2_K && params->ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && strcmp(tensor->name, "token_embd.weight") != 0)) && !imatrix) {
  7734. LLAMA_LOG_ERROR("\n\n============================================================\n");
  7735. LLAMA_LOG_ERROR("Missing importance matrix for tensor %s in a very low-bit quantization\n", tensor->name);
  7736. LLAMA_LOG_ERROR("The result will be garbage, so bailing out\n");
  7737. LLAMA_LOG_ERROR("============================================================\n\n");
  7738. throw std::runtime_error(format("Missing importance matrix for tensor %s in a very low-bit quantization", tensor->name));
  7739. }
  7740. float * f32_data;
  7741. if (tensor->type == GGML_TYPE_F32) {
  7742. f32_data = (float *) tensor->data;
  7743. } else if (ggml_is_quantized(tensor->type) && !params->allow_requantize) {
  7744. throw std::runtime_error(format("requantizing from type %s is disabled", ggml_type_name(tensor->type)));
  7745. } else {
  7746. llama_convert_tensor_internal(tensor, f32_conv_buf, workers, nelements, nthread);
  7747. f32_data = (float *) f32_conv_buf.data();
  7748. }
  7749. LLAMA_LOG_INFO("quantizing to %s .. ", ggml_type_name(new_type));
  7750. fflush(stdout);
  7751. if (work.size() < nelements * 4) {
  7752. work.resize(nelements * 4); // upper bound on size
  7753. }
  7754. new_data = work.data();
  7755. std::array<int64_t, 1 << 4> hist_cur = {};
  7756. const int n_per_row = tensor->ne[0];
  7757. const int nrows = nelements / n_per_row;
  7758. static const int min_chunk_size = 32 * 512;
  7759. 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);
  7760. const int nchunk = (nelements + chunk_size - 1)/chunk_size;
  7761. const int nthread_use = nthread > 1 ? std::max(1, std::min(nthread, nchunk)) : 1;
  7762. if (nthread_use < 2) {
  7763. new_size = ggml_quantize_chunk(new_type, f32_data, new_data, 0, nrows, n_per_row, hist_cur.data(), imatrix);
  7764. } else {
  7765. int counter = 0;
  7766. new_size = 0;
  7767. auto compute = [&mutex, &counter, &hist_cur, &new_size, new_type, f32_data, new_data, chunk_size,
  7768. nrows, n_per_row, imatrix]() {
  7769. std::array<int64_t, 1 << 4> local_hist = {};
  7770. const int nrows_per_chunk = chunk_size / n_per_row;
  7771. size_t local_size = 0;
  7772. while (true) {
  7773. std::unique_lock<std::mutex> lock(mutex);
  7774. int first_row = counter; counter += nrows_per_chunk;
  7775. if (first_row >= nrows) {
  7776. if (local_size > 0) {
  7777. for (int j=0; j<int(local_hist.size()); ++j) {
  7778. hist_cur[j] += local_hist[j];
  7779. }
  7780. new_size += local_size;
  7781. }
  7782. break;
  7783. }
  7784. lock.unlock();
  7785. const int this_nrow = std::min(nrows - first_row, nrows_per_chunk);
  7786. local_size += ggml_quantize_chunk(new_type, f32_data, new_data,
  7787. first_row * n_per_row, this_nrow, n_per_row, local_hist.data(), imatrix);
  7788. }
  7789. };
  7790. for (int it = 0; it < nthread_use - 1; ++it) {
  7791. workers.emplace_back(compute);
  7792. }
  7793. compute();
  7794. for (auto & w : workers) { w.join(); }
  7795. workers.clear();
  7796. }
  7797. LLAMA_LOG_INFO("size = %8.2f MiB -> %8.2f MiB", ggml_nbytes(tensor)/1024.0/1024.0, new_size/1024.0/1024.0);
  7798. int64_t tot_count = 0;
  7799. for (size_t i = 0; i < hist_cur.size(); i++) {
  7800. hist_all[i] += hist_cur[i];
  7801. tot_count += hist_cur[i];
  7802. }
  7803. if (tot_count > 0) {
  7804. LLAMA_LOG_INFO(" | hist: ");
  7805. for (size_t i = 0; i < hist_cur.size(); i++) {
  7806. LLAMA_LOG_INFO("%5.3f ", hist_cur[i] / float(nelements));
  7807. }
  7808. }
  7809. LLAMA_LOG_INFO("\n");
  7810. }
  7811. total_size_org += ggml_nbytes(tensor);
  7812. total_size_new += new_size;
  7813. // update the gguf meta data as we go
  7814. gguf_set_tensor_type(ctx_out, name.c_str(), new_type);
  7815. gguf_set_tensor_data(ctx_out, name.c_str(), new_data, new_size);
  7816. // write tensor data + padding
  7817. fout.write((const char *) new_data, new_size);
  7818. zeros(fout, GGML_PAD(new_size, align) - new_size);
  7819. }
  7820. // go back to beginning of file and write the updated meta data
  7821. {
  7822. fout.seekp(0);
  7823. std::vector<uint8_t> data(gguf_get_meta_size(ctx_out));
  7824. gguf_get_meta_data(ctx_out, data.data());
  7825. fout.write((const char *) data.data(), data.size());
  7826. }
  7827. fout.close();
  7828. gguf_free(ctx_out);
  7829. LLAMA_LOG_INFO("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  7830. LLAMA_LOG_INFO("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  7831. // print histogram for all tensors
  7832. {
  7833. int64_t sum_all = 0;
  7834. for (size_t i = 0; i < hist_all.size(); i++) {
  7835. sum_all += hist_all[i];
  7836. }
  7837. if (sum_all > 0) {
  7838. LLAMA_LOG_INFO("%s: hist: ", __func__);
  7839. for (size_t i = 0; i < hist_all.size(); i++) {
  7840. LLAMA_LOG_INFO("%5.3f ", hist_all[i] / float(sum_all));
  7841. }
  7842. LLAMA_LOG_INFO("\n");
  7843. }
  7844. }
  7845. if (qs.n_fallback > 0) {
  7846. LLAMA_LOG_WARN("%s: WARNING: %d of %d tensor(s) incompatible with k-quants and required fallback quantization\n",
  7847. __func__, qs.n_fallback, qs.n_k_quantized + qs.n_fallback);
  7848. }
  7849. }
  7850. static int llama_apply_lora_from_file_internal(
  7851. const struct llama_model & model, const char * path_lora, float scale, const char * path_base_model, int n_threads
  7852. ) {
  7853. LLAMA_LOG_INFO("%s: applying lora adapter from '%s' - please wait ...\n", __func__, path_lora);
  7854. const int64_t t_start_lora_us = ggml_time_us();
  7855. llama_file fin(path_lora, "rb");
  7856. // verify magic and version
  7857. {
  7858. uint32_t magic = fin.read_u32();
  7859. if (magic != LLAMA_FILE_MAGIC_GGLA) {
  7860. LLAMA_LOG_ERROR("%s: bad file magic\n", __func__);
  7861. return 1;
  7862. }
  7863. uint32_t format_version = fin.read_u32();
  7864. if (format_version != 1) {
  7865. LLAMA_LOG_ERROR("%s: unsupported file version\n", __func__ );
  7866. return 1;
  7867. }
  7868. }
  7869. int32_t lora_r = fin.read_u32();
  7870. int32_t lora_alpha = fin.read_u32();
  7871. float scaling = scale * (float)lora_alpha / (float)lora_r;
  7872. LLAMA_LOG_INFO("%s: r = %d, alpha = %d, scaling = %.2f\n", __func__, lora_r, lora_alpha, scaling);
  7873. // load base model
  7874. std::unique_ptr<llama_model_loader> ml;
  7875. if (path_base_model) {
  7876. LLAMA_LOG_INFO("%s: loading base model from '%s'\n", __func__, path_base_model);
  7877. ml.reset(new llama_model_loader(path_base_model, /*use_mmap*/ true, /*kv_overrides*/ nullptr));
  7878. ml->init_mapping(/*prefetch*/ false); // no prefetching
  7879. }
  7880. struct tensor_meta {
  7881. std::string name;
  7882. ggml_type type;
  7883. int32_t ne[2];
  7884. size_t offset;
  7885. };
  7886. std::map<std::string, tensor_meta> tensor_meta_map;
  7887. // load all tensor meta
  7888. while (true) {
  7889. if (fin.tell() == fin.size) {
  7890. // eof
  7891. break;
  7892. }
  7893. int32_t n_dims;
  7894. int32_t name_len;
  7895. int32_t ftype;
  7896. fin.read_raw(&n_dims, sizeof(n_dims));
  7897. fin.read_raw(&name_len, sizeof(name_len));
  7898. fin.read_raw(&ftype, sizeof(ftype));
  7899. if (n_dims != 1 && n_dims != 2) {
  7900. LLAMA_LOG_ERROR("%s: unsupported tensor dimension %d\n", __func__, n_dims);
  7901. return 1;
  7902. }
  7903. int32_t ne[2] = { 1, 1 };
  7904. for (int i = 0; i < n_dims; ++i) {
  7905. fin.read_raw(&ne[i], sizeof(ne[i]));
  7906. }
  7907. std::string name;
  7908. {
  7909. GGML_ASSERT(name_len < GGML_MAX_NAME);
  7910. char buf[GGML_MAX_NAME];
  7911. fin.read_raw(buf, name_len);
  7912. name = std::string(buf, name_len);
  7913. }
  7914. // check for lora suffix
  7915. std::string lora_suffix;
  7916. if (name.length() > 6) {
  7917. lora_suffix = name.substr(name.length() - 6);
  7918. }
  7919. if (lora_suffix != ".loraA" && lora_suffix != ".loraB") {
  7920. LLAMA_LOG_ERROR("%s: error: '%s' is not a lora tensor\n", __func__, name.c_str());
  7921. return 1;
  7922. }
  7923. // tensor type
  7924. ggml_type wtype;
  7925. switch (ftype) {
  7926. case 0: wtype = GGML_TYPE_F32; break;
  7927. case 1: wtype = GGML_TYPE_F16; break;
  7928. default:
  7929. {
  7930. LLAMA_LOG_ERROR("%s: invalid tensor data type '%d'\n",
  7931. __func__, ftype);
  7932. return false;
  7933. }
  7934. }
  7935. // data offset
  7936. size_t offset = fin.tell();
  7937. offset = (offset + 31) & -32;
  7938. // skip tensor data
  7939. fin.seek(offset + ggml_row_size(wtype, ne[0]) * ne[1], SEEK_SET);
  7940. tensor_meta_map.emplace(name, tensor_meta{ name, wtype, { ne[0], ne[1] }, offset });
  7941. }
  7942. bool warned = false;
  7943. int n_tensors = 0;
  7944. // apply
  7945. ggml_backend_t backend_cpu = ggml_backend_cpu_init();
  7946. if (backend_cpu == nullptr) {
  7947. LLAMA_LOG_ERROR("%s: error: failed to initialize cpu backend\n", __func__);
  7948. return 1;
  7949. }
  7950. ggml_backend_cpu_set_n_threads(backend_cpu, n_threads);
  7951. std::vector<no_init<uint8_t>> read_buf;
  7952. for (const auto & it : model.tensors_by_name) {
  7953. const std::string & base_name = it.first;
  7954. ggml_tensor * model_t = it.second;
  7955. if (tensor_meta_map.find(base_name + ".loraA") == tensor_meta_map.end() ||
  7956. tensor_meta_map.find(base_name + ".loraB") == tensor_meta_map.end()) {
  7957. continue;
  7958. }
  7959. tensor_meta & metaA = tensor_meta_map.at(base_name + ".loraA");
  7960. tensor_meta & metaB = tensor_meta_map.at(base_name + ".loraB");
  7961. ggml_init_params lora_init_params = {
  7962. /* .mem_size */ ggml_tensor_overhead()*128 + ggml_graph_overhead(),
  7963. /* .mem_buffer */ nullptr,
  7964. /* .no_alloc */ true,
  7965. };
  7966. ggml_context * lora_ctx = ggml_init(lora_init_params);
  7967. if (lora_ctx == nullptr) {
  7968. LLAMA_LOG_ERROR("%s: error: failed to initialize lora context\n", __func__);
  7969. ggml_backend_free(backend_cpu);
  7970. return 1;
  7971. }
  7972. // create tensors
  7973. ggml_tensor * loraA = ggml_new_tensor_2d(lora_ctx, metaA.type, metaA.ne[0], metaA.ne[1]);
  7974. ggml_tensor * loraB = ggml_new_tensor_2d(lora_ctx, metaB.type, metaB.ne[0], metaB.ne[1]);
  7975. ggml_set_name(loraA, metaA.name.c_str());
  7976. ggml_set_name(loraB, metaB.name.c_str());
  7977. ggml_tensor * base_t;
  7978. if (ml) {
  7979. if (gguf_find_tensor(ml->ctx_gguf, base_name.c_str()) < 0) {
  7980. LLAMA_LOG_ERROR("%s: error: tensor '%s' not found in base model\n", __func__, base_name.c_str());
  7981. return 1;
  7982. }
  7983. base_t = ggml_dup_tensor(lora_ctx, ml->get_tensor_meta(base_name.c_str()));
  7984. } else {
  7985. base_t = ggml_dup_tensor(lora_ctx, model_t);
  7986. }
  7987. ggml_set_name(base_t, base_name.c_str());
  7988. // allocate in backend buffer
  7989. ggml_backend_buffer_t lora_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  7990. if (lora_buf == nullptr) {
  7991. LLAMA_LOG_ERROR("%s: error: failed to allocate lora tensors\n", __func__);
  7992. return 1;
  7993. }
  7994. // load tensor data
  7995. auto load_tensor = [&read_buf, &fin](const tensor_meta & tensor_meta, ggml_tensor * tensor) {
  7996. read_buf.resize(ggml_nbytes(tensor));
  7997. fin.seek(tensor_meta.offset, SEEK_SET);
  7998. fin.read_raw(read_buf.data(), ggml_nbytes(tensor));
  7999. ggml_backend_tensor_set(tensor, read_buf.data(), 0, read_buf.size());
  8000. };
  8001. load_tensor(metaA, loraA);
  8002. load_tensor(metaB, loraB);
  8003. // load base model tensor data
  8004. if (ml) {
  8005. ml->load_data_for(base_t);
  8006. } else {
  8007. ggml_backend_tensor_copy(model_t, base_t);
  8008. }
  8009. if (ggml_is_quantized(base_t->type) && !warned) {
  8010. LLAMA_LOG_WARN("%s: warning: using a lora adapter with a quantized model may result in poor quality, "
  8011. "use a f16 or f32 base model with --lora-base\n", __func__);
  8012. warned = true;
  8013. }
  8014. if (base_t->ne[0] != loraA->ne[1] || base_t->ne[1] != loraB->ne[1]) {
  8015. LLAMA_LOG_ERROR("%s: incompatible tensor dimensions (%" PRId64 " and %" PRId64 ");"
  8016. " are you sure that this adapter is for this model?\n", __func__, base_t->ne[0], loraA->ne[1]);
  8017. ggml_free(lora_ctx);
  8018. ggml_backend_buffer_free(lora_buf);
  8019. ggml_backend_free(backend_cpu);
  8020. return 1;
  8021. }
  8022. auto build_lora_graph = [&]() {
  8023. // w = w + BA*s
  8024. ggml_tensor * BA = ggml_mul_mat(lora_ctx, loraA, loraB);
  8025. ggml_set_name(BA, "BA");
  8026. if (scaling != 1.0f) {
  8027. BA = ggml_scale(lora_ctx, BA, scaling);
  8028. ggml_set_name(BA, "BA_scaled");
  8029. }
  8030. ggml_tensor * r;
  8031. r = ggml_add_inplace(lora_ctx, base_t, BA);
  8032. ggml_set_name(r, "r_add");
  8033. if (base_t->type != model_t->type) {
  8034. // convert the result to the model type
  8035. r = ggml_cast(lora_ctx, r, model_t->type);
  8036. ggml_set_name(r, "r_cast");
  8037. }
  8038. return r;
  8039. };
  8040. ggml_cgraph * gf = ggml_new_graph(lora_ctx);
  8041. ggml_tensor * r = build_lora_graph();
  8042. ggml_build_forward_expand(gf, r);
  8043. ggml_backend_buffer_t graph_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  8044. if (graph_buf == nullptr) {
  8045. LLAMA_LOG_ERROR("%s: error: failed to allocate graph tensors\n", __func__);
  8046. ggml_free(lora_ctx);
  8047. ggml_backend_buffer_free(lora_buf);
  8048. ggml_backend_free(backend_cpu);
  8049. return 1;
  8050. }
  8051. ggml_backend_graph_compute(backend_cpu, gf);
  8052. ggml_backend_tensor_set(model_t, r->data, 0, ggml_nbytes(r));
  8053. #if 0
  8054. // TODO: use scheduler with fallback to CPU for less copies between CPU and GPU
  8055. //ggml_backend_sched_t sched = ggml_backend_sched_new(backends.data(), backends.size(), GGML_DEFAULT_GRAPH_SIZE);
  8056. // sched compute
  8057. ggml_build_forward_expand(gf, build_graph());
  8058. ggml_backend_sched_init_measure(sched, gf);
  8059. // create the graph again, since the previous one was destroyed by the measure
  8060. ggml_graph_clear(gf);
  8061. ggml_build_forward_expand(gf, build_graph());
  8062. ggml_backend_sched_graph_compute(sched, gf);
  8063. ggml_backend_sched_free(sched);
  8064. #endif
  8065. ggml_backend_buffer_free(lora_buf);
  8066. ggml_backend_buffer_free(graph_buf);
  8067. ggml_free(lora_ctx);
  8068. n_tensors++;
  8069. if (n_tensors % 4 == 0) {
  8070. LLAMA_LOG_INFO(".");
  8071. }
  8072. }
  8073. ggml_backend_free(backend_cpu);
  8074. const int64_t t_lora_us = ggml_time_us() - t_start_lora_us;
  8075. LLAMA_LOG_INFO(" done (%.2f ms)\n", t_lora_us / 1000.0);
  8076. return 0;
  8077. }
  8078. //
  8079. // interface implementation
  8080. //
  8081. struct llama_model_params llama_model_default_params() {
  8082. struct llama_model_params result = {
  8083. /*.n_gpu_layers =*/ 0,
  8084. /*.split_mode =*/ LLAMA_SPLIT_LAYER,
  8085. /*.main_gpu =*/ 0,
  8086. /*.tensor_split =*/ nullptr,
  8087. /*.progress_callback =*/ nullptr,
  8088. /*.progress_callback_user_data =*/ nullptr,
  8089. /*.kv_overrides =*/ nullptr,
  8090. /*.vocab_only =*/ false,
  8091. /*.use_mmap =*/ true,
  8092. /*.use_mlock =*/ false,
  8093. };
  8094. #ifdef GGML_USE_METAL
  8095. // note: we usually have plenty of VRAM, so by default offload all layers to the GPU
  8096. result.n_gpu_layers = 999;
  8097. #endif
  8098. return result;
  8099. }
  8100. struct llama_context_params llama_context_default_params() {
  8101. struct llama_context_params result = {
  8102. /*.seed =*/ LLAMA_DEFAULT_SEED,
  8103. /*.n_ctx =*/ 512,
  8104. /*.n_batch =*/ 512,
  8105. /*.n_threads =*/ GGML_DEFAULT_N_THREADS, // TODO: better default
  8106. /*.n_threads_batch =*/ GGML_DEFAULT_N_THREADS,
  8107. /*.rope_scaling_type =*/ LLAMA_ROPE_SCALING_UNSPECIFIED,
  8108. /*.rope_freq_base =*/ 0.0f,
  8109. /*.rope_freq_scale =*/ 0.0f,
  8110. /*.yarn_ext_factor =*/ -1.0f,
  8111. /*.yarn_attn_factor =*/ 1.0f,
  8112. /*.yarn_beta_fast =*/ 32.0f,
  8113. /*.yarn_beta_slow =*/ 1.0f,
  8114. /*.yarn_orig_ctx =*/ 0,
  8115. /*.cb_eval =*/ nullptr,
  8116. /*.cb_eval_user_data =*/ nullptr,
  8117. /*.type_k =*/ GGML_TYPE_F16,
  8118. /*.type_v =*/ GGML_TYPE_F16,
  8119. /*.mul_mat_q =*/ true,
  8120. /*.logits_all =*/ false,
  8121. /*.embedding =*/ false,
  8122. /*.offload_kqv =*/ true,
  8123. };
  8124. return result;
  8125. }
  8126. struct llama_model_quantize_params llama_model_quantize_default_params() {
  8127. struct llama_model_quantize_params result = {
  8128. /*.nthread =*/ 0,
  8129. /*.ftype =*/ LLAMA_FTYPE_MOSTLY_Q5_1,
  8130. /*.allow_requantize =*/ false,
  8131. /*.quantize_output_tensor =*/ true,
  8132. /*.only_copy =*/ false,
  8133. /*.pure =*/ false,
  8134. /*.imatrix =*/ nullptr,
  8135. };
  8136. return result;
  8137. }
  8138. int32_t llama_max_devices(void) {
  8139. return LLAMA_MAX_DEVICES;
  8140. }
  8141. bool llama_mmap_supported(void) {
  8142. return llama_mmap::SUPPORTED;
  8143. }
  8144. bool llama_mlock_supported(void) {
  8145. return llama_mlock::SUPPORTED;
  8146. }
  8147. void llama_backend_init(bool numa) {
  8148. ggml_time_init();
  8149. // needed to initialize f16 tables
  8150. {
  8151. struct ggml_init_params params = { 0, NULL, false };
  8152. struct ggml_context * ctx = ggml_init(params);
  8153. ggml_free(ctx);
  8154. }
  8155. if (numa) {
  8156. ggml_numa_init();
  8157. }
  8158. #ifdef GGML_USE_MPI
  8159. ggml_mpi_backend_init();
  8160. #endif
  8161. }
  8162. void llama_backend_free(void) {
  8163. #ifdef GGML_USE_MPI
  8164. ggml_mpi_backend_free();
  8165. #endif
  8166. ggml_quantize_free();
  8167. }
  8168. int64_t llama_time_us(void) {
  8169. return ggml_time_us();
  8170. }
  8171. struct llama_model * llama_load_model_from_file(
  8172. const char * path_model,
  8173. struct llama_model_params params) {
  8174. ggml_time_init();
  8175. llama_model * model = new llama_model;
  8176. unsigned cur_percentage = 0;
  8177. if (params.progress_callback == NULL) {
  8178. params.progress_callback_user_data = &cur_percentage;
  8179. params.progress_callback = [](float progress, void * ctx) {
  8180. unsigned * cur_percentage_p = (unsigned *) ctx;
  8181. unsigned percentage = (unsigned) (100 * progress);
  8182. while (percentage > *cur_percentage_p) {
  8183. *cur_percentage_p = percentage;
  8184. LLAMA_LOG_INFO(".");
  8185. if (percentage >= 100) {
  8186. LLAMA_LOG_INFO("\n");
  8187. }
  8188. }
  8189. return true;
  8190. };
  8191. }
  8192. int status = llama_model_load(path_model, *model, params);
  8193. GGML_ASSERT(status <= 0);
  8194. if (status < 0) {
  8195. if (status == -1) {
  8196. LLAMA_LOG_ERROR("%s: failed to load model\n", __func__);
  8197. } else if (status == -2) {
  8198. LLAMA_LOG_INFO("%s: cancelled model load\n", __func__);
  8199. }
  8200. delete model;
  8201. return nullptr;
  8202. }
  8203. return model;
  8204. }
  8205. void llama_free_model(struct llama_model * model) {
  8206. delete model;
  8207. }
  8208. struct llama_context * llama_new_context_with_model(
  8209. struct llama_model * model,
  8210. struct llama_context_params params) {
  8211. if (!model) {
  8212. return nullptr;
  8213. }
  8214. llama_context * ctx = new llama_context(*model);
  8215. const auto & hparams = model->hparams;
  8216. auto & cparams = ctx->cparams;
  8217. cparams.n_batch = params.n_batch;
  8218. cparams.n_threads = params.n_threads;
  8219. cparams.n_threads_batch = params.n_threads_batch;
  8220. cparams.yarn_ext_factor = params.yarn_ext_factor;
  8221. cparams.yarn_attn_factor = params.yarn_attn_factor;
  8222. cparams.yarn_beta_fast = params.yarn_beta_fast;
  8223. cparams.yarn_beta_slow = params.yarn_beta_slow;
  8224. cparams.mul_mat_q = params.mul_mat_q;
  8225. cparams.offload_kqv = params.offload_kqv;
  8226. cparams.n_ctx = params.n_ctx == 0 ? hparams.n_ctx_train : params.n_ctx;
  8227. cparams.rope_freq_base = params.rope_freq_base == 0.0f ? hparams.rope_freq_base_train : params.rope_freq_base;
  8228. cparams.rope_freq_scale = params.rope_freq_scale == 0.0f ? hparams.rope_freq_scale_train : params.rope_freq_scale;
  8229. cparams.n_yarn_orig_ctx = params.yarn_orig_ctx != 0 ? params.yarn_orig_ctx :
  8230. hparams.n_yarn_orig_ctx != 0 ? hparams.n_yarn_orig_ctx :
  8231. hparams.n_ctx_train;
  8232. cparams.cb_eval = params.cb_eval;
  8233. cparams.cb_eval_user_data = params.cb_eval_user_data;
  8234. auto rope_scaling_type = params.rope_scaling_type;
  8235. if (rope_scaling_type == LLAMA_ROPE_SCALING_UNSPECIFIED) {
  8236. rope_scaling_type = hparams.rope_scaling_type_train;
  8237. }
  8238. if (rope_scaling_type == LLAMA_ROPE_SCALING_NONE) {
  8239. cparams.rope_freq_scale = 1.0f; // never scale if scaling type is none
  8240. }
  8241. if (cparams.yarn_ext_factor < 0.0f) { // negative indicates 'not set'
  8242. cparams.yarn_ext_factor = rope_scaling_type == LLAMA_ROPE_SCALING_YARN ? 1.0f : 0.0f;
  8243. }
  8244. if (params.seed == LLAMA_DEFAULT_SEED) {
  8245. params.seed = time(NULL);
  8246. }
  8247. LLAMA_LOG_INFO("%s: n_ctx = %u\n", __func__, cparams.n_ctx);
  8248. LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, cparams.rope_freq_base);
  8249. LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, cparams.rope_freq_scale);
  8250. ctx->rng = std::mt19937(params.seed);
  8251. ctx->logits_all = params.logits_all;
  8252. const ggml_type type_k = params.type_k;
  8253. const ggml_type type_v = params.type_v;
  8254. GGML_ASSERT(hparams.n_embd_head_k % ggml_blck_size(type_k) == 0);
  8255. GGML_ASSERT(hparams.n_embd_head_v % ggml_blck_size(type_v) == 0);
  8256. if (!hparams.vocab_only) {
  8257. // initialize backends
  8258. #ifdef GGML_USE_METAL
  8259. if (model->n_gpu_layers > 0) {
  8260. ctx->backend_metal = ggml_backend_metal_init();
  8261. if (ctx->backend_metal == nullptr) {
  8262. LLAMA_LOG_ERROR("%s: failed to initialize Metal backend\n", __func__);
  8263. llama_free(ctx);
  8264. return nullptr;
  8265. }
  8266. ctx->backends.push_back(ctx->backend_metal);
  8267. }
  8268. #elif defined(GGML_USE_CUBLAS)
  8269. if (model->n_gpu_layers > 0) {
  8270. // with split_mode LLAMA_SPLIT_NONE or LLAMA_SPLIT_ROW, only the main GPU backend is used
  8271. if (model->split_mode == LLAMA_SPLIT_NONE || model->split_mode == LLAMA_SPLIT_ROW) {
  8272. ggml_backend_t backend = ggml_backend_cuda_init(model->main_gpu);
  8273. if (backend == nullptr) {
  8274. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, model->main_gpu);
  8275. llama_free(ctx);
  8276. return nullptr;
  8277. }
  8278. ctx->backends.push_back(backend);
  8279. } else {
  8280. // LLAMA_SPLIT_LAYER requires a backend for each GPU
  8281. for (int device = 0; device < ggml_backend_cuda_get_device_count(); ++device) {
  8282. ggml_backend_t backend = ggml_backend_cuda_init(device);
  8283. if (backend == nullptr) {
  8284. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, device);
  8285. llama_free(ctx);
  8286. return nullptr;
  8287. }
  8288. ctx->backends.push_back(backend);
  8289. }
  8290. }
  8291. }
  8292. #endif
  8293. ctx->backend_cpu = ggml_backend_cpu_init();
  8294. if (ctx->backend_cpu == nullptr) {
  8295. LLAMA_LOG_ERROR("%s: failed to initialize CPU backend\n", __func__);
  8296. llama_free(ctx);
  8297. return nullptr;
  8298. }
  8299. ctx->backends.push_back(ctx->backend_cpu);
  8300. if (!llama_kv_cache_init(ctx->kv_self, ctx->model, type_k, type_v,
  8301. cparams.n_ctx, cparams.offload_kqv)) {
  8302. LLAMA_LOG_ERROR("%s: llama_kv_cache_init() failed for self-attention cache\n", __func__);
  8303. llama_free(ctx);
  8304. return nullptr;
  8305. }
  8306. {
  8307. size_t memory_size_k = 0;
  8308. size_t memory_size_v = 0;
  8309. for (auto & k : ctx->kv_self.k_l) {
  8310. memory_size_k += ggml_nbytes(k);
  8311. }
  8312. for (auto & v : ctx->kv_self.v_l) {
  8313. memory_size_v += ggml_nbytes(v);
  8314. }
  8315. LLAMA_LOG_INFO("%s: KV self size = %7.2f MiB, K (%s): %7.2f MiB, V (%s): %7.2f MiB\n", __func__,
  8316. (float)(memory_size_k + memory_size_v) / (1024.0f * 1024.0f),
  8317. ggml_type_name(type_k), (float)memory_size_k / (1024.0f * 1024.0f),
  8318. ggml_type_name(type_v), (float)memory_size_v / (1024.0f * 1024.0f));
  8319. }
  8320. // resized during inference, reserve maximum
  8321. ctx->logits.reserve(hparams.n_vocab*cparams.n_batch);
  8322. if (params.embedding){
  8323. ctx->embedding.resize(hparams.n_embd);
  8324. }
  8325. // graph inputs
  8326. {
  8327. ggml_init_params init_params = {
  8328. /* .mem_size */ ggml_tensor_overhead()*5,
  8329. /* .mem_buffer */ nullptr,
  8330. /* .no_alloc */ true,
  8331. };
  8332. ctx->ctx_input = ggml_init(init_params);
  8333. ctx->inp_tokens = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_I32, cparams.n_batch);
  8334. ctx->inp_embd = ggml_new_tensor_2d(ctx->ctx_input, GGML_TYPE_F32, hparams.n_embd, cparams.n_batch);
  8335. ctx->inp_pos = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_I32, cparams.n_batch);
  8336. ctx->inp_KQ_mask = ggml_new_tensor_2d(ctx->ctx_input, GGML_TYPE_F32, cparams.n_ctx, cparams.n_batch);
  8337. ctx->inp_K_shift = ggml_new_tensor_1d(ctx->ctx_input, GGML_TYPE_I32, cparams.n_ctx);
  8338. ggml_set_name(ctx->inp_tokens, "inp_tokens");
  8339. ggml_set_name(ctx->inp_embd, "inp_embd");
  8340. ggml_set_name(ctx->inp_pos, "inp_pos");
  8341. ggml_set_name(ctx->inp_KQ_mask, "inp_KQ_mask");
  8342. ggml_set_name(ctx->inp_K_shift, "inp_K_shift");
  8343. ctx->buf_input = ggml_backend_alloc_ctx_tensors_from_buft(ctx->ctx_input, llama_default_buffer_type_cpu(true));
  8344. LLAMA_LOG_INFO("%s: %10s input buffer size = %8.2f MiB\n", __func__,
  8345. ggml_backend_buffer_name(ctx->buf_input),
  8346. ggml_backend_buffer_get_size(ctx->buf_input) / 1024.0 / 1024.0);
  8347. }
  8348. // scheduler and compute buffers
  8349. {
  8350. // buffer types used for the compute buffer of each backend
  8351. std::vector<ggml_backend_buffer_type_t> backend_buft;
  8352. for (auto * backend : ctx->backends) {
  8353. if (ggml_backend_is_cpu(backend)) {
  8354. // use host buffers for the CPU backend compute buffer
  8355. backend_buft.push_back(llama_default_buffer_type_cpu(true));
  8356. } else {
  8357. backend_buft.push_back(ggml_backend_get_default_buffer_type(backend));
  8358. }
  8359. }
  8360. // buffer used to store the computation graph and the tensor meta data
  8361. ctx->buf_compute_meta.resize(ggml_tensor_overhead()*LLAMA_MAX_NODES + ggml_graph_overhead());
  8362. ctx->sched = ggml_backend_sched_new(ctx->backends.data(), backend_buft.data(), ctx->backends.size(), LLAMA_MAX_NODES);
  8363. ctx->alloc = ggml_backend_sched_get_tallocr(ctx->sched, ctx->backend_cpu);
  8364. // build worst-case graph
  8365. int n_tokens = (int)std::min(cparams.n_ctx, cparams.n_batch);
  8366. int n_past = cparams.n_ctx - n_tokens;
  8367. 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
  8368. ggml_cgraph * gf = llama_build_graph(*ctx, llama_batch_get_one(&token, n_tokens, n_past, 0));
  8369. // initialize scheduler with the worst-case graph
  8370. ggml_backend_sched_init_measure(ctx->sched, gf);
  8371. ctx->alloc = ggml_backend_sched_get_tallocr(ctx->sched, ctx->backend_cpu);
  8372. for (ggml_backend_t backend : ctx->backends) {
  8373. ggml_backend_buffer_t buf = ggml_backend_sched_get_buffer(ctx->sched, backend);
  8374. LLAMA_LOG_INFO("%s: %10s compute buffer size = %8.2f MiB\n", __func__,
  8375. ggml_backend_buffer_name(buf),
  8376. ggml_backend_buffer_get_size(buf) / 1024.0 / 1024.0);
  8377. }
  8378. // note: the number of splits during measure is higher than during inference due to the kv shift
  8379. int n_splits = ggml_backend_sched_get_n_splits(ctx->sched);
  8380. LLAMA_LOG_INFO("%s: graph splits (measure): %d\n", __func__, n_splits);
  8381. }
  8382. }
  8383. #ifdef GGML_USE_MPI
  8384. ctx->ctx_mpi = ggml_mpi_init();
  8385. if (ggml_mpi_rank(ctx->ctx_mpi) > 0) {
  8386. // Enter a blocking eval loop with dummy input, letting rank=0 drive the process
  8387. // TODO: needs fix after #3228
  8388. GGML_ASSERT(false && "not implemented");
  8389. //const std::vector<llama_token> tmp(ctx->model.hparams.n_ctx, llama_token_bos(ctx));
  8390. //while (!llama_eval(ctx, tmp.data(), tmp.size(), 0, 0)) {};
  8391. llama_backend_free();
  8392. exit(1);
  8393. }
  8394. #endif
  8395. return ctx;
  8396. }
  8397. void llama_free(struct llama_context * ctx) {
  8398. delete ctx;
  8399. }
  8400. const llama_model * llama_get_model(const struct llama_context * ctx) {
  8401. return &ctx->model;
  8402. }
  8403. uint32_t llama_n_ctx(const struct llama_context * ctx) {
  8404. return ctx->cparams.n_ctx;
  8405. }
  8406. uint32_t llama_n_batch(const struct llama_context * ctx) {
  8407. return ctx->cparams.n_batch;
  8408. }
  8409. enum llama_vocab_type llama_vocab_type(const struct llama_model * model) {
  8410. return model->vocab.type;
  8411. }
  8412. int32_t llama_n_vocab(const struct llama_model * model) {
  8413. return model->vocab.id_to_token.size();
  8414. }
  8415. int32_t llama_n_ctx_train(const struct llama_model * model) {
  8416. return model->hparams.n_ctx_train;
  8417. }
  8418. int32_t llama_n_embd(const struct llama_model * model) {
  8419. return model->hparams.n_embd;
  8420. }
  8421. float llama_rope_freq_scale_train(const struct llama_model * model) {
  8422. return model->hparams.rope_freq_scale_train;
  8423. }
  8424. int32_t llama_model_meta_val_str(const struct llama_model * model, const char * key, char * buf, size_t buf_size) {
  8425. const auto & it = model->gguf_kv.find(key);
  8426. if (it == model->gguf_kv.end()) {
  8427. if (buf_size > 0) {
  8428. buf[0] = '\0';
  8429. }
  8430. return -1;
  8431. }
  8432. return snprintf(buf, buf_size, "%s", it->second.c_str());
  8433. }
  8434. int32_t llama_model_meta_count(const struct llama_model * model) {
  8435. return (int)model->gguf_kv.size();
  8436. }
  8437. int32_t llama_model_meta_key_by_index(const struct llama_model * model, int i, char * buf, size_t buf_size) {
  8438. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  8439. if (buf_size > 0) {
  8440. buf[0] = '\0';
  8441. }
  8442. return -1;
  8443. }
  8444. auto it = model->gguf_kv.begin();
  8445. std::advance(it, i);
  8446. return snprintf(buf, buf_size, "%s", it->first.c_str());
  8447. }
  8448. int32_t llama_model_meta_val_str_by_index(const struct llama_model * model, int32_t i, char * buf, size_t buf_size) {
  8449. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  8450. if (buf_size > 0) {
  8451. buf[0] = '\0';
  8452. }
  8453. return -1;
  8454. }
  8455. auto it = model->gguf_kv.begin();
  8456. std::advance(it, i);
  8457. return snprintf(buf, buf_size, "%s", it->second.c_str());
  8458. }
  8459. int32_t llama_model_desc(const struct llama_model * model, char * buf, size_t buf_size) {
  8460. return snprintf(buf, buf_size, "%s %s %s",
  8461. llama_model_arch_name(model->arch).c_str(),
  8462. llama_model_type_name(model->type),
  8463. llama_model_ftype_name(model->ftype).c_str());
  8464. }
  8465. uint64_t llama_model_size(const struct llama_model * model) {
  8466. uint64_t size = 0;
  8467. for (const auto & it : model->tensors_by_name) {
  8468. size += ggml_nbytes(it.second);
  8469. }
  8470. return size;
  8471. }
  8472. uint64_t llama_model_n_params(const struct llama_model * model) {
  8473. uint64_t nparams = 0;
  8474. for (const auto & it : model->tensors_by_name) {
  8475. nparams += ggml_nelements(it.second);
  8476. }
  8477. return nparams;
  8478. }
  8479. struct ggml_tensor * llama_get_model_tensor(struct llama_model * model, const char * name) {
  8480. auto it = std::find_if(model->tensors_by_name.begin(), model->tensors_by_name.end(),
  8481. [name](const std::pair<std::string, struct ggml_tensor *> & it) {
  8482. return it.first == name;
  8483. });
  8484. if (it == model->tensors_by_name.end()) {
  8485. return nullptr;
  8486. }
  8487. return it->second;
  8488. }
  8489. uint32_t llama_model_quantize(
  8490. const char * fname_inp,
  8491. const char * fname_out,
  8492. const llama_model_quantize_params * params) {
  8493. try {
  8494. llama_model_quantize_internal(fname_inp, fname_out, params);
  8495. return 0;
  8496. } catch (const std::exception & err) {
  8497. LLAMA_LOG_ERROR("%s: failed to quantize: %s\n", __func__, err.what());
  8498. return 1;
  8499. }
  8500. }
  8501. 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) {
  8502. try {
  8503. return llama_apply_lora_from_file_internal(ctx->model, path_lora, scale, path_base_model, n_threads);
  8504. } catch (const std::exception & err) {
  8505. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  8506. return 1;
  8507. }
  8508. }
  8509. 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) {
  8510. try {
  8511. return llama_apply_lora_from_file_internal(*model, path_lora, scale, path_base_model, n_threads);
  8512. } catch (const std::exception & err) {
  8513. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  8514. return 1;
  8515. }
  8516. }
  8517. struct llama_kv_cache_view llama_kv_cache_view_init(const struct llama_context * ctx, int32_t n_max_seq) {
  8518. struct llama_kv_cache_view result = {
  8519. /*.n_cells = */ 0,
  8520. /*.n_max_seq = */ n_max_seq,
  8521. /*.token_count = */ 0,
  8522. /*.used_cells = */ llama_get_kv_cache_used_cells(ctx),
  8523. /*.max_contiguous = */ 0,
  8524. /*.max_contiguous_idx = */ -1,
  8525. /*.cells = */ nullptr,
  8526. /*.cells_sequences = */ nullptr,
  8527. };
  8528. return result;
  8529. }
  8530. void llama_kv_cache_view_free(struct llama_kv_cache_view * view) {
  8531. if (view->cells != nullptr) {
  8532. free(view->cells);
  8533. view->cells = nullptr;
  8534. }
  8535. if (view->cells_sequences != nullptr) {
  8536. free(view->cells_sequences);
  8537. view->cells_sequences = nullptr;
  8538. }
  8539. }
  8540. void llama_kv_cache_view_update(const struct llama_context * ctx, struct llama_kv_cache_view * view) {
  8541. if (uint32_t(view->n_cells) < ctx->kv_self.size || view->cells == nullptr) {
  8542. view->n_cells = int32_t(ctx->kv_self.size);
  8543. void * p = realloc(view->cells, sizeof(struct llama_kv_cache_view_cell) * view->n_cells);
  8544. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells");
  8545. view->cells = (struct llama_kv_cache_view_cell *)p;
  8546. p = realloc(view->cells_sequences, sizeof(llama_seq_id) * view->n_max_seq * view->n_cells);
  8547. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells sequences");
  8548. view->cells_sequences = (llama_seq_id *)p;
  8549. }
  8550. const std::vector<llama_kv_cell> & kv_cells = ctx->kv_self.cells;
  8551. llama_kv_cache_view_cell * c_curr = view->cells;
  8552. llama_seq_id * cs_curr = view->cells_sequences;
  8553. int32_t used_cells = 0;
  8554. int32_t token_count = 0;
  8555. int32_t curr_contig_idx = -1;
  8556. uint32_t max_contig = 0;
  8557. int32_t max_contig_idx = -1;
  8558. for (int32_t i = 0; i < int32_t(ctx->kv_self.size); i++, c_curr++, cs_curr += view->n_max_seq) {
  8559. const size_t curr_size = kv_cells[i].seq_id.size();
  8560. token_count += curr_size;
  8561. c_curr->pos = kv_cells[i].pos + kv_cells[i].delta;
  8562. if (curr_size > 0) {
  8563. if (curr_contig_idx >= 0 && uint32_t(i - curr_contig_idx) > max_contig) {
  8564. max_contig = i - curr_contig_idx;
  8565. max_contig_idx = curr_contig_idx;
  8566. }
  8567. curr_contig_idx = -1;
  8568. } else if (curr_contig_idx < 0) {
  8569. curr_contig_idx = i;
  8570. }
  8571. int seq_idx = 0;
  8572. for (const llama_seq_id it : kv_cells[i].seq_id) {
  8573. if (seq_idx >= view->n_max_seq) {
  8574. break;
  8575. }
  8576. cs_curr[seq_idx] = it;
  8577. seq_idx++;
  8578. }
  8579. if (seq_idx != 0) {
  8580. used_cells++;
  8581. }
  8582. for (; seq_idx < view->n_max_seq; seq_idx++) {
  8583. cs_curr[seq_idx] = -1;
  8584. }
  8585. }
  8586. if (curr_contig_idx >= 0 && kv_cells.size() - curr_contig_idx > max_contig) {
  8587. max_contig_idx = curr_contig_idx;
  8588. max_contig = kv_cells.size() - curr_contig_idx;
  8589. }
  8590. view->max_contiguous = max_contig;
  8591. view->max_contiguous_idx = max_contig_idx;
  8592. view->token_count = token_count;
  8593. view->used_cells = used_cells;
  8594. if (uint32_t(used_cells) != ctx->kv_self.used) {
  8595. LLAMA_LOG_ERROR("%s: used cells mismatch. kv_cache says %d but we calculated %d\n",
  8596. __func__, ctx->kv_self.used, used_cells);
  8597. }
  8598. }
  8599. int32_t llama_get_kv_cache_token_count(const struct llama_context * ctx) {
  8600. int result = 0;
  8601. for (uint32_t i = 0; i < ctx->kv_self.size; i++) {
  8602. result += ctx->kv_self.cells[i].seq_id.size();
  8603. }
  8604. return result;
  8605. }
  8606. int32_t llama_get_kv_cache_used_cells(const struct llama_context * ctx) {
  8607. return ctx->kv_self.used;
  8608. }
  8609. void llama_kv_cache_clear(struct llama_context * ctx) {
  8610. llama_kv_cache_clear(ctx->kv_self);
  8611. }
  8612. void llama_kv_cache_seq_rm(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
  8613. llama_kv_cache_seq_rm(ctx->kv_self, seq_id, p0, p1);
  8614. }
  8615. 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) {
  8616. if (seq_id_src == seq_id_dst) {
  8617. return;
  8618. }
  8619. llama_kv_cache_seq_cp(ctx->kv_self, seq_id_src, seq_id_dst, p0, p1);
  8620. }
  8621. void llama_kv_cache_seq_keep(struct llama_context * ctx, llama_seq_id seq_id) {
  8622. llama_kv_cache_seq_keep(ctx->kv_self, seq_id);
  8623. }
  8624. void llama_kv_cache_seq_shift(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos delta) {
  8625. if (delta == 0) {
  8626. return;
  8627. }
  8628. llama_kv_cache_seq_shift(ctx->kv_self, seq_id, p0, p1, delta);
  8629. }
  8630. void llama_kv_cache_seq_div(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) {
  8631. if (d == 1) {
  8632. return;
  8633. }
  8634. llama_kv_cache_seq_div(ctx->kv_self, seq_id, p0, p1, d);
  8635. }
  8636. // Returns the *maximum* size of the state
  8637. size_t llama_get_state_size(const struct llama_context * ctx) {
  8638. // we don't know size of rng until we actually serialize it. so reserve more than enough memory for its serialized state.
  8639. // for reference, std::mt19937(1337) serializes to 6701 bytes.
  8640. const size_t s_rng_size = sizeof(size_t);
  8641. const size_t s_rng = LLAMA_MAX_RNG_STATE;
  8642. const size_t s_logits_size = sizeof(size_t);
  8643. // assume worst case for logits although only currently set ones are serialized
  8644. const size_t s_logits = ctx->logits.capacity() * sizeof(float);
  8645. const size_t s_embedding_size = sizeof(size_t);
  8646. const size_t s_embedding = ctx->embedding.size() * sizeof(float);
  8647. const size_t s_kv_size = sizeof(size_t);
  8648. const size_t s_kv_ntok = sizeof(int);
  8649. const size_t s_kv = ctx->kv_self.total_size();
  8650. const size_t s_total = (
  8651. + s_rng_size
  8652. + s_rng
  8653. + s_logits_size
  8654. + s_logits
  8655. + s_embedding_size
  8656. + s_embedding
  8657. + s_kv_size
  8658. + s_kv_ntok
  8659. + s_kv
  8660. );
  8661. return s_total;
  8662. }
  8663. // llama_context_data
  8664. struct llama_data_context {
  8665. virtual void write(const void * src, size_t size) = 0;
  8666. virtual size_t get_size_written() = 0;
  8667. virtual ~llama_data_context() = default;
  8668. };
  8669. struct llama_data_buffer_context : llama_data_context {
  8670. uint8_t * ptr;
  8671. size_t size_written = 0;
  8672. llama_data_buffer_context(uint8_t * p) : ptr(p) {}
  8673. void write(const void * src, size_t size) override {
  8674. memcpy(ptr, src, size);
  8675. ptr += size;
  8676. size_written += size;
  8677. }
  8678. size_t get_size_written() override {
  8679. return size_written;
  8680. }
  8681. };
  8682. struct llama_data_file_context : llama_data_context {
  8683. llama_file * file;
  8684. size_t size_written = 0;
  8685. llama_data_file_context(llama_file * f) : file(f) {}
  8686. void write(const void * src, size_t size) override {
  8687. file->write_raw(src, size);
  8688. size_written += size;
  8689. }
  8690. size_t get_size_written() override {
  8691. return size_written;
  8692. }
  8693. };
  8694. /** copy state data into either a buffer or file depending on the passed in context
  8695. *
  8696. * file context:
  8697. * llama_file file("/path", "wb");
  8698. * llama_data_file_context data_ctx(&file);
  8699. * llama_copy_state_data(ctx, &data_ctx);
  8700. *
  8701. * buffer context:
  8702. * std::vector<uint8_t> buf(max_size, 0);
  8703. * llama_data_buffer_context data_ctx(&buf.data());
  8704. * llama_copy_state_data(ctx, &data_ctx);
  8705. *
  8706. */
  8707. static void llama_copy_state_data_internal(struct llama_context * ctx, llama_data_context * data_ctx) {
  8708. // copy rng
  8709. {
  8710. std::ostringstream rng_ss;
  8711. rng_ss << ctx->rng;
  8712. const std::string & rng_str = rng_ss.str();
  8713. const size_t rng_size = rng_str.size();
  8714. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  8715. data_ctx->write(&rng_size, sizeof(rng_size));
  8716. data_ctx->write(rng_str.data(), rng_size);
  8717. }
  8718. // copy logits
  8719. {
  8720. const size_t logits_size = ctx->logits.size();
  8721. data_ctx->write(&logits_size, sizeof(logits_size));
  8722. if (logits_size) {
  8723. data_ctx->write(ctx->logits.data(), logits_size * sizeof(float));
  8724. }
  8725. }
  8726. // copy embeddings
  8727. {
  8728. const size_t embedding_size = ctx->embedding.size();
  8729. data_ctx->write(&embedding_size, sizeof(embedding_size));
  8730. if (embedding_size) {
  8731. data_ctx->write(ctx->embedding.data(), embedding_size * sizeof(float));
  8732. }
  8733. }
  8734. // copy kv cache
  8735. {
  8736. const auto & kv_self = ctx->kv_self;
  8737. const auto & hparams = ctx->model.hparams;
  8738. const auto & cparams = ctx->cparams;
  8739. const auto n_layer = hparams.n_layer;
  8740. const auto n_embd_k_gqa = hparams.n_embd_k_gqa();
  8741. const auto n_embd_v_gqa = hparams.n_embd_v_gqa();
  8742. const auto n_ctx = cparams.n_ctx;
  8743. const size_t kv_buf_size = kv_self.total_size();
  8744. const uint32_t kv_head = kv_self.head;
  8745. const uint32_t kv_size = kv_self.size;
  8746. const uint32_t kv_used = kv_self.used;
  8747. data_ctx->write(&kv_buf_size, sizeof(kv_buf_size));
  8748. data_ctx->write(&kv_head, sizeof(kv_head));
  8749. data_ctx->write(&kv_size, sizeof(kv_size));
  8750. data_ctx->write(&kv_used, sizeof(kv_used));
  8751. if (kv_buf_size) {
  8752. const size_t elt_size = ggml_element_size(kv_self.k_l[0]);
  8753. std::vector<uint8_t> tmp_buf;
  8754. for (int il = 0; il < (int) n_layer; ++il) {
  8755. tmp_buf.resize(elt_size*n_embd_k_gqa*kv_head);
  8756. ggml_backend_tensor_get(kv_self.k_l[il], tmp_buf.data(), 0, tmp_buf.size());
  8757. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  8758. // v is not contiguous, copy row by row
  8759. tmp_buf.resize(elt_size*kv_head);
  8760. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  8761. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), ir*elt_size*n_ctx, tmp_buf.size());
  8762. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  8763. }
  8764. }
  8765. }
  8766. for (uint32_t i = 0; i < kv_size; ++i) {
  8767. const auto & cell = kv_self.cells[i];
  8768. const llama_pos pos = cell.pos;
  8769. const size_t seq_id_size = cell.seq_id.size();
  8770. data_ctx->write(&pos, sizeof(pos));
  8771. data_ctx->write(&seq_id_size, sizeof(seq_id_size));
  8772. for (auto seq_id : cell.seq_id) {
  8773. data_ctx->write(&seq_id, sizeof(seq_id));
  8774. }
  8775. }
  8776. }
  8777. }
  8778. size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dst) {
  8779. llama_data_buffer_context data_ctx(dst);
  8780. llama_copy_state_data_internal(ctx, &data_ctx);
  8781. return data_ctx.get_size_written();
  8782. }
  8783. // Sets the state reading from the specified source address
  8784. size_t llama_set_state_data(struct llama_context * ctx, uint8_t * src) {
  8785. uint8_t * inp = src;
  8786. // set rng
  8787. {
  8788. size_t rng_size;
  8789. memcpy(&rng_size, inp, sizeof(rng_size)); inp += sizeof(rng_size);
  8790. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  8791. std::string rng_str((char *)inp, rng_size); inp += rng_size;
  8792. std::istringstream rng_ss(rng_str);
  8793. rng_ss >> ctx->rng;
  8794. GGML_ASSERT(!rng_ss.fail());
  8795. }
  8796. // set logits
  8797. {
  8798. size_t logits_size;
  8799. memcpy(&logits_size, inp, sizeof(logits_size)); inp += sizeof(logits_size);
  8800. GGML_ASSERT(ctx->logits.capacity() >= logits_size);
  8801. if (logits_size) {
  8802. ctx->logits.resize(logits_size);
  8803. memcpy(ctx->logits.data(), inp, logits_size * sizeof(float));
  8804. inp += logits_size * sizeof(float);
  8805. }
  8806. }
  8807. // set embeddings
  8808. {
  8809. size_t embedding_size;
  8810. memcpy(&embedding_size, inp, sizeof(embedding_size)); inp += sizeof(embedding_size);
  8811. GGML_ASSERT(ctx->embedding.capacity() == embedding_size);
  8812. if (embedding_size) {
  8813. memcpy(ctx->embedding.data(), inp, embedding_size * sizeof(float));
  8814. inp += embedding_size * sizeof(float);
  8815. }
  8816. }
  8817. // set kv cache
  8818. {
  8819. const auto & kv_self = ctx->kv_self;
  8820. const auto & hparams = ctx->model.hparams;
  8821. const auto & cparams = ctx->cparams;
  8822. const int n_layer = hparams.n_layer;
  8823. const int n_embd_k_gqa = hparams.n_embd_k_gqa();
  8824. const int n_embd_v_gqa = hparams.n_embd_v_gqa();
  8825. const int n_ctx = cparams.n_ctx;
  8826. size_t kv_buf_size;
  8827. uint32_t kv_head;
  8828. uint32_t kv_size;
  8829. uint32_t kv_used;
  8830. memcpy(&kv_buf_size, inp, sizeof(kv_buf_size)); inp += sizeof(kv_buf_size);
  8831. memcpy(&kv_head, inp, sizeof(kv_head)); inp += sizeof(kv_head);
  8832. memcpy(&kv_size, inp, sizeof(kv_size)); inp += sizeof(kv_size);
  8833. memcpy(&kv_used, inp, sizeof(kv_used)); inp += sizeof(kv_used);
  8834. if (kv_buf_size) {
  8835. GGML_ASSERT(kv_self.total_size() == kv_buf_size);
  8836. const size_t elt_size = ggml_element_size(kv_self.k_l[0]);
  8837. for (int il = 0; il < (int) n_layer; ++il) {
  8838. size_t k_size = elt_size*n_embd_k_gqa*kv_head;
  8839. ggml_backend_tensor_set(kv_self.k_l[il], inp, 0, k_size);
  8840. inp += k_size;
  8841. // v is not contiguous, copy row by row
  8842. size_t v_row_size = elt_size*kv_head;
  8843. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  8844. ggml_backend_tensor_set(kv_self.v_l[il], inp, ir*elt_size*n_ctx, v_row_size);
  8845. inp += v_row_size;
  8846. }
  8847. }
  8848. }
  8849. ctx->kv_self.head = kv_head;
  8850. ctx->kv_self.size = kv_size;
  8851. ctx->kv_self.used = kv_used;
  8852. ctx->kv_self.cells.resize(kv_size);
  8853. for (uint32_t i = 0; i < kv_size; ++i) {
  8854. llama_pos pos;
  8855. size_t seq_id_size;
  8856. memcpy(&pos, inp, sizeof(pos)); inp += sizeof(pos);
  8857. memcpy(&seq_id_size, inp, sizeof(seq_id_size)); inp += sizeof(seq_id_size);
  8858. ctx->kv_self.cells[i].pos = pos;
  8859. llama_seq_id seq_id;
  8860. for (size_t j = 0; j < seq_id_size; ++j) {
  8861. memcpy(&seq_id, inp, sizeof(seq_id)); inp += sizeof(seq_id);
  8862. ctx->kv_self.cells[i].seq_id.insert(seq_id);
  8863. }
  8864. }
  8865. }
  8866. const size_t nread = inp - src;
  8867. const size_t max_size = llama_get_state_size(ctx);
  8868. GGML_ASSERT(nread <= max_size);
  8869. return nread;
  8870. }
  8871. 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) {
  8872. llama_file file(path_session, "rb");
  8873. // sanity checks
  8874. {
  8875. const uint32_t magic = file.read_u32();
  8876. const uint32_t version = file.read_u32();
  8877. if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
  8878. LLAMA_LOG_ERROR("%s : unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
  8879. return false;
  8880. }
  8881. llama_hparams session_hparams;
  8882. file.read_raw(&session_hparams, sizeof(llama_hparams));
  8883. if (session_hparams != ctx->model.hparams) {
  8884. LLAMA_LOG_INFO("%s : model hparams didn't match from session file!\n", __func__);
  8885. return false;
  8886. }
  8887. }
  8888. // load the prompt
  8889. {
  8890. const uint32_t n_token_count = file.read_u32();
  8891. if (n_token_count > n_token_capacity) {
  8892. LLAMA_LOG_ERROR("%s : token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  8893. return false;
  8894. }
  8895. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  8896. *n_token_count_out = n_token_count;
  8897. }
  8898. // restore the context state
  8899. {
  8900. const size_t n_state_size_cur = file.size - file.tell();
  8901. const size_t n_state_size_max = llama_get_state_size(ctx);
  8902. if (n_state_size_cur > n_state_size_max) {
  8903. 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);
  8904. return false;
  8905. }
  8906. std::vector<uint8_t> state_data(n_state_size_max);
  8907. file.read_raw(state_data.data(), n_state_size_cur);
  8908. llama_set_state_data(ctx, state_data.data());
  8909. }
  8910. return true;
  8911. }
  8912. 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) {
  8913. try {
  8914. return llama_load_session_file_internal(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  8915. } catch (const std::exception & err) {
  8916. LLAMA_LOG_ERROR("error loading session file: %s\n", err.what());
  8917. return false;
  8918. }
  8919. }
  8920. bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  8921. llama_file file(path_session, "wb");
  8922. file.write_u32(LLAMA_SESSION_MAGIC);
  8923. file.write_u32(LLAMA_SESSION_VERSION);
  8924. file.write_raw(&ctx->model.hparams, sizeof(llama_hparams));
  8925. // save the prompt
  8926. file.write_u32((uint32_t) n_token_count);
  8927. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  8928. // save the context state using stream saving
  8929. llama_data_file_context data_ctx(&file);
  8930. llama_copy_state_data_internal(ctx, &data_ctx);
  8931. return true;
  8932. }
  8933. int llama_eval(
  8934. struct llama_context * ctx,
  8935. llama_token * tokens,
  8936. int32_t n_tokens,
  8937. int32_t n_past) {
  8938. llama_kv_cache_seq_rm(ctx->kv_self, -1, n_past, -1);
  8939. const int ret = llama_decode_internal(*ctx, llama_batch_get_one(tokens, n_tokens, n_past, 0));
  8940. if (ret < 0) {
  8941. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  8942. }
  8943. return ret;
  8944. }
  8945. int llama_eval_embd(
  8946. struct llama_context * ctx,
  8947. float * embd,
  8948. int32_t n_tokens,
  8949. int32_t n_past) {
  8950. llama_kv_cache_seq_rm(ctx->kv_self, -1, n_past, -1);
  8951. llama_batch batch = { n_tokens, nullptr, embd, nullptr, nullptr, nullptr, nullptr, n_past, 1, 0, };
  8952. const int ret = llama_decode_internal(*ctx, batch);
  8953. if (ret < 0) {
  8954. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  8955. }
  8956. return ret;
  8957. }
  8958. void llama_set_n_threads(struct llama_context * ctx, uint32_t n_threads, uint32_t n_threads_batch) {
  8959. ctx->cparams.n_threads = n_threads;
  8960. ctx->cparams.n_threads_batch = n_threads_batch;
  8961. }
  8962. struct llama_batch llama_batch_get_one(
  8963. llama_token * tokens,
  8964. int32_t n_tokens,
  8965. llama_pos pos_0,
  8966. llama_seq_id seq_id) {
  8967. return {
  8968. /*n_tokens =*/ n_tokens,
  8969. /*tokens =*/ tokens,
  8970. /*embd =*/ nullptr,
  8971. /*pos =*/ nullptr,
  8972. /*n_seq_id =*/ nullptr,
  8973. /*seq_id =*/ nullptr,
  8974. /*logits =*/ nullptr,
  8975. /*all_pos_0 =*/ pos_0,
  8976. /*all_pos_1 =*/ 1,
  8977. /*all_seq_id =*/ seq_id,
  8978. };
  8979. }
  8980. struct llama_batch llama_batch_init(int32_t n_tokens, int32_t embd, int32_t n_seq_max) {
  8981. llama_batch batch = { 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, 0, 0, 0, };
  8982. if (embd) {
  8983. batch.embd = (float *) malloc(sizeof(float) * n_tokens * embd);
  8984. } else {
  8985. batch.token = (llama_token *) malloc(sizeof(llama_token) * n_tokens);
  8986. }
  8987. batch.pos = (llama_pos *) malloc(sizeof(llama_pos) * n_tokens);
  8988. batch.n_seq_id = (int32_t *) malloc(sizeof(int32_t) * n_tokens);
  8989. batch.seq_id = (llama_seq_id **) malloc(sizeof(llama_seq_id *) * n_tokens);
  8990. for (int i = 0; i < n_tokens; ++i) {
  8991. batch.seq_id[i] = (llama_seq_id *) malloc(sizeof(llama_seq_id) * n_seq_max);
  8992. }
  8993. batch.logits = (int8_t *) malloc(sizeof(int8_t) * n_tokens);
  8994. return batch;
  8995. }
  8996. void llama_batch_free(struct llama_batch batch) {
  8997. if (batch.token) free(batch.token);
  8998. if (batch.embd) free(batch.embd);
  8999. if (batch.pos) free(batch.pos);
  9000. if (batch.n_seq_id) free(batch.n_seq_id);
  9001. if (batch.seq_id) {
  9002. for (int i = 0; i < batch.n_tokens; ++i) {
  9003. free(batch.seq_id[i]);
  9004. }
  9005. free(batch.seq_id);
  9006. }
  9007. if (batch.logits) free(batch.logits);
  9008. }
  9009. int32_t llama_decode(
  9010. struct llama_context * ctx,
  9011. struct llama_batch batch) {
  9012. const int ret = llama_decode_internal(*ctx, batch);
  9013. if (ret < 0) {
  9014. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  9015. }
  9016. return ret;
  9017. }
  9018. float * llama_get_logits(struct llama_context * ctx) {
  9019. return ctx->logits.data();
  9020. }
  9021. float * llama_get_logits_ith(struct llama_context * ctx, int32_t i) {
  9022. assert(ctx->logits_valid.at(i));
  9023. return ctx->logits.data() + i*ctx->model.hparams.n_vocab;
  9024. }
  9025. float * llama_get_embeddings(struct llama_context * ctx) {
  9026. return ctx->embedding.data();
  9027. }
  9028. const char * llama_token_get_text(const struct llama_model * model, llama_token token) {
  9029. return model->vocab.id_to_token[token].text.c_str();
  9030. }
  9031. float llama_token_get_score(const struct llama_model * model, llama_token token) {
  9032. return model->vocab.id_to_token[token].score;
  9033. }
  9034. llama_token_type llama_token_get_type(const struct llama_model * model, llama_token token) {
  9035. return model->vocab.id_to_token[token].type;
  9036. }
  9037. llama_token llama_token_bos(const struct llama_model * model) {
  9038. return model->vocab.special_bos_id;
  9039. }
  9040. llama_token llama_token_eos(const struct llama_model * model) {
  9041. return model->vocab.special_eos_id;
  9042. }
  9043. llama_token llama_token_nl(const struct llama_model * model) {
  9044. return model->vocab.linefeed_id;
  9045. }
  9046. int32_t llama_add_bos_token(const struct llama_model * model) {
  9047. return model->vocab.special_add_bos;
  9048. }
  9049. int32_t llama_add_eos_token(const struct llama_model * model) {
  9050. return model->vocab.special_add_eos;
  9051. }
  9052. llama_token llama_token_prefix(const struct llama_model * model) {
  9053. return model->vocab.special_prefix_id;
  9054. }
  9055. llama_token llama_token_middle(const struct llama_model * model) {
  9056. return model->vocab.special_middle_id;
  9057. }
  9058. llama_token llama_token_suffix(const struct llama_model * model) {
  9059. return model->vocab.special_suffix_id;
  9060. }
  9061. llama_token llama_token_eot(const struct llama_model * model) {
  9062. return model->vocab.special_eot_id;
  9063. }
  9064. int32_t llama_tokenize(
  9065. const struct llama_model * model,
  9066. const char * text,
  9067. int32_t text_len,
  9068. llama_token * tokens,
  9069. int32_t n_max_tokens,
  9070. bool add_bos,
  9071. bool special) {
  9072. auto res = llama_tokenize_internal(model->vocab, std::string(text, text_len), add_bos, special);
  9073. if (n_max_tokens < (int) res.size()) {
  9074. // LLAMA_LOG_ERROR("%s: too many tokens\n", __func__);
  9075. return -((int) res.size());
  9076. }
  9077. for (size_t i = 0; i < res.size(); i++) {
  9078. tokens[i] = res[i];
  9079. }
  9080. return res.size();
  9081. }
  9082. static std::string llama_decode_text(const std::string & text) {
  9083. std::string decoded_text;
  9084. auto unicode_sequences = codepoints_from_utf8(text);
  9085. for (auto& unicode_sequence : unicode_sequences) {
  9086. decoded_text += unicode_to_bytes_bpe(codepoint_to_utf8(unicode_sequence));
  9087. }
  9088. return decoded_text;
  9089. }
  9090. // does not write null-terminator to buf
  9091. int32_t llama_token_to_piece(const struct llama_model * model, llama_token token, char * buf, int32_t length) {
  9092. if (0 <= token && token < llama_n_vocab(model)) {
  9093. switch (llama_vocab_get_type(model->vocab)) {
  9094. case LLAMA_VOCAB_TYPE_SPM: {
  9095. // NOTE: we accept all unsupported token types,
  9096. // suppressing them like CONTROL tokens.
  9097. if (llama_is_normal_token(model->vocab, token)) {
  9098. std::string result = model->vocab.id_to_token[token].text;
  9099. llama_unescape_whitespace(result);
  9100. if (length < (int) result.length()) {
  9101. return -(int) result.length();
  9102. }
  9103. memcpy(buf, result.c_str(), result.length());
  9104. return result.length();
  9105. } else if (llama_is_user_defined_token(model->vocab, token)) {
  9106. std::string result = model->vocab.id_to_token[token].text;
  9107. if (length < (int) result.length()) {
  9108. return -result.length();
  9109. }
  9110. memcpy(buf, result.c_str(), result.length());
  9111. return result.length();
  9112. } else if (llama_is_unknown_token(model->vocab, token)) { // NOLINT
  9113. if (length < 3) {
  9114. return -3;
  9115. }
  9116. memcpy(buf, "\xe2\x96\x85", 3);
  9117. return 3;
  9118. } else if (llama_is_control_token(model->vocab, token)) {
  9119. ;
  9120. } else if (llama_is_byte_token(model->vocab, token)) {
  9121. if (length < 1) {
  9122. return -1;
  9123. }
  9124. buf[0] = llama_token_to_byte(model->vocab, token);
  9125. return 1;
  9126. }
  9127. break;
  9128. }
  9129. case LLAMA_VOCAB_TYPE_BPE: {
  9130. // NOTE: we accept all unsupported token types,
  9131. // suppressing them like CONTROL tokens.
  9132. if (llama_is_normal_token(model->vocab, token)) {
  9133. std::string result = model->vocab.id_to_token[token].text;
  9134. result = llama_decode_text(result);
  9135. if (length < (int) result.length()) {
  9136. return -(int) result.length();
  9137. }
  9138. memcpy(buf, result.c_str(), result.length());
  9139. return result.length();
  9140. } else if (llama_is_user_defined_token(model->vocab, token)) {
  9141. std::string result = model->vocab.id_to_token[token].text;
  9142. if (length < (int) result.length()) {
  9143. return -result.length();
  9144. }
  9145. memcpy(buf, result.c_str(), result.length());
  9146. return result.length();
  9147. } else if (llama_is_control_token(model->vocab, token)) {
  9148. ;
  9149. }
  9150. break;
  9151. }
  9152. default:
  9153. GGML_ASSERT(false);
  9154. }
  9155. }
  9156. return 0;
  9157. }
  9158. struct llama_timings llama_get_timings(struct llama_context * ctx) {
  9159. struct llama_timings result = {
  9160. /*.t_start_ms =*/ 1e-3 * ctx->t_start_us,
  9161. /*.t_end_ms =*/ 1.00 * ggml_time_ms(),
  9162. /*.t_load_ms =*/ 1e-3 * ctx->t_load_us,
  9163. /*.t_sample_ms =*/ 1e-3 * ctx->t_sample_us,
  9164. /*.t_p_eval_ms =*/ 1e-3 * ctx->t_p_eval_us,
  9165. /*.t_eval_ms =*/ 1e-3 * ctx->t_eval_us,
  9166. /*.n_sample =*/ std::max(1, ctx->n_sample),
  9167. /*.n_p_eval =*/ std::max(1, ctx->n_p_eval),
  9168. /*.n_eval =*/ std::max(1, ctx->n_eval),
  9169. };
  9170. return result;
  9171. }
  9172. void llama_print_timings(struct llama_context * ctx) {
  9173. const llama_timings timings = llama_get_timings(ctx);
  9174. LLAMA_LOG_INFO("\n");
  9175. LLAMA_LOG_INFO("%s: load time = %10.2f ms\n", __func__, timings.t_load_ms);
  9176. LLAMA_LOG_INFO("%s: sample time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  9177. __func__, timings.t_sample_ms, timings.n_sample, timings.t_sample_ms / timings.n_sample, 1e3 / timings.t_sample_ms * timings.n_sample);
  9178. LLAMA_LOG_INFO("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  9179. __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);
  9180. LLAMA_LOG_INFO("%s: eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  9181. __func__, timings.t_eval_ms, timings.n_eval, timings.t_eval_ms / timings.n_eval, 1e3 / timings.t_eval_ms * timings.n_eval);
  9182. 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));
  9183. }
  9184. void llama_reset_timings(struct llama_context * ctx) {
  9185. ctx->t_start_us = ggml_time_us();
  9186. ctx->t_sample_us = ctx->n_sample = 0;
  9187. ctx->t_eval_us = ctx->n_eval = 0;
  9188. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  9189. }
  9190. const char * llama_print_system_info(void) {
  9191. static std::string s;
  9192. s = "";
  9193. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  9194. s += "AVX_VNNI = " + std::to_string(ggml_cpu_has_avx_vnni()) + " | ";
  9195. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  9196. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  9197. s += "AVX512_VBMI = " + std::to_string(ggml_cpu_has_avx512_vbmi()) + " | ";
  9198. s += "AVX512_VNNI = " + std::to_string(ggml_cpu_has_avx512_vnni()) + " | ";
  9199. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  9200. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  9201. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  9202. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  9203. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  9204. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  9205. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  9206. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  9207. s += "SSSE3 = " + std::to_string(ggml_cpu_has_ssse3()) + " | ";
  9208. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  9209. return s.c_str();
  9210. }
  9211. void llama_dump_timing_info_yaml(FILE * stream, const llama_context * ctx) {
  9212. fprintf(stream, "\n");
  9213. fprintf(stream, "###########\n");
  9214. fprintf(stream, "# Timings #\n");
  9215. fprintf(stream, "###########\n");
  9216. fprintf(stream, "\n");
  9217. fprintf(stream, "mst_eval: %.2f # ms / token during generation\n",
  9218. 1.0e-3 * ctx->t_eval_us / ctx->n_eval);
  9219. fprintf(stream, "mst_p_eval: %.2f # ms / token during prompt processing\n",
  9220. 1.0e-3 * ctx->t_p_eval_us / ctx->n_p_eval);
  9221. fprintf(stream, "mst_sample: %.2f # ms / token during sampling\n",
  9222. 1.0e-3 * ctx->t_sample_us / ctx->n_sample);
  9223. fprintf(stream, "n_eval: %d # number of tokens generated (excluding the first one)\n", ctx->n_eval);
  9224. fprintf(stream, "n_p_eval: %d # number of tokens processed in batches at the beginning\n", ctx->n_p_eval);
  9225. fprintf(stream, "n_sample: %d # number of sampled tokens\n", ctx->n_sample);
  9226. fprintf(stream, "t_eval_us: %" PRId64 " # total microseconds spent generating tokens\n", ctx->t_eval_us);
  9227. fprintf(stream, "t_load_us: %" PRId64 " # total microseconds spent loading the model\n", ctx->t_load_us);
  9228. fprintf(stream, "t_p_eval_us: %" PRId64 " # total microseconds spent prompt processing\n", ctx->t_p_eval_us);
  9229. fprintf(stream, "t_sample_us: %" PRId64 " # total microseconds spent sampling\n", ctx->t_sample_us);
  9230. fprintf(stream, "ts_eval: %.2f # tokens / second during generation\n",
  9231. 1.0e6 * ctx->n_eval / ctx->t_eval_us);
  9232. fprintf(stream, "ts_p_eval: %.2f # tokens / second during prompt processing\n",
  9233. 1.0e6 * ctx->n_p_eval / ctx->t_p_eval_us);
  9234. fprintf(stream, "ts_sample: %.2f # tokens / second during sampling\n",
  9235. 1.0e6 * ctx->n_sample / ctx->t_sample_us);
  9236. }
  9237. // For internal test use
  9238. const std::vector<std::pair<std::string, struct ggml_tensor *>> & llama_internal_get_tensor_map(
  9239. struct llama_context * ctx
  9240. ) {
  9241. return ctx->model.tensors_by_name;
  9242. }
  9243. void llama_log_set(ggml_log_callback log_callback, void * user_data) {
  9244. g_state.log_callback = log_callback ? log_callback : llama_log_callback_default;
  9245. g_state.log_callback_user_data = user_data;
  9246. #ifdef GGML_USE_METAL
  9247. ggml_backend_metal_log_set_callback(g_state.log_callback, g_state.log_callback_user_data);
  9248. #endif
  9249. }
  9250. static void llama_log_internal_v(ggml_log_level level, const char * format, va_list args) {
  9251. va_list args_copy;
  9252. va_copy(args_copy, args);
  9253. char buffer[128];
  9254. int len = vsnprintf(buffer, 128, format, args);
  9255. if (len < 128) {
  9256. g_state.log_callback(level, buffer, g_state.log_callback_user_data);
  9257. } else {
  9258. char* buffer2 = new char[len+1];
  9259. vsnprintf(buffer2, len+1, format, args_copy);
  9260. buffer2[len] = 0;
  9261. g_state.log_callback(level, buffer2, g_state.log_callback_user_data);
  9262. delete[] buffer2;
  9263. }
  9264. va_end(args_copy);
  9265. }
  9266. static void llama_log_internal(ggml_log_level level, const char * format, ...) {
  9267. va_list args;
  9268. va_start(args, format);
  9269. llama_log_internal_v(level, format, args);
  9270. va_end(args);
  9271. }
  9272. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data) {
  9273. (void) level;
  9274. (void) user_data;
  9275. fputs(text, stderr);
  9276. fflush(stderr);
  9277. }