llama.cpp 420 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021
  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_1B,
  1182. MODEL_3B,
  1183. MODEL_7B,
  1184. MODEL_8B,
  1185. MODEL_13B,
  1186. MODEL_15B,
  1187. MODEL_30B,
  1188. MODEL_34B,
  1189. MODEL_40B,
  1190. MODEL_65B,
  1191. MODEL_70B,
  1192. MODEL_SMALL,
  1193. MODEL_MEDIUM,
  1194. MODEL_LARGE,
  1195. MODEL_XL,
  1196. };
  1197. static const size_t kiB = 1024;
  1198. static const size_t MiB = 1024*kiB;
  1199. static const size_t GiB = 1024*MiB;
  1200. struct llama_hparams {
  1201. bool vocab_only;
  1202. uint32_t n_vocab;
  1203. uint32_t n_ctx_train; // context size the model was trained on
  1204. uint32_t n_embd;
  1205. uint32_t n_head;
  1206. uint32_t n_head_kv;
  1207. uint32_t n_layer;
  1208. uint32_t n_rot;
  1209. 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
  1210. uint32_t n_embd_head_v; // dimension of values (d_v) aka n_embd_head
  1211. uint32_t n_ff;
  1212. uint32_t n_expert = 0;
  1213. uint32_t n_expert_used = 0;
  1214. float f_norm_eps;
  1215. float f_norm_rms_eps;
  1216. float rope_freq_base_train;
  1217. float rope_freq_scale_train;
  1218. uint32_t n_yarn_orig_ctx;
  1219. int8_t rope_scaling_type_train : 3;
  1220. bool rope_finetuned : 1;
  1221. float f_clamp_kqv;
  1222. float f_max_alibi_bias;
  1223. bool operator!=(const llama_hparams & other) const {
  1224. if (this->vocab_only != other.vocab_only) return true;
  1225. if (this->n_vocab != other.n_vocab) return true;
  1226. if (this->n_ctx_train != other.n_ctx_train) return true;
  1227. if (this->n_embd != other.n_embd) return true;
  1228. if (this->n_head != other.n_head) return true;
  1229. if (this->n_head_kv != other.n_head_kv) return true;
  1230. if (this->n_layer != other.n_layer) return true;
  1231. if (this->n_rot != other.n_rot) return true;
  1232. if (this->n_embd_head_k != other.n_embd_head_k) return true;
  1233. if (this->n_embd_head_v != other.n_embd_head_v) return true;
  1234. if (this->n_ff != other.n_ff) return true;
  1235. if (this->n_expert != other.n_expert) return true;
  1236. if (this->n_expert_used != other.n_expert_used) return true;
  1237. if (this->rope_finetuned != other.rope_finetuned) return true;
  1238. if (this->n_yarn_orig_ctx != other.n_yarn_orig_ctx) return true;
  1239. const float EPSILON = 1e-9f;
  1240. if (!is_float_close(this->f_norm_eps, other.f_norm_eps, EPSILON)) return true;
  1241. if (!is_float_close(this->f_norm_rms_eps, other.f_norm_rms_eps, EPSILON)) return true;
  1242. if (!is_float_close(this->rope_freq_base_train, other.rope_freq_base_train, EPSILON)) return true;
  1243. if (!is_float_close(this->rope_freq_scale_train, other.rope_freq_scale_train, EPSILON)) return true;
  1244. return false;
  1245. }
  1246. uint32_t n_gqa() const {
  1247. return n_head/n_head_kv;
  1248. }
  1249. uint32_t n_embd_k_gqa() const { // dimension of key embeddings across all k-v heads
  1250. return n_embd_head_k * n_head_kv;
  1251. }
  1252. uint32_t n_embd_v_gqa() const { // dimension of value embeddings across all k-v heads
  1253. return n_embd_head_v * n_head_kv;
  1254. }
  1255. };
  1256. struct llama_cparams {
  1257. uint32_t n_ctx; // context size used during inference
  1258. uint32_t n_batch;
  1259. uint32_t n_threads; // number of threads to use for generation
  1260. uint32_t n_threads_batch; // number of threads to use for batch processing
  1261. float rope_freq_base;
  1262. float rope_freq_scale;
  1263. uint32_t n_yarn_orig_ctx;
  1264. // These hyperparameters are not exposed in GGUF, because all
  1265. // existing YaRN models use the same values for them.
  1266. float yarn_ext_factor;
  1267. float yarn_attn_factor;
  1268. float yarn_beta_fast;
  1269. float yarn_beta_slow;
  1270. bool mul_mat_q;
  1271. bool offload_kqv;
  1272. ggml_backend_sched_eval_callback cb_eval;
  1273. void * cb_eval_user_data;
  1274. };
  1275. struct llama_layer {
  1276. // normalization
  1277. struct ggml_tensor * attn_norm;
  1278. struct ggml_tensor * attn_norm_b;
  1279. struct ggml_tensor * attn_norm_2;
  1280. struct ggml_tensor * attn_norm_2_b;
  1281. struct ggml_tensor * attn_q_norm;
  1282. struct ggml_tensor * attn_q_norm_b;
  1283. struct ggml_tensor * attn_k_norm;
  1284. struct ggml_tensor * attn_k_norm_b;
  1285. // attention
  1286. struct ggml_tensor * wq;
  1287. struct ggml_tensor * wk;
  1288. struct ggml_tensor * wv;
  1289. struct ggml_tensor * wo;
  1290. struct ggml_tensor * wqkv;
  1291. // attention bias
  1292. struct ggml_tensor * bq;
  1293. struct ggml_tensor * bk;
  1294. struct ggml_tensor * bv;
  1295. struct ggml_tensor * bo;
  1296. struct ggml_tensor * bqkv;
  1297. // normalization
  1298. struct ggml_tensor * ffn_norm;
  1299. struct ggml_tensor * ffn_norm_b;
  1300. // ff
  1301. struct ggml_tensor * ffn_gate; // w1
  1302. struct ggml_tensor * ffn_down; // w2
  1303. struct ggml_tensor * ffn_up; // w3
  1304. // ff MoE
  1305. struct ggml_tensor * ffn_gate_inp;
  1306. struct ggml_tensor * ffn_gate_exp[LLAMA_MAX_EXPERTS];
  1307. struct ggml_tensor * ffn_down_exp[LLAMA_MAX_EXPERTS];
  1308. struct ggml_tensor * ffn_up_exp [LLAMA_MAX_EXPERTS];
  1309. // ff bias
  1310. struct ggml_tensor * ffn_down_b; // b2
  1311. struct ggml_tensor * ffn_up_b; // b3
  1312. struct ggml_tensor * ffn_act;
  1313. };
  1314. struct llama_kv_cell {
  1315. llama_pos pos = -1;
  1316. llama_pos delta = 0;
  1317. std::set<llama_seq_id> seq_id;
  1318. bool has_seq_id(const llama_seq_id & id) const {
  1319. return seq_id.find(id) != seq_id.end();
  1320. }
  1321. };
  1322. // ring-buffer of cached KV data
  1323. struct llama_kv_cache {
  1324. bool has_shift = false;
  1325. // Note: The value of head isn't only used to optimize searching
  1326. // for a free KV slot. llama_decode_internal also uses it, so it
  1327. // cannot be freely changed after a slot has been allocated.
  1328. uint32_t head = 0;
  1329. uint32_t size = 0;
  1330. uint32_t used = 0; // used cells (i.e. at least one seq_id)
  1331. // computed before each graph build
  1332. uint32_t n = 0;
  1333. std::vector<llama_kv_cell> cells;
  1334. std::vector<struct ggml_tensor *> k_l; // per layer
  1335. std::vector<struct ggml_tensor *> v_l;
  1336. std::vector<struct ggml_context *> ctxs;
  1337. std::vector<ggml_backend_buffer_t> bufs;
  1338. size_t total_size() const {
  1339. size_t size = 0;
  1340. for (ggml_backend_buffer_t buf : bufs) {
  1341. size += ggml_backend_buffer_get_size(buf);
  1342. }
  1343. return size;
  1344. }
  1345. ~llama_kv_cache() {
  1346. for (struct ggml_context * ctx : ctxs) {
  1347. ggml_free(ctx);
  1348. }
  1349. for (ggml_backend_buffer_t buf : bufs) {
  1350. ggml_backend_buffer_free(buf);
  1351. }
  1352. }
  1353. };
  1354. struct llama_vocab {
  1355. using id = int32_t;
  1356. using token = std::string;
  1357. using ttype = llama_token_type;
  1358. struct token_data {
  1359. token text;
  1360. float score;
  1361. ttype type;
  1362. };
  1363. enum llama_vocab_type type = LLAMA_VOCAB_TYPE_SPM;
  1364. std::unordered_map<token, id> token_to_id;
  1365. std::vector<token_data> id_to_token;
  1366. std::unordered_map<token, id> special_tokens_cache;
  1367. std::map<std::pair<std::string, std::string>, int> bpe_ranks;
  1368. // default LLaMA special tokens
  1369. id special_bos_id = 1;
  1370. id special_eos_id = 2;
  1371. id special_unk_id = 0;
  1372. id special_sep_id = -1;
  1373. id special_pad_id = -1;
  1374. int special_add_bos = -1; // -1 unknown, 1 add, 0 don't add.
  1375. int special_add_eos = -1; // -1 unknown, 1 add, 0 don't add.
  1376. id linefeed_id = 13;
  1377. id special_prefix_id = 32007;
  1378. id special_middle_id = 32009;
  1379. id special_suffix_id = 32008;
  1380. id special_eot_id = 32010;
  1381. int find_bpe_rank(const std::string & token_left, const std::string & token_right) const {
  1382. GGML_ASSERT(token_left.find(' ') == std::string::npos);
  1383. GGML_ASSERT(token_left.find('\n') == std::string::npos);
  1384. GGML_ASSERT(token_right.find(' ') == std::string::npos);
  1385. GGML_ASSERT(token_right.find('\n') == std::string::npos);
  1386. auto it = bpe_ranks.find(std::make_pair(token_left, token_right));
  1387. if (it == bpe_ranks.end()) {
  1388. return -1;
  1389. }
  1390. return it->second;
  1391. }
  1392. };
  1393. struct llama_model {
  1394. e_model type = MODEL_UNKNOWN;
  1395. llm_arch arch = LLM_ARCH_UNKNOWN;
  1396. llama_ftype ftype = LLAMA_FTYPE_ALL_F32;
  1397. std::string name = "n/a";
  1398. llama_hparams hparams = {};
  1399. llama_vocab vocab;
  1400. struct ggml_tensor * tok_embd;
  1401. struct ggml_tensor * pos_embd;
  1402. struct ggml_tensor * tok_norm;
  1403. struct ggml_tensor * tok_norm_b;
  1404. struct ggml_tensor * output_norm;
  1405. struct ggml_tensor * output_norm_b;
  1406. struct ggml_tensor * output;
  1407. struct ggml_tensor * output_b;
  1408. std::vector<llama_layer> layers;
  1409. llama_split_mode split_mode;
  1410. int main_gpu;
  1411. int n_gpu_layers;
  1412. // gguf metadata
  1413. std::unordered_map<std::string, std::string> gguf_kv;
  1414. // layer -> buffer type mapping
  1415. struct layer_buft {
  1416. layer_buft() : buft_matrix(nullptr), buft(nullptr) {}
  1417. layer_buft(ggml_backend_buffer_type_t matrix) : buft_matrix(matrix), buft(matrix) {}
  1418. layer_buft(ggml_backend_buffer_type_t matrix, ggml_backend_buffer_type_t other) : buft_matrix(matrix), buft(other) {}
  1419. ggml_backend_buffer_type_t buft_matrix; // matrices only - used by split buffers and backends that support only matrix multiplication
  1420. ggml_backend_buffer_type_t buft; // everything else
  1421. };
  1422. layer_buft buft_input;
  1423. layer_buft buft_output;
  1424. std::vector<layer_buft> buft_layer;
  1425. // contexts where the model tensors metadata is stored
  1426. std::vector<struct ggml_context *> ctxs;
  1427. // the model memory buffers for the tensor data
  1428. std::vector<ggml_backend_buffer_t> bufs;
  1429. // model memory mapped file
  1430. std::unique_ptr<llama_mmap> mapping;
  1431. // objects representing data potentially being locked in memory
  1432. std::vector<std::unique_ptr<llama_mlock>> mlock_bufs;
  1433. llama_mlock mlock_mmap;
  1434. // for quantize-stats only
  1435. std::vector<std::pair<std::string, struct ggml_tensor *>> tensors_by_name;
  1436. int64_t t_load_us = 0;
  1437. int64_t t_start_us = 0;
  1438. ~llama_model() {
  1439. for (struct ggml_context * ctx : ctxs) {
  1440. ggml_free(ctx);
  1441. }
  1442. for (ggml_backend_buffer_t buf : bufs) {
  1443. ggml_backend_buffer_free(buf);
  1444. }
  1445. }
  1446. };
  1447. struct llama_context {
  1448. llama_context(const llama_model & model) : model(model), t_start_us(model.t_start_us), t_load_us(model.t_load_us) {}
  1449. ~llama_context() {
  1450. ggml_backend_sched_free(sched);
  1451. for (ggml_backend_t backend : backends) {
  1452. ggml_backend_free(backend);
  1453. }
  1454. }
  1455. llama_cparams cparams;
  1456. std::vector<ggml_backend_t> backends;
  1457. #ifdef GGML_USE_METAL
  1458. ggml_backend_t backend_metal = nullptr;
  1459. #endif
  1460. ggml_backend_t backend_cpu = nullptr;
  1461. const llama_model & model;
  1462. // key + value cache for the self attention
  1463. struct llama_kv_cache kv_self;
  1464. std::mt19937 rng;
  1465. bool has_evaluated_once = false;
  1466. int64_t t_start_us;
  1467. int64_t t_load_us;
  1468. int64_t t_sample_us = 0;
  1469. int64_t t_p_eval_us = 0;
  1470. int64_t t_eval_us = 0;
  1471. int32_t n_sample = 0; // number of tokens sampled
  1472. int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1)
  1473. int32_t n_eval = 0; // number of eval calls
  1474. // decode output (2-dimensional array: [n_tokens][n_vocab])
  1475. std::vector<float> logits;
  1476. #ifndef NDEBUG
  1477. // guard against access to unset logits
  1478. std::vector<bool> logits_valid;
  1479. #endif
  1480. bool logits_all = false;
  1481. // input embedding (1-dimensional array: [n_embd])
  1482. std::vector<float> embedding;
  1483. // memory buffers used to evaluate the model
  1484. std::vector<uint8_t> buf_compute_meta;
  1485. ggml_backend_sched_t sched = nullptr;
  1486. // allocator for the input tensors
  1487. ggml_tallocr * alloc = nullptr;
  1488. // temporary buffer for copying data to/from the backend
  1489. std::vector<no_init<uint8_t>> buf_copy;
  1490. #ifdef GGML_USE_MPI
  1491. ggml_mpi_context * ctx_mpi = NULL;
  1492. #endif
  1493. };
  1494. //
  1495. // kv cache helpers
  1496. //
  1497. static bool llama_kv_cache_init(
  1498. struct llama_kv_cache & cache,
  1499. const llama_model & model,
  1500. ggml_type ktype,
  1501. ggml_type vtype,
  1502. uint32_t n_ctx,
  1503. bool offload) {
  1504. const struct llama_hparams & hparams = model.hparams;
  1505. const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  1506. const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  1507. const int64_t n_layer = hparams.n_layer;
  1508. cache.has_shift = false;
  1509. cache.head = 0;
  1510. cache.size = n_ctx;
  1511. cache.used = 0;
  1512. cache.cells.clear();
  1513. cache.cells.resize(n_ctx);
  1514. #ifdef GGML_USE_CLBLAST
  1515. offload = false;
  1516. #endif
  1517. // count used buffer types
  1518. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  1519. if (offload) {
  1520. for (int64_t i = 0; i < n_layer; ++i) {
  1521. buft_layer_count[model.buft_layer[i].buft]++;
  1522. }
  1523. } else {
  1524. buft_layer_count[llama_default_buffer_type_cpu(true)] = n_layer;
  1525. }
  1526. // create a context for each buffer type
  1527. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  1528. for (auto & it : buft_layer_count) {
  1529. int n_layers = it.second;
  1530. struct ggml_init_params params = {
  1531. /*.mem_size =*/ 2u*n_layers*ggml_tensor_overhead(),
  1532. /*.mem_buffer =*/ NULL,
  1533. /*.no_alloc =*/ true,
  1534. };
  1535. ggml_context * ctx = ggml_init(params);
  1536. if (!ctx) {
  1537. LLAMA_LOG_ERROR("%s: failed to allocate context for kv cache\n", __func__);
  1538. return false;
  1539. }
  1540. ctx_map[it.first] = ctx;
  1541. cache.ctxs.push_back(ctx);
  1542. }
  1543. cache.k_l.reserve(n_layer);
  1544. cache.v_l.reserve(n_layer);
  1545. for (int i = 0; i < (int) n_layer; i++) {
  1546. struct ggml_context * ctx = offload ? ctx_map.at(model.buft_layer[i].buft) : cache.ctxs.front();
  1547. ggml_tensor * k = ggml_new_tensor_1d(ctx, ktype, n_embd_k_gqa*n_ctx);
  1548. ggml_tensor * v = ggml_new_tensor_1d(ctx, vtype, n_embd_v_gqa*n_ctx);
  1549. ggml_format_name(k, "cache_k_l%d", i);
  1550. ggml_format_name(v, "cache_v_l%d", i);
  1551. cache.k_l.push_back(k);
  1552. cache.v_l.push_back(v);
  1553. }
  1554. // allocate tensors and initialize the buffers to avoid NaNs in the padding
  1555. for (auto it : ctx_map) {
  1556. ggml_backend_buffer_type_t buft = it.first;
  1557. ggml_context * ctx = it.second;
  1558. ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  1559. if (!buf) {
  1560. LLAMA_LOG_ERROR("%s: failed to allocate buffer for kv cache\n", __func__);
  1561. return false;
  1562. }
  1563. ggml_backend_buffer_clear(buf, 0);
  1564. 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);
  1565. cache.bufs.push_back(buf);
  1566. }
  1567. return true;
  1568. }
  1569. // find an empty slot of size "n_tokens" in the cache
  1570. // updates the cache head
  1571. // Note: On success, it's important that cache.head points
  1572. // to the first cell of the slot.
  1573. static bool llama_kv_cache_find_slot(
  1574. struct llama_kv_cache & cache,
  1575. const struct llama_batch & batch) {
  1576. const uint32_t n_ctx = cache.size;
  1577. const uint32_t n_tokens = batch.n_tokens;
  1578. if (n_tokens > n_ctx) {
  1579. LLAMA_LOG_ERROR("%s: n_tokens=%d > n_ctx=%d\n", __func__, n_tokens, n_ctx);
  1580. return false;
  1581. }
  1582. uint32_t n_tested = 0;
  1583. while (true) {
  1584. if (cache.head + n_tokens > n_ctx) {
  1585. n_tested += n_ctx - cache.head;
  1586. cache.head = 0;
  1587. continue;
  1588. }
  1589. bool found = true;
  1590. for (uint32_t i = 0; i < n_tokens; i++) {
  1591. if (cache.cells[cache.head + i].pos >= 0) {
  1592. found = false;
  1593. cache.head += i + 1;
  1594. n_tested += i + 1;
  1595. break;
  1596. }
  1597. }
  1598. if (found) {
  1599. break;
  1600. }
  1601. if (n_tested >= n_ctx) {
  1602. //LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens);
  1603. return false;
  1604. }
  1605. }
  1606. for (uint32_t i = 0; i < n_tokens; i++) {
  1607. cache.cells[cache.head + i].pos = batch.pos[i];
  1608. for (int32_t j = 0; j < batch.n_seq_id[i]; j++) {
  1609. cache.cells[cache.head + i].seq_id.insert(batch.seq_id[i][j]);
  1610. }
  1611. }
  1612. cache.used += n_tokens;
  1613. return true;
  1614. }
  1615. // find how many cells are currently in use
  1616. static int32_t llama_kv_cache_cell_max(const struct llama_kv_cache & cache) {
  1617. for (uint32_t i = cache.size - 1; i > 0; --i) {
  1618. if (cache.cells[i].pos >= 0 && !cache.cells[i].seq_id.empty()) {
  1619. return i + 1;
  1620. }
  1621. }
  1622. return 0;
  1623. }
  1624. static void llama_kv_cache_clear(struct llama_kv_cache & cache) {
  1625. for (int32_t i = 0; i < (int32_t) cache.size; ++i) {
  1626. cache.cells[i].pos = -1;
  1627. cache.cells[i].seq_id.clear();
  1628. }
  1629. cache.head = 0;
  1630. cache.used = 0;
  1631. }
  1632. static void llama_kv_cache_seq_rm(
  1633. struct llama_kv_cache & cache,
  1634. llama_seq_id seq_id,
  1635. llama_pos p0,
  1636. llama_pos p1) {
  1637. uint32_t new_head = cache.size;
  1638. if (p0 < 0) p0 = 0;
  1639. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1640. for (uint32_t i = 0; i < cache.size; ++i) {
  1641. if (cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1642. if (seq_id < 0) {
  1643. cache.cells[i].seq_id.clear();
  1644. } else if (cache.cells[i].has_seq_id(seq_id)) {
  1645. cache.cells[i].seq_id.erase(seq_id);
  1646. } else {
  1647. continue;
  1648. }
  1649. if (cache.cells[i].seq_id.empty()) {
  1650. // keep count of the number of used cells
  1651. if (cache.cells[i].pos >= 0) cache.used--;
  1652. cache.cells[i].pos = -1;
  1653. if (new_head == cache.size) new_head = i;
  1654. }
  1655. }
  1656. }
  1657. // If we freed up a slot, set head to it so searching can start there.
  1658. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  1659. }
  1660. static void llama_kv_cache_seq_cp(
  1661. struct llama_kv_cache & cache,
  1662. llama_seq_id seq_id_src,
  1663. llama_seq_id seq_id_dst,
  1664. llama_pos p0,
  1665. llama_pos p1) {
  1666. if (p0 < 0) p0 = 0;
  1667. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1668. cache.head = 0;
  1669. for (uint32_t i = 0; i < cache.size; ++i) {
  1670. if (cache.cells[i].has_seq_id(seq_id_src) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1671. cache.cells[i].seq_id.insert(seq_id_dst);
  1672. }
  1673. }
  1674. }
  1675. static void llama_kv_cache_seq_keep(struct llama_kv_cache & cache, llama_seq_id seq_id) {
  1676. uint32_t new_head = cache.size;
  1677. for (uint32_t i = 0; i < cache.size; ++i) {
  1678. if (!cache.cells[i].has_seq_id(seq_id)) {
  1679. if (cache.cells[i].pos >= 0) cache.used--;
  1680. cache.cells[i].pos = -1;
  1681. cache.cells[i].seq_id.clear();
  1682. if (new_head == cache.size) new_head = i;
  1683. } else {
  1684. cache.cells[i].seq_id.clear();
  1685. cache.cells[i].seq_id.insert(seq_id);
  1686. }
  1687. }
  1688. // If we freed up a slot, set head to it so searching can start there.
  1689. if (new_head != cache.size && new_head < cache.head) cache.head = new_head;
  1690. }
  1691. static void llama_kv_cache_seq_shift(
  1692. struct llama_kv_cache & cache,
  1693. llama_seq_id seq_id,
  1694. llama_pos p0,
  1695. llama_pos p1,
  1696. llama_pos delta) {
  1697. uint32_t new_head = cache.size;
  1698. if (p0 < 0) p0 = 0;
  1699. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1700. for (uint32_t i = 0; i < cache.size; ++i) {
  1701. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1702. cache.has_shift = true;
  1703. cache.cells[i].pos += delta;
  1704. cache.cells[i].delta += delta;
  1705. if (cache.cells[i].pos < 0) {
  1706. if (!cache.cells[i].seq_id.empty()) cache.used--;
  1707. cache.cells[i].pos = -1;
  1708. cache.cells[i].seq_id.clear();
  1709. if (new_head == cache.size) new_head = i;
  1710. }
  1711. }
  1712. }
  1713. // If we freed up a slot, set head to it so searching can start there.
  1714. // Otherwise we just start the next search from the beginning.
  1715. cache.head = new_head != cache.size ? new_head : 0;
  1716. }
  1717. static void llama_kv_cache_seq_div(
  1718. struct llama_kv_cache & cache,
  1719. llama_seq_id seq_id,
  1720. llama_pos p0,
  1721. llama_pos p1,
  1722. int d) {
  1723. if (p0 < 0) p0 = 0;
  1724. if (p1 < 0) p1 = std::numeric_limits<llama_pos>::max();
  1725. for (uint32_t i = 0; i < cache.size; ++i) {
  1726. if (cache.cells[i].has_seq_id(seq_id) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) {
  1727. cache.has_shift = true;
  1728. {
  1729. llama_pos p_old = cache.cells[i].pos;
  1730. cache.cells[i].pos /= d;
  1731. cache.cells[i].delta += cache.cells[i].pos - p_old;
  1732. }
  1733. }
  1734. }
  1735. }
  1736. //
  1737. // model loading and saving
  1738. //
  1739. enum llama_fver {
  1740. GGUF_FILE_VERSION_V1 = 1,
  1741. GGUF_FILE_VERSION_V2 = 2,
  1742. GGUF_FILE_VERSION_V3 = 3,
  1743. };
  1744. static const char * llama_file_version_name(llama_fver version) {
  1745. switch (version) {
  1746. case GGUF_FILE_VERSION_V1: return "GGUF V1 (support until nov 2023)";
  1747. case GGUF_FILE_VERSION_V2: return "GGUF V2";
  1748. case GGUF_FILE_VERSION_V3: return "GGUF V3 (latest)";
  1749. }
  1750. return "unknown";
  1751. }
  1752. static std::string llama_format_tensor_shape(const std::vector<int64_t> & ne) {
  1753. char buf[256];
  1754. snprintf(buf, sizeof(buf), "%5" PRId64, ne.at(0));
  1755. for (size_t i = 1; i < ne.size(); i++) {
  1756. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, ne.at(i));
  1757. }
  1758. return buf;
  1759. }
  1760. static std::string llama_format_tensor_shape(const struct ggml_tensor * t) {
  1761. char buf[256];
  1762. snprintf(buf, sizeof(buf), "%5" PRId64, t->ne[0]);
  1763. for (int i = 1; i < GGML_MAX_DIMS; i++) {
  1764. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ", %5" PRId64, t->ne[i]);
  1765. }
  1766. return buf;
  1767. }
  1768. namespace GGUFMeta {
  1769. template <typename T, gguf_type gt_, T (*gfun)(const gguf_context *, const int)>
  1770. struct GKV_Base_Type {
  1771. static constexpr gguf_type gt = gt_;
  1772. static T getter(const gguf_context * ctx, const int kid) {
  1773. return gfun(ctx, kid);
  1774. }
  1775. };
  1776. template<typename T> struct GKV_Base;
  1777. template<> struct GKV_Base<bool >: GKV_Base_Type<bool, GGUF_TYPE_BOOL, gguf_get_val_bool> {};
  1778. template<> struct GKV_Base<uint8_t >: GKV_Base_Type<uint8_t, GGUF_TYPE_UINT8, gguf_get_val_u8 > {};
  1779. template<> struct GKV_Base<uint16_t >: GKV_Base_Type<uint16_t, GGUF_TYPE_UINT16, gguf_get_val_u16 > {};
  1780. template<> struct GKV_Base<uint32_t >: GKV_Base_Type<uint32_t, GGUF_TYPE_UINT32, gguf_get_val_u32 > {};
  1781. template<> struct GKV_Base<uint64_t >: GKV_Base_Type<uint64_t, GGUF_TYPE_UINT64, gguf_get_val_u64 > {};
  1782. template<> struct GKV_Base<int8_t >: GKV_Base_Type<int8_t, GGUF_TYPE_INT8, gguf_get_val_i8 > {};
  1783. template<> struct GKV_Base<int16_t >: GKV_Base_Type<int16_t, GGUF_TYPE_INT16, gguf_get_val_i16 > {};
  1784. template<> struct GKV_Base<int32_t >: GKV_Base_Type<int32_t, GGUF_TYPE_INT32, gguf_get_val_i32 > {};
  1785. template<> struct GKV_Base<int64_t >: GKV_Base_Type<int64_t, GGUF_TYPE_INT64, gguf_get_val_i64 > {};
  1786. template<> struct GKV_Base<float >: GKV_Base_Type<float, GGUF_TYPE_FLOAT32, gguf_get_val_f32 > {};
  1787. template<> struct GKV_Base<double >: GKV_Base_Type<double, GGUF_TYPE_FLOAT64, gguf_get_val_f64 > {};
  1788. template<> struct GKV_Base<const char *>: GKV_Base_Type<const char *, GGUF_TYPE_STRING, gguf_get_val_str > {};
  1789. template<> struct GKV_Base<std::string> {
  1790. static constexpr gguf_type gt = GGUF_TYPE_STRING;
  1791. static std::string getter(const gguf_context * ctx, const int kid) {
  1792. return gguf_get_val_str(ctx, kid);
  1793. }
  1794. };
  1795. struct ArrayInfo{
  1796. const gguf_type gt;
  1797. const size_t length;
  1798. const void * data;
  1799. };
  1800. template<> struct GKV_Base<ArrayInfo> {
  1801. public:
  1802. static constexpr gguf_type gt = GGUF_TYPE_ARRAY;
  1803. static ArrayInfo getter(const gguf_context *ctx, const int k) {
  1804. return ArrayInfo {
  1805. gguf_get_arr_type(ctx, k),
  1806. size_t(gguf_get_arr_n(ctx, k)),
  1807. gguf_get_arr_data(ctx, k),
  1808. };
  1809. }
  1810. };
  1811. template<typename T>
  1812. class GKV: public GKV_Base<T> {
  1813. GKV() = delete;
  1814. public:
  1815. static T get_kv(const gguf_context * ctx, const int k) {
  1816. const enum gguf_type kt = gguf_get_kv_type(ctx, k);
  1817. if (kt != GKV::gt) {
  1818. throw std::runtime_error(format("key %s has wrong type %s but expected type %s",
  1819. gguf_get_key(ctx, k), gguf_type_name(kt), gguf_type_name(GKV::gt)));
  1820. }
  1821. return GKV::getter(ctx, k);
  1822. }
  1823. static const char * override_type_to_str(const llama_model_kv_override_type ty) {
  1824. switch (ty) {
  1825. case LLAMA_KV_OVERRIDE_BOOL: return "bool";
  1826. case LLAMA_KV_OVERRIDE_INT: return "int";
  1827. case LLAMA_KV_OVERRIDE_FLOAT: return "float";
  1828. }
  1829. return "unknown";
  1830. }
  1831. static bool validate_override(const llama_model_kv_override_type expected_type, const struct llama_model_kv_override *override) {
  1832. if (!override) { return false; }
  1833. if (override->tag == expected_type) {
  1834. LLAMA_LOG_INFO("%s: Using metadata override (%5s) '%s' = ",
  1835. __func__, override_type_to_str(override->tag), override->key);
  1836. switch (override->tag) {
  1837. case LLAMA_KV_OVERRIDE_BOOL: {
  1838. LLAMA_LOG_INFO("%s\n", override->bool_value ? "true" : "false");
  1839. } break;
  1840. case LLAMA_KV_OVERRIDE_INT: {
  1841. LLAMA_LOG_INFO("%" PRId64 "\n", override->int_value);
  1842. } break;
  1843. case LLAMA_KV_OVERRIDE_FLOAT: {
  1844. LLAMA_LOG_INFO("%.6f\n", override->float_value);
  1845. } break;
  1846. default:
  1847. // Shouldn't be possible to end up here, but just in case...
  1848. throw std::runtime_error(
  1849. format("Unsupported attempt to override %s type for metadata key %s\n",
  1850. override_type_to_str(override->tag), override->key));
  1851. }
  1852. return true;
  1853. }
  1854. LLAMA_LOG_WARN("%s: Warning: Bad metadata override type for key '%s', expected %s but got %s\n",
  1855. __func__, override->key, override_type_to_str(expected_type), override_type_to_str(override->tag));
  1856. return false;
  1857. }
  1858. template<typename OT>
  1859. static typename std::enable_if<std::is_same<OT, bool>::value, bool>::type
  1860. try_override(OT & target, const struct llama_model_kv_override *override) {
  1861. if (validate_override(LLAMA_KV_OVERRIDE_BOOL, override)) {
  1862. target = override->bool_value;
  1863. return true;
  1864. }
  1865. return false;
  1866. }
  1867. template<typename OT>
  1868. static typename std::enable_if<!std::is_same<OT, bool>::value && std::is_integral<OT>::value, bool>::type
  1869. try_override(OT & target, const struct llama_model_kv_override *override) {
  1870. if (validate_override(LLAMA_KV_OVERRIDE_INT, override)) {
  1871. target = override->int_value;
  1872. return true;
  1873. }
  1874. return false;
  1875. }
  1876. template<typename OT>
  1877. static typename std::enable_if<std::is_floating_point<OT>::value, bool>::type
  1878. try_override(T & target, const struct llama_model_kv_override *override) {
  1879. if (validate_override(LLAMA_KV_OVERRIDE_FLOAT, override)) {
  1880. target = override->float_value;
  1881. return true;
  1882. }
  1883. return false;
  1884. }
  1885. template<typename OT>
  1886. static typename std::enable_if<std::is_same<OT, std::string>::value, bool>::type
  1887. try_override(T & target, const struct llama_model_kv_override *override) {
  1888. (void)target;
  1889. (void)override;
  1890. if (!override) { return false; }
  1891. // Currently, we should never end up here so it would be a bug if we do.
  1892. throw std::runtime_error(format("Unsupported attempt to override string type for metadata key %s\n",
  1893. override ? override->key : "NULL"));
  1894. }
  1895. static bool set(const gguf_context * ctx, const int k, T & target, const struct llama_model_kv_override *override = nullptr) {
  1896. if (try_override<T>(target, override)) {
  1897. return true;
  1898. }
  1899. if (k < 0) { return false; }
  1900. target = get_kv(ctx, k);
  1901. return true;
  1902. }
  1903. static bool set(const gguf_context * ctx, const char * key, T & target, const struct llama_model_kv_override *override = nullptr) {
  1904. return set(ctx, gguf_find_key(ctx, key), target, override);
  1905. }
  1906. static bool set(const gguf_context * ctx, const std::string & key, T & target, const struct llama_model_kv_override *override = nullptr) {
  1907. return set(ctx, key.c_str(), target, override);
  1908. }
  1909. };
  1910. }
  1911. struct llama_model_loader {
  1912. int n_kv = 0;
  1913. int n_tensors = 0;
  1914. int n_created = 0;
  1915. int64_t n_elements = 0;
  1916. size_t n_bytes = 0;
  1917. bool use_mmap = false;
  1918. llama_file file;
  1919. llama_ftype ftype;
  1920. llama_fver fver;
  1921. std::unique_ptr<llama_mmap> mapping;
  1922. std::unordered_map<std::string, struct llama_model_kv_override> kv_overrides;
  1923. struct gguf_context * ctx_gguf = NULL;
  1924. struct ggml_context * ctx_meta = NULL;
  1925. std::string arch_name;
  1926. LLM_KV llm_kv = LLM_KV(LLM_ARCH_UNKNOWN);
  1927. llama_model_loader(const std::string & fname, bool use_mmap, const struct llama_model_kv_override * param_overrides_p) : file(fname.c_str(), "rb") {
  1928. int trace = 0;
  1929. if (getenv("LLAMA_TRACE")) {
  1930. trace = atoi(getenv("LLAMA_TRACE"));
  1931. }
  1932. struct gguf_init_params params = {
  1933. /*.no_alloc = */ true,
  1934. /*.ctx = */ &ctx_meta,
  1935. };
  1936. if (param_overrides_p != nullptr) {
  1937. for (const struct llama_model_kv_override *p = param_overrides_p; p->key[0] != 0; p++) {
  1938. kv_overrides.insert({std::string(p->key), *p});
  1939. }
  1940. }
  1941. ctx_gguf = gguf_init_from_file(fname.c_str(), params);
  1942. if (!ctx_gguf) {
  1943. throw std::runtime_error(format("%s: failed to load model from %s\n", __func__, fname.c_str()));
  1944. }
  1945. get_key(llm_kv(LLM_KV_GENERAL_ARCHITECTURE), arch_name, false);
  1946. llm_kv = LLM_KV(llm_arch_from_string(arch_name));
  1947. n_kv = gguf_get_n_kv(ctx_gguf);
  1948. n_tensors = gguf_get_n_tensors(ctx_gguf);
  1949. fver = (enum llama_fver ) gguf_get_version(ctx_gguf);
  1950. for (int i = 0; i < n_tensors; i++) {
  1951. const char * name = gguf_get_tensor_name(ctx_gguf, i);
  1952. struct ggml_tensor * t = ggml_get_tensor(ctx_meta, name);
  1953. n_elements += ggml_nelements(t);
  1954. n_bytes += ggml_nbytes(t);
  1955. }
  1956. LLAMA_LOG_INFO("%s: loaded meta data with %d key-value pairs and %d tensors from %s (version %s)\n",
  1957. __func__, n_kv, n_tensors, fname.c_str(), llama_file_version_name(fver));
  1958. // determine file type based on the number of tensors for each quantization and print meta data
  1959. // TODO: make optional
  1960. {
  1961. std::map<enum ggml_type, uint32_t> n_type;
  1962. uint32_t n_type_max = 0;
  1963. enum ggml_type type_max = GGML_TYPE_F32;
  1964. for (int i = 0; i < n_tensors; i++) {
  1965. enum ggml_type type = gguf_get_tensor_type(ctx_gguf, i);
  1966. n_type[type]++;
  1967. if (n_type_max < n_type[type]) {
  1968. n_type_max = n_type[type];
  1969. type_max = type;
  1970. }
  1971. if (trace > 0) {
  1972. struct ggml_tensor * meta = ggml_get_tensor(ctx_meta, gguf_get_tensor_name(ctx_gguf, i));
  1973. 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());
  1974. }
  1975. }
  1976. switch (type_max) {
  1977. case GGML_TYPE_F32: ftype = LLAMA_FTYPE_ALL_F32; break;
  1978. case GGML_TYPE_F16: ftype = LLAMA_FTYPE_MOSTLY_F16; break;
  1979. case GGML_TYPE_Q4_0: ftype = LLAMA_FTYPE_MOSTLY_Q4_0; break;
  1980. case GGML_TYPE_Q4_1: ftype = LLAMA_FTYPE_MOSTLY_Q4_1; break;
  1981. case GGML_TYPE_Q5_0: ftype = LLAMA_FTYPE_MOSTLY_Q5_0; break;
  1982. case GGML_TYPE_Q5_1: ftype = LLAMA_FTYPE_MOSTLY_Q5_1; break;
  1983. case GGML_TYPE_Q8_0: ftype = LLAMA_FTYPE_MOSTLY_Q8_0; break;
  1984. case GGML_TYPE_Q2_K: ftype = LLAMA_FTYPE_MOSTLY_Q2_K; break;
  1985. case GGML_TYPE_Q3_K: ftype = LLAMA_FTYPE_MOSTLY_Q3_K_M; break;
  1986. case GGML_TYPE_Q4_K: ftype = LLAMA_FTYPE_MOSTLY_Q4_K_M; break;
  1987. case GGML_TYPE_Q5_K: ftype = LLAMA_FTYPE_MOSTLY_Q5_K_M; break;
  1988. case GGML_TYPE_Q6_K: ftype = LLAMA_FTYPE_MOSTLY_Q6_K; break;
  1989. case GGML_TYPE_IQ2_XXS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XXS; break;
  1990. case GGML_TYPE_IQ2_XS: ftype = LLAMA_FTYPE_MOSTLY_IQ2_XS; break;
  1991. default:
  1992. {
  1993. LLAMA_LOG_WARN("%s: unknown type %s\n", __func__, ggml_type_name(type_max));
  1994. ftype = LLAMA_FTYPE_ALL_F32;
  1995. } break;
  1996. }
  1997. // this is a way to mark that we have "guessed" the file type
  1998. ftype = (llama_ftype) (ftype | LLAMA_FTYPE_GUESSED);
  1999. {
  2000. const int kid = gguf_find_key(ctx_gguf, "general.file_type");
  2001. if (kid >= 0) {
  2002. ftype = (llama_ftype) gguf_get_val_u32(ctx_gguf, kid);
  2003. }
  2004. }
  2005. LLAMA_LOG_INFO("%s: Dumping metadata keys/values. Note: KV overrides do not apply in this output.\n", __func__);
  2006. for (int i = 0; i < n_kv; i++) {
  2007. const char * name = gguf_get_key(ctx_gguf, i);
  2008. const enum gguf_type type = gguf_get_kv_type(ctx_gguf, i);
  2009. const std::string type_name =
  2010. type == GGUF_TYPE_ARRAY
  2011. ? 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))
  2012. : gguf_type_name(type);
  2013. std::string value = gguf_kv_to_str(ctx_gguf, i);
  2014. const size_t MAX_VALUE_LEN = 40;
  2015. if (value.size() > MAX_VALUE_LEN) {
  2016. value = format("%s...", value.substr(0, MAX_VALUE_LEN - 3).c_str());
  2017. }
  2018. replace_all(value, "\n", "\\n");
  2019. LLAMA_LOG_INFO("%s: - kv %3d: %42s %-16s = %s\n", __func__, i, name, type_name.c_str(), value.c_str());
  2020. }
  2021. // print type counts
  2022. for (auto & kv : n_type) {
  2023. if (kv.second == 0) {
  2024. continue;
  2025. }
  2026. LLAMA_LOG_INFO("%s: - type %4s: %4d tensors\n", __func__, ggml_type_name(kv.first), kv.second);
  2027. }
  2028. }
  2029. if (!llama_mmap::SUPPORTED) {
  2030. LLAMA_LOG_WARN("%s: mmap is not supported on this platform\n", __func__);
  2031. use_mmap = false;
  2032. }
  2033. this->use_mmap = use_mmap;
  2034. }
  2035. ~llama_model_loader() {
  2036. if (ctx_gguf) {
  2037. gguf_free(ctx_gguf);
  2038. }
  2039. if (ctx_meta) {
  2040. ggml_free(ctx_meta);
  2041. }
  2042. }
  2043. template<typename T>
  2044. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2045. get_arr_n(const std::string & key, T & result, const bool required = true) {
  2046. const int kid = gguf_find_key(ctx_gguf, key.c_str());
  2047. if (kid < 0) {
  2048. if (required) {
  2049. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2050. }
  2051. return false;
  2052. }
  2053. struct GGUFMeta::ArrayInfo arr_info =
  2054. GGUFMeta::GKV<GGUFMeta::ArrayInfo>::get_kv(ctx_gguf, kid);
  2055. result = arr_info.length;
  2056. return true;
  2057. }
  2058. template<typename T>
  2059. typename std::enable_if<std::is_integral<T>::value, bool>::type
  2060. get_arr_n(const enum llm_kv kid, T & result, const bool required = true) {
  2061. return get_arr_n(llm_kv(kid), result, required);
  2062. }
  2063. template<typename T>
  2064. bool get_key(const std::string & key, T & result, const bool required = true) {
  2065. auto it = kv_overrides.find(key);
  2066. const struct llama_model_kv_override * override =
  2067. it != kv_overrides.end() ? &it->second : nullptr;
  2068. const bool found = GGUFMeta::GKV<T>::set(ctx_gguf, key, result, override);
  2069. if (required && !found) {
  2070. throw std::runtime_error(format("key not found in model: %s", key.c_str()));
  2071. }
  2072. return found;
  2073. }
  2074. template<typename T>
  2075. bool get_key(const enum llm_kv kid, T & result, const bool required = true) {
  2076. return get_key(llm_kv(kid), result, required);
  2077. }
  2078. std::string get_arch_name() const {
  2079. return arch_name;
  2080. }
  2081. enum llm_arch get_arch() const {
  2082. return llm_kv.arch;
  2083. }
  2084. const char * get_tensor_name(int i) const {
  2085. return gguf_get_tensor_name(ctx_gguf, i);
  2086. }
  2087. struct ggml_tensor * get_tensor_meta(const char * name) const {
  2088. return ggml_get_tensor(ctx_meta, name);
  2089. }
  2090. struct ggml_tensor * get_tensor_meta(int i) const {
  2091. return get_tensor_meta(get_tensor_name(i));
  2092. }
  2093. struct ggml_tensor * create_tensor_for(struct ggml_context * ctx, struct ggml_tensor * meta) {
  2094. struct ggml_tensor * tensor = ggml_dup_tensor(ctx, meta);
  2095. ggml_set_name(tensor, ggml_get_name(meta));
  2096. n_created++;
  2097. return tensor;
  2098. }
  2099. struct ggml_tensor * create_tensor(struct ggml_context * ctx, const std::string & name, const std::vector<int64_t> & ne, bool required = true) {
  2100. struct ggml_tensor * cur = ggml_get_tensor(ctx_meta, name.c_str());
  2101. if (cur == NULL) {
  2102. if (!required) {
  2103. return NULL;
  2104. }
  2105. throw std::runtime_error(format("%s: tensor '%s' not found", __func__, name.c_str()));
  2106. }
  2107. {
  2108. bool is_ok = true;
  2109. for (size_t i = 0; i < ne.size(); ++i) {
  2110. if (ne[i] != cur->ne[i]) {
  2111. is_ok = false;
  2112. break;
  2113. }
  2114. }
  2115. if (!is_ok) {
  2116. throw std::runtime_error(
  2117. format("%s: tensor '%s' has wrong shape; expected %s, got %s",
  2118. __func__, name.c_str(),
  2119. llama_format_tensor_shape(ne).c_str(),
  2120. llama_format_tensor_shape(cur).c_str()));
  2121. }
  2122. }
  2123. return create_tensor_for(ctx, cur);
  2124. }
  2125. void done_getting_tensors() const {
  2126. if (n_created != n_tensors) {
  2127. throw std::runtime_error(format("%s: wrong number of tensors; expected %d, got %d", __func__, n_tensors, n_created));
  2128. }
  2129. }
  2130. size_t file_offset(const char * name) const {
  2131. const int idx = gguf_find_tensor(ctx_gguf, name);
  2132. if (idx < 0) {
  2133. throw std::runtime_error(format("%s: tensor '%s' not found in the file", __func__, name));
  2134. }
  2135. return gguf_get_data_offset(ctx_gguf) + gguf_get_tensor_offset(ctx_gguf, idx);
  2136. }
  2137. void init_mapping(bool prefetch = true, llama_mlock * lmlock = nullptr) {
  2138. // prefetch the whole file - all the data is needed anyway
  2139. if (use_mmap) {
  2140. mapping.reset(new llama_mmap(&file, prefetch ? -1 : 0, ggml_is_numa()));
  2141. }
  2142. // compute the total size of all tensors for progress reporting
  2143. for (int i = 0; i < gguf_get_n_tensors(ctx_gguf); i++) {
  2144. struct ggml_tensor * cur = ggml_get_tensor(ctx_meta, gguf_get_tensor_name(ctx_gguf, i));
  2145. size_data += ggml_nbytes(cur);
  2146. }
  2147. if (use_mmap && mapping) {
  2148. if (lmlock) {
  2149. lmlock->init(mapping->addr);
  2150. }
  2151. mmap_used_first = mapping->size;
  2152. }
  2153. }
  2154. void get_mapping_range(size_t * first, size_t * last, ggml_context * ctx) const {
  2155. GGML_ASSERT(mapping);
  2156. *first = mapping->size;
  2157. *last = 0;
  2158. for (ggml_tensor * tensor = ggml_get_first_tensor(ctx); tensor; tensor = ggml_get_next_tensor(ctx, tensor)) {
  2159. const size_t offs = file_offset(ggml_get_name(tensor));
  2160. *first = std::min(*first, offs);
  2161. *last = std::max(*last, offs + ggml_nbytes(tensor));
  2162. }
  2163. }
  2164. // for backwards compatibility, does not support ggml-backend
  2165. void load_data_for(struct ggml_tensor * cur) const {
  2166. const size_t offs = file_offset(ggml_get_name(cur));
  2167. if (use_mmap && mapping) {
  2168. if (cur->data == nullptr) {
  2169. cur->data = (uint8_t *)mapping->addr + offs;
  2170. } else {
  2171. memcpy(cur->data, (uint8_t *)mapping->addr + offs, ggml_nbytes(cur));
  2172. }
  2173. } else {
  2174. GGML_ASSERT(cur->data != nullptr);
  2175. file.seek(offs, SEEK_SET);
  2176. file.read_raw(cur->data, ggml_nbytes(cur));
  2177. }
  2178. }
  2179. size_t size_done = 0;
  2180. size_t size_data = 0;
  2181. size_t mmap_used_first = -1;
  2182. size_t mmap_used_last = 0;
  2183. // Returns false if cancelled by progress_callback
  2184. 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) {
  2185. GGML_ASSERT(size_data != 0 && "call init_mapping() first");
  2186. std::vector<no_init<uint8_t>> read_buf;
  2187. for (int i = 0; i < gguf_get_n_tensors(ctx_gguf); i++) {
  2188. struct ggml_tensor * cur = ggml_get_tensor(ctx, gguf_get_tensor_name(ctx_gguf, i));
  2189. if (!cur) {
  2190. // some tensors may be allocated in a different context
  2191. continue;
  2192. }
  2193. if (progress_callback) {
  2194. if (!progress_callback((float) size_done / size_data, progress_callback_user_data)) {
  2195. return false;
  2196. }
  2197. }
  2198. const size_t offs = file_offset(ggml_get_name(cur));
  2199. if (use_mmap && mapping) {
  2200. if (buf_mmap && cur->data == nullptr) {
  2201. ggml_backend_tensor_alloc(buf_mmap, cur, (uint8_t *) mapping->addr + offs);
  2202. if (lmlock) {
  2203. lmlock->grow_to(offs + ggml_nbytes(cur));
  2204. }
  2205. mmap_used_first = std::min(mmap_used_first, offs);
  2206. mmap_used_last = std::max(mmap_used_last, offs + ggml_nbytes(cur));
  2207. } else {
  2208. ggml_backend_tensor_set(cur, (uint8_t *) mapping->addr + offs, 0, ggml_nbytes(cur));
  2209. }
  2210. } else {
  2211. if (ggml_backend_buffer_is_host(cur->buffer)) {
  2212. file.seek(offs, SEEK_SET);
  2213. file.read_raw(cur->data, ggml_nbytes(cur));
  2214. } else {
  2215. read_buf.resize(ggml_nbytes(cur));
  2216. file.seek(offs, SEEK_SET);
  2217. file.read_raw(read_buf.data(), ggml_nbytes(cur));
  2218. ggml_backend_tensor_set(cur, read_buf.data(), 0, ggml_nbytes(cur));
  2219. }
  2220. }
  2221. size_done += ggml_nbytes(cur);
  2222. }
  2223. // check if this is the last call and do final cleanup
  2224. if (size_done >= size_data) {
  2225. // unmap offloaded tensors and metadata
  2226. if (use_mmap && mapping) {
  2227. mapping->unmap_fragment(0, mmap_used_first);
  2228. if (mmap_used_last != 0) {
  2229. mapping->unmap_fragment(mmap_used_last, mapping->size);
  2230. }
  2231. }
  2232. if (progress_callback) {
  2233. // Even though the model is done loading, we still honor
  2234. // cancellation since we need to free allocations.
  2235. return progress_callback(1.0f, progress_callback_user_data);
  2236. }
  2237. }
  2238. return true;
  2239. }
  2240. };
  2241. //
  2242. // load LLaMA models
  2243. //
  2244. static std::string llama_model_arch_name(llm_arch arch) {
  2245. auto it = LLM_ARCH_NAMES.find(arch);
  2246. if (it == LLM_ARCH_NAMES.end()) {
  2247. return "unknown";
  2248. }
  2249. return it->second;
  2250. }
  2251. static std::string llama_model_ftype_name(llama_ftype ftype) {
  2252. if (ftype & LLAMA_FTYPE_GUESSED) {
  2253. return llama_model_ftype_name((enum llama_ftype) (ftype & ~LLAMA_FTYPE_GUESSED)) + " (guessed)";
  2254. }
  2255. switch (ftype) {
  2256. case LLAMA_FTYPE_ALL_F32: return "all F32";
  2257. case LLAMA_FTYPE_MOSTLY_F16: return "F16";
  2258. case LLAMA_FTYPE_MOSTLY_Q4_0: return "Q4_0";
  2259. case LLAMA_FTYPE_MOSTLY_Q4_1: return "Q4_1";
  2260. case LLAMA_FTYPE_MOSTLY_Q4_1_SOME_F16:
  2261. return "Q4_1, some F16";
  2262. case LLAMA_FTYPE_MOSTLY_Q5_0: return "Q5_0";
  2263. case LLAMA_FTYPE_MOSTLY_Q5_1: return "Q5_1";
  2264. case LLAMA_FTYPE_MOSTLY_Q8_0: return "Q8_0";
  2265. // K-quants
  2266. case LLAMA_FTYPE_MOSTLY_Q2_K: return "Q2_K - Medium";
  2267. case LLAMA_FTYPE_MOSTLY_Q2_K_S: return "Q2_K - Small";
  2268. case LLAMA_FTYPE_MOSTLY_Q3_K_S: return "Q3_K - Small";
  2269. case LLAMA_FTYPE_MOSTLY_Q3_K_M: return "Q3_K - Medium";
  2270. case LLAMA_FTYPE_MOSTLY_Q3_K_L: return "Q3_K - Large";
  2271. case LLAMA_FTYPE_MOSTLY_Q4_K_S: return "Q4_K - Small";
  2272. case LLAMA_FTYPE_MOSTLY_Q4_K_M: return "Q4_K - Medium";
  2273. case LLAMA_FTYPE_MOSTLY_Q5_K_S: return "Q5_K - Small";
  2274. case LLAMA_FTYPE_MOSTLY_Q5_K_M: return "Q5_K - Medium";
  2275. case LLAMA_FTYPE_MOSTLY_Q6_K: return "Q6_K";
  2276. case LLAMA_FTYPE_MOSTLY_IQ2_XXS:return "IQ2_XSS - 2.0625 bpw";
  2277. case LLAMA_FTYPE_MOSTLY_IQ2_XS: return "IQ2_XS - 2.3125 bpw";
  2278. default: return "unknown, may not work";
  2279. }
  2280. }
  2281. static const char * llama_model_type_name(e_model type) {
  2282. switch (type) {
  2283. case MODEL_1B: return "1B";
  2284. case MODEL_3B: return "3B";
  2285. case MODEL_7B: return "7B";
  2286. case MODEL_8B: return "8B";
  2287. case MODEL_13B: return "13B";
  2288. case MODEL_15B: return "15B";
  2289. case MODEL_30B: return "30B";
  2290. case MODEL_34B: return "34B";
  2291. case MODEL_40B: return "40B";
  2292. case MODEL_65B: return "65B";
  2293. case MODEL_70B: return "70B";
  2294. case MODEL_SMALL: return "0.1B";
  2295. case MODEL_MEDIUM: return "0.4B";
  2296. case MODEL_LARGE: return "0.8B";
  2297. case MODEL_XL: return "1.5B";
  2298. default: return "?B";
  2299. }
  2300. }
  2301. static void llm_load_arch(llama_model_loader & ml, llama_model & model) {
  2302. model.arch = ml.get_arch();
  2303. if (model.arch == LLM_ARCH_UNKNOWN) {
  2304. throw std::runtime_error("unknown model architecture: '" + ml.get_arch_name() + "'");
  2305. }
  2306. }
  2307. static void llm_load_hparams(
  2308. llama_model_loader & ml,
  2309. llama_model & model) {
  2310. auto & hparams = model.hparams;
  2311. const gguf_context * ctx = ml.ctx_gguf;
  2312. // get metadata as string
  2313. for (int i = 0; i < gguf_get_n_kv(ctx); i++) {
  2314. enum gguf_type type = gguf_get_kv_type(ctx, i);
  2315. if (type == GGUF_TYPE_ARRAY) {
  2316. continue;
  2317. }
  2318. const char * name = gguf_get_key(ctx, i);
  2319. const std::string value = gguf_kv_to_str(ctx, i);
  2320. model.gguf_kv.emplace(name, value);
  2321. }
  2322. // get general kv
  2323. ml.get_key(LLM_KV_GENERAL_NAME, model.name, false);
  2324. // get hparams kv
  2325. ml.get_arr_n(LLM_KV_TOKENIZER_LIST, hparams.n_vocab);
  2326. ml.get_key (LLM_KV_CONTEXT_LENGTH, hparams.n_ctx_train);
  2327. ml.get_key (LLM_KV_EMBEDDING_LENGTH, hparams.n_embd);
  2328. ml.get_key (LLM_KV_FEED_FORWARD_LENGTH, hparams.n_ff);
  2329. ml.get_key (LLM_KV_ATTENTION_HEAD_COUNT, hparams.n_head);
  2330. ml.get_key (LLM_KV_BLOCK_COUNT, hparams.n_layer);
  2331. ml.get_key (LLM_KV_EXPERT_COUNT, hparams.n_expert, false);
  2332. ml.get_key (LLM_KV_EXPERT_USED_COUNT, hparams.n_expert_used, false);
  2333. GGML_ASSERT(hparams.n_expert <= LLAMA_MAX_EXPERTS);
  2334. GGML_ASSERT(hparams.n_expert_used <= hparams.n_expert);
  2335. if (hparams.n_expert > 0) {
  2336. GGML_ASSERT(hparams.n_expert_used > 0);
  2337. } else {
  2338. GGML_ASSERT(hparams.n_expert_used == 0);
  2339. }
  2340. // n_head_kv is optional, default to n_head
  2341. hparams.n_head_kv = hparams.n_head;
  2342. ml.get_key(LLM_KV_ATTENTION_HEAD_COUNT_KV, hparams.n_head_kv, false);
  2343. bool rope_finetuned = false;
  2344. ml.get_key(LLM_KV_ROPE_SCALING_FINETUNED, rope_finetuned, false);
  2345. hparams.rope_finetuned = rope_finetuned;
  2346. hparams.n_yarn_orig_ctx = hparams.n_ctx_train;
  2347. ml.get_key(LLM_KV_ROPE_SCALING_ORIG_CTX_LEN, hparams.n_yarn_orig_ctx, false);
  2348. // rope_freq_base (optional)
  2349. hparams.rope_freq_base_train = 10000.0f;
  2350. ml.get_key(LLM_KV_ROPE_FREQ_BASE, hparams.rope_freq_base_train, false);
  2351. std::string rope_scaling("linear");
  2352. ml.get_key(LLM_KV_ROPE_SCALING_TYPE, rope_scaling, false);
  2353. hparams.rope_scaling_type_train = llama_rope_scaling_type_from_string(rope_scaling);
  2354. GGML_ASSERT(hparams.rope_scaling_type_train != LLAMA_ROPE_SCALING_UNSPECIFIED);
  2355. // rope_freq_scale (inverse of the kv) is optional
  2356. float ropescale = 0.0f;
  2357. if (!ml.get_key(LLM_KV_ROPE_SCALING_FACTOR, ropescale, false)) {
  2358. // try the old key name
  2359. ml.get_key(LLM_KV_ROPE_SCALE_LINEAR, ropescale, false);
  2360. }
  2361. hparams.rope_freq_scale_train = ropescale == 0.0f ? 1.0f : 1.0f/ropescale;
  2362. // sanity check for n_rot (optional)
  2363. {
  2364. hparams.n_rot = hparams.n_embd / hparams.n_head;
  2365. ml.get_key(LLM_KV_ROPE_DIMENSION_COUNT, hparams.n_rot, false);
  2366. if (model.arch == LLM_ARCH_LLAMA || model.arch == LLM_ARCH_FALCON) {
  2367. if (hparams.n_rot != hparams.n_embd / hparams.n_head) {
  2368. throw std::runtime_error(format("invalid n_rot: %u, expected %u", hparams.n_rot, hparams.n_embd / hparams.n_head));
  2369. }
  2370. }
  2371. // gpt-neox n_rot = rotary_pct * (n_embd / n_head)
  2372. // gpt-j n_rot = rotary_dim
  2373. }
  2374. hparams.n_embd_head_k = hparams.n_embd / hparams.n_head;
  2375. ml.get_key(LLM_KV_ATTENTION_KEY_LENGTH, hparams.n_embd_head_k, false);
  2376. hparams.n_embd_head_v = hparams.n_embd / hparams.n_head;
  2377. ml.get_key(LLM_KV_ATTENTION_VALUE_LENGTH, hparams.n_embd_head_v, false);
  2378. // arch-specific KVs
  2379. switch (model.arch) {
  2380. case LLM_ARCH_LLAMA:
  2381. {
  2382. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2383. switch (hparams.n_layer) {
  2384. case 22: model.type = e_model::MODEL_1B; break;
  2385. case 26: model.type = e_model::MODEL_3B; break;
  2386. case 32: model.type = e_model::MODEL_7B; break;
  2387. case 40: model.type = e_model::MODEL_13B; break;
  2388. case 48: model.type = e_model::MODEL_34B; break;
  2389. case 60: model.type = e_model::MODEL_30B; break;
  2390. case 80: model.type = hparams.n_head == hparams.n_head_kv ? e_model::MODEL_65B : e_model::MODEL_70B; break;
  2391. default: model.type = e_model::MODEL_UNKNOWN;
  2392. }
  2393. } break;
  2394. case LLM_ARCH_FALCON:
  2395. {
  2396. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2397. switch (hparams.n_layer) {
  2398. case 32: model.type = e_model::MODEL_7B; break;
  2399. case 60: model.type = e_model::MODEL_40B; break;
  2400. default: model.type = e_model::MODEL_UNKNOWN;
  2401. }
  2402. } break;
  2403. case LLM_ARCH_BAICHUAN:
  2404. {
  2405. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2406. switch (hparams.n_layer) {
  2407. case 32: model.type = e_model::MODEL_7B; break;
  2408. case 40: model.type = e_model::MODEL_13B; break;
  2409. default: model.type = e_model::MODEL_UNKNOWN;
  2410. }
  2411. } break;
  2412. case LLM_ARCH_STARCODER:
  2413. {
  2414. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2415. switch (hparams.n_layer) {
  2416. case 24: model.type = e_model::MODEL_1B; break;
  2417. case 36: model.type = e_model::MODEL_3B; break;
  2418. case 42: model.type = e_model::MODEL_7B; break;
  2419. case 40: model.type = e_model::MODEL_15B; break;
  2420. default: model.type = e_model::MODEL_UNKNOWN;
  2421. }
  2422. } break;
  2423. case LLM_ARCH_PERSIMMON:
  2424. {
  2425. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2426. switch (hparams.n_layer) {
  2427. case 36: model.type = e_model::MODEL_8B; break;
  2428. default: model.type = e_model::MODEL_UNKNOWN;
  2429. }
  2430. } break;
  2431. case LLM_ARCH_REFACT:
  2432. {
  2433. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2434. switch (hparams.n_layer) {
  2435. case 32: model.type = e_model::MODEL_1B; break;
  2436. default: model.type = e_model::MODEL_UNKNOWN;
  2437. }
  2438. } break;
  2439. case LLM_ARCH_BLOOM:
  2440. {
  2441. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2442. switch (hparams.n_layer) {
  2443. case 24: model.type = e_model::MODEL_1B; break;
  2444. case 30:
  2445. switch (hparams.n_embd) {
  2446. case 2560: model.type = e_model::MODEL_3B; break;
  2447. case 4096: model.type = e_model::MODEL_7B; break;
  2448. } break;
  2449. }
  2450. } break;
  2451. case LLM_ARCH_MPT:
  2452. {
  2453. hparams.f_clamp_kqv = 0.0f;
  2454. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2455. ml.get_key(LLM_KV_ATTENTION_CLAMP_KQV, hparams.f_clamp_kqv, false);
  2456. ml.get_key(LLM_KV_ATTENTION_MAX_ALIBI_BIAS, hparams.f_max_alibi_bias);
  2457. switch (hparams.n_layer) {
  2458. case 32: model.type = e_model::MODEL_7B; break;
  2459. case 48: model.type = e_model::MODEL_30B; break;
  2460. default: model.type = e_model::MODEL_UNKNOWN;
  2461. }
  2462. } break;
  2463. case LLM_ARCH_STABLELM:
  2464. {
  2465. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2466. switch (hparams.n_layer) {
  2467. case 32: model.type = e_model::MODEL_3B; break;
  2468. default: model.type = e_model::MODEL_UNKNOWN;
  2469. }
  2470. } break;
  2471. case LLM_ARCH_QWEN:
  2472. {
  2473. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2474. switch (hparams.n_layer) {
  2475. case 32: model.type = e_model::MODEL_7B; break;
  2476. case 40: model.type = e_model::MODEL_13B; break;
  2477. default: model.type = e_model::MODEL_UNKNOWN;
  2478. }
  2479. } break;
  2480. case LLM_ARCH_QWEN2:
  2481. {
  2482. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2483. switch (hparams.n_layer) {
  2484. case 24: model.type = e_model::MODEL_1B; break;
  2485. case 32: model.type = e_model::MODEL_7B; break;
  2486. case 40: model.type = e_model::MODEL_13B; break;
  2487. case 80: model.type = e_model::MODEL_70B; break;
  2488. default: model.type = e_model::MODEL_UNKNOWN;
  2489. }
  2490. } break;
  2491. case LLM_ARCH_PHI2:
  2492. {
  2493. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2494. switch (hparams.n_layer) {
  2495. case 24: model.type = e_model::MODEL_1B; break;
  2496. case 32: model.type = e_model::MODEL_3B; break;
  2497. default: model.type = e_model::MODEL_UNKNOWN;
  2498. }
  2499. } break;
  2500. case LLM_ARCH_PLAMO:
  2501. {
  2502. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);
  2503. switch (hparams.n_layer) {
  2504. case 40: model.type = e_model::MODEL_13B; break;
  2505. default: model.type = e_model::MODEL_UNKNOWN;
  2506. }
  2507. } break;
  2508. case LLM_ARCH_GPT2:
  2509. {
  2510. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2511. switch (hparams.n_layer) {
  2512. case 12: model.type = e_model::MODEL_SMALL; break;
  2513. case 24: model.type = e_model::MODEL_MEDIUM; break;
  2514. case 36: model.type = e_model::MODEL_LARGE; break;
  2515. case 48: model.type = e_model::MODEL_XL; break;
  2516. default: model.type = e_model::MODEL_UNKNOWN;
  2517. }
  2518. } break;
  2519. case LLM_ARCH_CODESHELL:
  2520. {
  2521. ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps);
  2522. switch (hparams.n_layer) {
  2523. case 42: model.type = e_model::MODEL_SMALL; break;
  2524. default: model.type = e_model::MODEL_UNKNOWN;
  2525. }
  2526. } break;
  2527. default: (void)0;
  2528. }
  2529. model.ftype = ml.ftype;
  2530. }
  2531. // TODO: This should probably be in llama.h
  2532. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special = false);
  2533. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch);
  2534. static void llm_load_vocab(
  2535. llama_model_loader & ml,
  2536. llama_model & model) {
  2537. auto & vocab = model.vocab;
  2538. struct gguf_context * ctx = ml.ctx_gguf;
  2539. const auto kv = LLM_KV(model.arch);
  2540. const int token_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_LIST).c_str());
  2541. if (token_idx == -1) {
  2542. throw std::runtime_error("cannot find tokenizer vocab in model file\n");
  2543. }
  2544. const float * scores = nullptr;
  2545. const int score_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_SCORES).c_str());
  2546. if (score_idx != -1) {
  2547. scores = (const float * ) gguf_get_arr_data(ctx, score_idx);
  2548. }
  2549. const int * toktypes = nullptr;
  2550. const int toktype_idx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_TOKEN_TYPE).c_str());
  2551. if (toktype_idx != -1) {
  2552. toktypes = (const int * ) gguf_get_arr_data(ctx, toktype_idx);
  2553. }
  2554. // determine vocab type
  2555. {
  2556. std::string tokenizer_name;
  2557. ml.get_key(LLM_KV_TOKENIZER_MODEL, tokenizer_name);
  2558. if (tokenizer_name == "llama") {
  2559. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  2560. // default special tokens
  2561. vocab.special_bos_id = 1;
  2562. vocab.special_eos_id = 2;
  2563. vocab.special_unk_id = 0;
  2564. vocab.special_sep_id = -1;
  2565. vocab.special_pad_id = -1;
  2566. } else if (tokenizer_name == "gpt2") {
  2567. vocab.type = LLAMA_VOCAB_TYPE_BPE;
  2568. // read bpe merges and populate bpe ranks
  2569. const int merges_keyidx = gguf_find_key(ctx, kv(LLM_KV_TOKENIZER_MERGES).c_str());
  2570. if (merges_keyidx == -1) {
  2571. throw std::runtime_error("cannot find tokenizer merges in model file\n");
  2572. }
  2573. const int n_merges = gguf_get_arr_n(ctx, merges_keyidx);
  2574. for (int i = 0; i < n_merges; i++) {
  2575. const std::string word = gguf_get_arr_str(ctx, merges_keyidx, i);
  2576. GGML_ASSERT(codepoints_from_utf8(word).size() > 0);
  2577. std::string first;
  2578. std::string second;
  2579. const size_t pos = word.find(' ', 1);
  2580. if (pos != std::string::npos) {
  2581. first = word.substr(0, pos);
  2582. second = word.substr(pos + 1);
  2583. }
  2584. vocab.bpe_ranks.emplace(std::make_pair(first, second), i);
  2585. }
  2586. // default special tokens
  2587. vocab.special_bos_id = 11;
  2588. vocab.special_eos_id = 11;
  2589. vocab.special_unk_id = -1;
  2590. vocab.special_sep_id = -1;
  2591. vocab.special_pad_id = -1;
  2592. } else {
  2593. LLAMA_LOG_WARN("%s: unknown tokenizer: '%s'", __func__, tokenizer_name.c_str());
  2594. LLAMA_LOG_WARN("%s: using default tokenizer: 'llama'", __func__);
  2595. vocab.type = LLAMA_VOCAB_TYPE_SPM;
  2596. }
  2597. }
  2598. const uint32_t n_vocab = gguf_get_arr_n(ctx, token_idx);
  2599. vocab.id_to_token.resize(n_vocab);
  2600. for (uint32_t i = 0; i < n_vocab; i++) {
  2601. std::string word = gguf_get_arr_str(ctx, token_idx, i);
  2602. GGML_ASSERT(codepoints_from_utf8(word).size() > 0);
  2603. vocab.token_to_id[word] = i;
  2604. auto & token_data = vocab.id_to_token[i];
  2605. token_data.text = std::move(word);
  2606. token_data.score = scores ? scores[i] : 0.0f;
  2607. token_data.type = toktypes ? (llama_token_type) toktypes[i] : LLAMA_TOKEN_TYPE_NORMAL;
  2608. }
  2609. GGML_ASSERT(vocab.id_to_token.size() == vocab.token_to_id.size());
  2610. // determine the newline token: LLaMA "<0x0A>" == 10 == '\n', Falcon 193 == '\n'
  2611. if (vocab.type == LLAMA_VOCAB_TYPE_SPM) {
  2612. vocab.linefeed_id = llama_byte_to_token(vocab, '\n');
  2613. } else {
  2614. const std::vector<int> ids = llama_tokenize_internal(vocab, "\u010A", false);
  2615. GGML_ASSERT(!ids.empty() && "model vocab missing newline token");
  2616. vocab.linefeed_id = ids[0];
  2617. }
  2618. // special tokens
  2619. {
  2620. const std::vector<std::pair<enum llm_kv, int32_t &>> special_token_types = {
  2621. { LLM_KV_TOKENIZER_BOS_ID, vocab.special_bos_id },
  2622. { LLM_KV_TOKENIZER_EOS_ID, vocab.special_eos_id },
  2623. { LLM_KV_TOKENIZER_UNK_ID, vocab.special_unk_id },
  2624. { LLM_KV_TOKENIZER_SEP_ID, vocab.special_sep_id },
  2625. { LLM_KV_TOKENIZER_PAD_ID, vocab.special_pad_id },
  2626. };
  2627. for (const auto & it : special_token_types) {
  2628. const std::string & key = kv(std::get<0>(it));
  2629. int32_t & id = std::get<1>(it);
  2630. uint32_t new_id;
  2631. if (!ml.get_key(std::get<0>(it), new_id, false)) {
  2632. continue;
  2633. }
  2634. if (new_id >= vocab.id_to_token.size()) {
  2635. LLAMA_LOG_WARN("%s: bad special token: '%s' = %ud, using default id %d\n",
  2636. __func__, key.c_str(), new_id, id);
  2637. } else {
  2638. id = new_id;
  2639. }
  2640. }
  2641. // Handle add_bos_token and add_eos_token
  2642. {
  2643. bool temp = true;
  2644. if (ml.get_key(LLM_KV_TOKENIZER_ADD_BOS, temp, false)) {
  2645. vocab.special_add_bos = int(temp);
  2646. }
  2647. if (ml.get_key(LLM_KV_TOKENIZER_ADD_EOS, temp, false)) {
  2648. vocab.special_add_eos = int(temp);
  2649. }
  2650. }
  2651. }
  2652. // build special tokens cache
  2653. {
  2654. // TODO: It is unclear (to me) at this point, whether special tokes are guaranteed to be of a deterministic type,
  2655. // and will always be correctly labeled in 'added_tokens.json' etc.
  2656. // The assumption is, since special tokens aren't meant to be exposed to end user, they are designed
  2657. // to be unmatchable by the tokenizer, therefore tokens from the vocab, which are unmatchable by the tokenizer
  2658. // are special tokens.
  2659. // From testing, this appears to correlate 1:1 with special tokens.
  2660. //
  2661. // Counting special tokens and verifying in only one direction
  2662. // is sufficient to detect difference in those two sets.
  2663. //
  2664. uint32_t special_tokens_count_by_type = 0;
  2665. uint32_t special_tokens_count_from_verification = 0;
  2666. bool special_tokens_definition_mismatch = false;
  2667. for (const auto & t : vocab.token_to_id) {
  2668. const auto & token = t.first;
  2669. const auto & id = t.second;
  2670. // Count all non-normal tokens in the vocab while iterating
  2671. if (vocab.id_to_token[id].type != LLAMA_TOKEN_TYPE_NORMAL) {
  2672. special_tokens_count_by_type++;
  2673. }
  2674. // Skip single character tokens
  2675. if (token.length() > 1) {
  2676. bool is_tokenizable = false;
  2677. // Split token string representation in two, in all possible ways
  2678. // and check if both halves can be matched to a valid token
  2679. for (unsigned i = 1; i < token.length();) {
  2680. const auto left = token.substr(0, i);
  2681. const auto right = token.substr(i);
  2682. // check if we didnt partition in the middle of a utf sequence
  2683. auto utf = utf8_len(left.at(left.length() - 1));
  2684. if (utf == 1) {
  2685. if (vocab.token_to_id.find(left) != vocab.token_to_id.end() &&
  2686. vocab.token_to_id.find(right) != vocab.token_to_id.end() ) {
  2687. is_tokenizable = true;
  2688. break;
  2689. }
  2690. i++;
  2691. } else {
  2692. // skip over the rest of multibyte utf sequence
  2693. i += utf - 1;
  2694. }
  2695. }
  2696. if (!is_tokenizable) {
  2697. // Some tokens are multibyte, but they are utf sequences with equivalent text length of 1
  2698. // it's faster to re-filter them here, since there are way less candidates now
  2699. // Calculate a total "utf" length of a token string representation
  2700. size_t utf8_str_len = 0;
  2701. for (unsigned i = 0; i < token.length();) {
  2702. utf8_str_len++;
  2703. i += utf8_len(token.at(i));
  2704. }
  2705. // And skip the ones which are one character
  2706. if (utf8_str_len > 1) {
  2707. // At this point what we have left are special tokens only
  2708. vocab.special_tokens_cache[token] = id;
  2709. // Count manually found special tokens
  2710. special_tokens_count_from_verification++;
  2711. // If this manually found special token is not marked as such, flag a mismatch
  2712. if (vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL) {
  2713. special_tokens_definition_mismatch = true;
  2714. }
  2715. }
  2716. }
  2717. }
  2718. }
  2719. if (special_tokens_definition_mismatch || special_tokens_count_from_verification != special_tokens_count_by_type) {
  2720. LLAMA_LOG_WARN("%s: mismatch in special tokens definition ( %u/%zu vs %u/%zu ).\n",
  2721. __func__,
  2722. special_tokens_count_from_verification, vocab.id_to_token.size(),
  2723. special_tokens_count_by_type, vocab.id_to_token.size()
  2724. );
  2725. } else {
  2726. LLAMA_LOG_INFO("%s: special tokens definition check successful ( %u/%zu ).\n",
  2727. __func__,
  2728. special_tokens_count_from_verification, vocab.id_to_token.size()
  2729. );
  2730. }
  2731. }
  2732. }
  2733. static void llm_load_print_meta(llama_model_loader & ml, llama_model & model) {
  2734. const auto & hparams = model.hparams;
  2735. const auto & vocab = model.vocab;
  2736. const auto rope_scaling_type = LLAMA_ROPE_SCALING_TYPES.at(hparams.rope_scaling_type_train);
  2737. // hparams
  2738. LLAMA_LOG_INFO("%s: format = %s\n", __func__, llama_file_version_name(ml.fver));
  2739. LLAMA_LOG_INFO("%s: arch = %s\n", __func__, LLM_ARCH_NAMES.at(model.arch).c_str());
  2740. LLAMA_LOG_INFO("%s: vocab type = %s\n", __func__, vocab.type == LLAMA_VOCAB_TYPE_SPM ? "SPM" : "BPE"); // TODO: fix
  2741. LLAMA_LOG_INFO("%s: n_vocab = %u\n", __func__, hparams.n_vocab);
  2742. LLAMA_LOG_INFO("%s: n_merges = %u\n", __func__, (int) vocab.bpe_ranks.size());
  2743. LLAMA_LOG_INFO("%s: n_ctx_train = %u\n", __func__, hparams.n_ctx_train);
  2744. LLAMA_LOG_INFO("%s: n_embd = %u\n", __func__, hparams.n_embd);
  2745. LLAMA_LOG_INFO("%s: n_head = %u\n", __func__, hparams.n_head);
  2746. LLAMA_LOG_INFO("%s: n_head_kv = %u\n", __func__, hparams.n_head_kv);
  2747. LLAMA_LOG_INFO("%s: n_layer = %u\n", __func__, hparams.n_layer);
  2748. LLAMA_LOG_INFO("%s: n_rot = %u\n", __func__, hparams.n_rot);
  2749. LLAMA_LOG_INFO("%s: n_embd_head_k = %u\n", __func__, hparams.n_embd_head_k);
  2750. LLAMA_LOG_INFO("%s: n_embd_head_v = %u\n", __func__, hparams.n_embd_head_v);
  2751. LLAMA_LOG_INFO("%s: n_gqa = %u\n", __func__, hparams.n_gqa());
  2752. LLAMA_LOG_INFO("%s: n_embd_k_gqa = %u\n", __func__, hparams.n_embd_k_gqa());
  2753. LLAMA_LOG_INFO("%s: n_embd_v_gqa = %u\n", __func__, hparams.n_embd_v_gqa());
  2754. LLAMA_LOG_INFO("%s: f_norm_eps = %.1e\n", __func__, hparams.f_norm_eps);
  2755. LLAMA_LOG_INFO("%s: f_norm_rms_eps = %.1e\n", __func__, hparams.f_norm_rms_eps);
  2756. LLAMA_LOG_INFO("%s: f_clamp_kqv = %.1e\n", __func__, hparams.f_clamp_kqv);
  2757. LLAMA_LOG_INFO("%s: f_max_alibi_bias = %.1e\n", __func__, hparams.f_max_alibi_bias);
  2758. LLAMA_LOG_INFO("%s: n_ff = %u\n", __func__, hparams.n_ff);
  2759. LLAMA_LOG_INFO("%s: n_expert = %u\n", __func__, hparams.n_expert);
  2760. LLAMA_LOG_INFO("%s: n_expert_used = %u\n", __func__, hparams.n_expert_used);
  2761. LLAMA_LOG_INFO("%s: rope scaling = %s\n", __func__, rope_scaling_type.c_str());
  2762. LLAMA_LOG_INFO("%s: freq_base_train = %.1f\n", __func__, hparams.rope_freq_base_train);
  2763. LLAMA_LOG_INFO("%s: freq_scale_train = %g\n", __func__, hparams.rope_freq_scale_train);
  2764. LLAMA_LOG_INFO("%s: n_yarn_orig_ctx = %u\n", __func__, hparams.n_yarn_orig_ctx);
  2765. LLAMA_LOG_INFO("%s: rope_finetuned = %s\n", __func__, hparams.rope_finetuned ? "yes" : "unknown");
  2766. LLAMA_LOG_INFO("%s: model type = %s\n", __func__, llama_model_type_name(model.type));
  2767. LLAMA_LOG_INFO("%s: model ftype = %s\n", __func__, llama_model_ftype_name(model.ftype).c_str());
  2768. if (ml.n_elements >= 1e12) {
  2769. LLAMA_LOG_INFO("%s: model params = %.2f T\n", __func__, ml.n_elements*1e-12);
  2770. } else if (ml.n_elements >= 1e9) {
  2771. LLAMA_LOG_INFO("%s: model params = %.2f B\n", __func__, ml.n_elements*1e-9);
  2772. } else if (ml.n_elements >= 1e6) {
  2773. LLAMA_LOG_INFO("%s: model params = %.2f M\n", __func__, ml.n_elements*1e-6);
  2774. } else {
  2775. LLAMA_LOG_INFO("%s: model params = %.2f K\n", __func__, ml.n_elements*1e-3);
  2776. }
  2777. if (ml.n_bytes < GiB) {
  2778. 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);
  2779. } else {
  2780. 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);
  2781. }
  2782. // general kv
  2783. LLAMA_LOG_INFO("%s: general.name = %s\n", __func__, model.name.c_str());
  2784. // special tokens
  2785. 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() ); }
  2786. 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() ); }
  2787. 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() ); }
  2788. 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() ); }
  2789. 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() ); }
  2790. 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() ); }
  2791. }
  2792. // Returns false if cancelled by progress_callback
  2793. static bool llm_load_tensors(
  2794. llama_model_loader & ml,
  2795. llama_model & model,
  2796. int n_gpu_layers,
  2797. enum llama_split_mode split_mode,
  2798. int main_gpu,
  2799. const float * tensor_split,
  2800. bool use_mlock,
  2801. llama_progress_callback progress_callback,
  2802. void * progress_callback_user_data) {
  2803. model.t_start_us = ggml_time_us();
  2804. auto & hparams = model.hparams;
  2805. model.split_mode = split_mode;
  2806. model.main_gpu = main_gpu;
  2807. model.n_gpu_layers = n_gpu_layers;
  2808. const int64_t n_layer = hparams.n_layer;
  2809. const int64_t i_gpu_start = std::max((int64_t) hparams.n_layer - n_gpu_layers, (int64_t) 0);
  2810. // there is very little benefit to offloading the input layer, so always keep it on the CPU
  2811. model.buft_input = llama_default_buffer_type_cpu(true);
  2812. model.buft_layer.resize(n_layer);
  2813. // assign cpu layers
  2814. for (int64_t i = 0; i < i_gpu_start; ++i) {
  2815. model.buft_layer[i] = llama_default_buffer_type_cpu(true);
  2816. }
  2817. #ifdef GGML_USE_CUBLAS
  2818. if (split_mode == LLAMA_SPLIT_LAYER) {
  2819. // calculate the split points
  2820. int device_count = ggml_backend_cuda_get_device_count();
  2821. bool all_zero = tensor_split == nullptr || std::all_of(tensor_split, tensor_split + device_count, [](float x) { return x == 0.0f; });
  2822. float splits[GGML_CUDA_MAX_DEVICES];
  2823. if (all_zero) {
  2824. // default split, by free memory
  2825. for (int i = 0; i < device_count; ++i) {
  2826. size_t total;
  2827. size_t free;
  2828. ggml_backend_cuda_get_device_memory(i, &total, &free);
  2829. splits[i] = free;
  2830. }
  2831. } else {
  2832. std::copy(tensor_split, tensor_split + device_count, splits);
  2833. }
  2834. // sum and normalize the splits to get the split points
  2835. float split_sum = 0.0f;
  2836. for (int i = 0; i < device_count; ++i) {
  2837. split_sum += splits[i];
  2838. splits[i] = split_sum;
  2839. }
  2840. for (int i = 0; i < device_count; ++i) {
  2841. splits[i] /= split_sum;
  2842. }
  2843. // assign the repeating layers to the devices according to the splits
  2844. int act_gpu_layers = std::min(n_gpu_layers, (int)n_layer + 1);
  2845. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  2846. int layer_gpu = std::upper_bound(splits, splits + device_count, float(i - i_gpu_start)/act_gpu_layers) - splits;
  2847. model.buft_layer[i] = llama_default_buffer_type_offload(layer_gpu);
  2848. }
  2849. // assign the output layer
  2850. if (n_gpu_layers > n_layer) {
  2851. int layer_gpu = std::upper_bound(splits, splits + device_count, float(act_gpu_layers - 1)/act_gpu_layers) - splits;
  2852. model.buft_output = llama_default_buffer_type_offload(layer_gpu);
  2853. } else {
  2854. model.buft_output = llama_default_buffer_type_cpu(true);
  2855. }
  2856. } else
  2857. #endif
  2858. {
  2859. ggml_backend_buffer_type_t split_buft;
  2860. if (split_mode == LLAMA_SPLIT_ROW) {
  2861. split_buft = llama_default_buffer_type_split(main_gpu, tensor_split);
  2862. } else {
  2863. // LLAMA_SPLIT_NONE or LLAMA_SPLIT_LAYER in backends where it is not supported
  2864. split_buft = llama_default_buffer_type_offload(main_gpu);
  2865. }
  2866. // assign the repeating layers
  2867. for (int64_t i = i_gpu_start; i < n_layer; ++i) {
  2868. model.buft_layer[i] = {
  2869. split_buft,
  2870. llama_default_buffer_type_offload(main_gpu)
  2871. };
  2872. }
  2873. // assign the output layer
  2874. if (n_gpu_layers > n_layer) {
  2875. model.buft_output = {
  2876. split_buft,
  2877. llama_default_buffer_type_offload(main_gpu)
  2878. };
  2879. } else {
  2880. model.buft_output = llama_default_buffer_type_cpu(true);
  2881. }
  2882. }
  2883. // count used buffer types
  2884. std::map<ggml_backend_buffer_type_t, int> buft_layer_count;
  2885. buft_layer_count[model.buft_input.buft]++;
  2886. buft_layer_count[model.buft_input.buft_matrix]++;
  2887. buft_layer_count[model.buft_output.buft]++;
  2888. buft_layer_count[model.buft_output.buft_matrix]++;
  2889. for (int64_t i = 0; i < n_layer; ++i) {
  2890. buft_layer_count[model.buft_layer[i].buft]++;
  2891. buft_layer_count[model.buft_layer[i].buft_matrix]++;
  2892. }
  2893. // create one context per buffer type
  2894. size_t ctx_size = ggml_tensor_overhead()*ml.n_tensors;
  2895. std::map<ggml_backend_buffer_type_t, ggml_context *> ctx_map;
  2896. for (auto & it : buft_layer_count) {
  2897. struct ggml_init_params params = {
  2898. /*.mem_size =*/ ctx_size,
  2899. /*.mem_buffer =*/ NULL,
  2900. /*.no_alloc =*/ true,
  2901. };
  2902. ggml_context * ctx = ggml_init(params);
  2903. if (!ctx) {
  2904. throw std::runtime_error(format("failed to create context"));
  2905. }
  2906. ctx_map[it.first] = ctx;
  2907. model.ctxs.push_back(ctx);
  2908. }
  2909. LLAMA_LOG_INFO("%s: ggml ctx size = %7.2f MiB\n", __func__, model.ctxs.size()*ctx_size/1024.0/1024.0);
  2910. // create tensors for the weights
  2911. {
  2912. const int64_t n_embd = hparams.n_embd;
  2913. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  2914. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  2915. const int64_t n_embd_gqa = n_embd_v_gqa;
  2916. const int64_t n_vocab = hparams.n_vocab;
  2917. const int64_t n_ff = hparams.n_ff;
  2918. GGML_ASSERT(n_embd_gqa == n_embd_k_gqa);
  2919. ggml_context * ctx_input = ctx_map.at(model.buft_input.buft);
  2920. ggml_context * ctx_output = ctx_map.at(model.buft_output.buft);
  2921. ggml_context * ctx_output_split = ctx_map.at(model.buft_output.buft_matrix);
  2922. auto ctx_for_layer = [&](int i) { return ctx_map.at(model.buft_layer[i].buft); };
  2923. auto ctx_for_layer_split = [&](int i) { return ctx_map.at(model.buft_layer[i].buft_matrix); };
  2924. model.layers.resize(n_layer);
  2925. const auto tn = LLM_TN(model.arch);
  2926. switch (model.arch) {
  2927. case LLM_ARCH_LLAMA:
  2928. case LLM_ARCH_REFACT:
  2929. {
  2930. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  2931. // output
  2932. {
  2933. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  2934. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  2935. }
  2936. for (int i = 0; i < n_layer; ++i) {
  2937. ggml_context * ctx_layer = ctx_for_layer(i);
  2938. ggml_context * ctx_split = ctx_for_layer_split(i);
  2939. auto & layer = model.layers[i];
  2940. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  2941. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  2942. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  2943. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  2944. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  2945. // optional bias tensors
  2946. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd}, false);
  2947. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa}, false);
  2948. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa}, false);
  2949. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd}, false);
  2950. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  2951. layer.ffn_gate_inp = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd}, false);
  2952. if (layer.ffn_gate_inp == nullptr) {
  2953. GGML_ASSERT(hparams.n_expert == 0);
  2954. GGML_ASSERT(hparams.n_expert_used == 0);
  2955. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  2956. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  2957. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  2958. } else {
  2959. GGML_ASSERT(hparams.n_expert > 0);
  2960. GGML_ASSERT(hparams.n_expert_used > 0);
  2961. // MoE branch
  2962. for (uint32_t x = 0; x < hparams.n_expert; ++x) {
  2963. layer.ffn_gate_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE_EXP, "weight", i, x), {n_embd, n_ff});
  2964. layer.ffn_down_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN_EXP, "weight", i, x), { n_ff, n_embd});
  2965. layer.ffn_up_exp[x] = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP_EXP, "weight", i, x), {n_embd, n_ff});
  2966. }
  2967. }
  2968. }
  2969. } break;
  2970. case LLM_ARCH_BAICHUAN:
  2971. {
  2972. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  2973. {
  2974. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  2975. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  2976. }
  2977. for (int i = 0; i < n_layer; ++i) {
  2978. ggml_context * ctx_layer = ctx_for_layer(i);
  2979. ggml_context * ctx_split = ctx_for_layer_split(i);
  2980. auto & layer = model.layers[i];
  2981. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  2982. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  2983. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  2984. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  2985. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  2986. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  2987. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  2988. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  2989. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  2990. }
  2991. } break;
  2992. case LLM_ARCH_FALCON:
  2993. {
  2994. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  2995. // output
  2996. {
  2997. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  2998. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  2999. if (gguf_find_tensor(ml.ctx_gguf, tn(LLM_TENSOR_OUTPUT, "weight").c_str()) >= 0) {
  3000. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3001. } else {
  3002. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}); // needs to be on GPU
  3003. ml.n_created--; // artificial tensor
  3004. }
  3005. }
  3006. for (int i = 0; i < n_layer; ++i) {
  3007. ggml_context * ctx_layer = ctx_for_layer(i);
  3008. ggml_context * ctx_split = ctx_for_layer_split(i);
  3009. auto & layer = model.layers[i];
  3010. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3011. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3012. if (gguf_find_tensor(ml.ctx_gguf, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i).c_str()) >= 0) {
  3013. layer.attn_norm_2 = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "weight", i), {n_embd});
  3014. layer.attn_norm_2_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM_2, "bias", i), {n_embd});
  3015. }
  3016. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3017. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3018. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3019. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3020. }
  3021. } break;
  3022. case LLM_ARCH_STARCODER:
  3023. {
  3024. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3025. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3026. // output
  3027. {
  3028. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3029. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3030. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3031. }
  3032. for (int i = 0; i < n_layer; ++i) {
  3033. ggml_context * ctx_layer = ctx_for_layer(i);
  3034. ggml_context * ctx_split = ctx_for_layer_split(i);
  3035. auto & layer = model.layers[i];
  3036. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3037. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3038. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3039. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3040. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3041. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3042. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3043. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3044. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3045. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3046. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3047. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3048. }
  3049. } break;
  3050. case LLM_ARCH_PERSIMMON:
  3051. {
  3052. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3053. {
  3054. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3055. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3056. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3057. }
  3058. for (int i = 0; i < n_layer; ++i) {
  3059. ggml_context * ctx_layer = ctx_for_layer(i);
  3060. ggml_context * ctx_split = ctx_for_layer_split(i);
  3061. auto & layer = model.layers[i];
  3062. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3063. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3064. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3065. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3066. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3067. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3068. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3069. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3070. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3071. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3072. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3073. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3074. layer.attn_q_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {64});
  3075. layer.attn_q_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q_NORM, "bias", i), {64});
  3076. layer.attn_k_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {64});
  3077. layer.attn_k_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K_NORM, "bias", i), {64});
  3078. }
  3079. } break;
  3080. case LLM_ARCH_BLOOM:
  3081. {
  3082. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3083. model.tok_norm = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight"), {n_embd});
  3084. model.tok_norm_b = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD_NORM, "bias"), {n_embd});
  3085. // output
  3086. {
  3087. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3088. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3089. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3090. }
  3091. for (int i = 0; i < n_layer; ++i) {
  3092. ggml_context * ctx_layer = ctx_for_layer(i);
  3093. ggml_context * ctx_split = ctx_for_layer_split(i);
  3094. auto & layer = model.layers[i];
  3095. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3096. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3097. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3098. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3099. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3100. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3101. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3102. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3103. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3104. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3105. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3106. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3107. }
  3108. } break;
  3109. case LLM_ARCH_MPT:
  3110. {
  3111. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3112. // output
  3113. {
  3114. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3115. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3116. }
  3117. for (int i = 0; i < n_layer; ++i) {
  3118. ggml_context * ctx_layer = ctx_for_layer(i);
  3119. ggml_context * ctx_split = ctx_for_layer_split(i);
  3120. auto & layer = model.layers[i];
  3121. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3122. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3123. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3124. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3125. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3126. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3127. // AWQ ScaleActivation layer
  3128. layer.ffn_act = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_ACT, "scales", i), {n_ff}, false);
  3129. }
  3130. } break;
  3131. case LLM_ARCH_STABLELM:
  3132. {
  3133. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3134. // output
  3135. {
  3136. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3137. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3138. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3139. }
  3140. for (int i = 0; i < n_layer; ++i) {
  3141. ggml_context * ctx_layer = ctx_for_layer(i);
  3142. ggml_context * ctx_split = ctx_for_layer_split(i);
  3143. auto & layer = model.layers[i];
  3144. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3145. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3146. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3147. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3148. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3149. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3150. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3151. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3152. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3153. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3154. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3155. }
  3156. } break;
  3157. case LLM_ARCH_QWEN:
  3158. {
  3159. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3160. // output
  3161. {
  3162. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3163. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3164. }
  3165. for (int i = 0; i < n_layer; ++i) {
  3166. ggml_context * ctx_layer = ctx_for_layer(i);
  3167. ggml_context * ctx_split = ctx_for_layer_split(i);
  3168. auto & layer = model.layers[i];
  3169. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3170. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd*3});
  3171. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd*3});
  3172. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3173. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3174. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff/2});
  3175. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff/2, n_embd});
  3176. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff/2});
  3177. }
  3178. } break;
  3179. case LLM_ARCH_QWEN2:
  3180. {
  3181. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3182. // output
  3183. {
  3184. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3185. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3186. }
  3187. for (int i = 0; i < n_layer; ++i) {
  3188. ggml_context * ctx_layer = ctx_for_layer(i);
  3189. ggml_context * ctx_split = ctx_for_layer_split(i);
  3190. auto & layer = model.layers[i];
  3191. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3192. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3193. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3194. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3195. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3196. // optional bias tensors
  3197. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  3198. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  3199. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  3200. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3201. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3202. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3203. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3204. }
  3205. } break;
  3206. case LLM_ARCH_PHI2:
  3207. {
  3208. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3209. // output
  3210. {
  3211. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3212. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3213. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3214. model.output_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT, "bias"), {n_vocab});
  3215. }
  3216. for (int i = 0; i < n_layer; ++i) {
  3217. ggml_context * ctx_layer = ctx_for_layer(i);
  3218. ggml_context * ctx_split = ctx_for_layer_split(i);
  3219. auto & layer = model.layers[i];
  3220. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3221. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3222. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa}, false);
  3223. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa}, false);
  3224. if (layer.wqkv == nullptr) {
  3225. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3226. layer.bq = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_Q, "bias", i), {n_embd});
  3227. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3228. layer.bk = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_K, "bias", i), {n_embd_gqa});
  3229. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3230. layer.bv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_V, "bias", i), {n_embd_gqa});
  3231. }
  3232. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3233. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3234. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3235. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3236. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3237. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3238. }
  3239. } break;
  3240. case LLM_ARCH_PLAMO:
  3241. {
  3242. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3243. // output
  3244. {
  3245. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3246. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3247. }
  3248. for (int i = 0; i < n_layer; ++i) {
  3249. ggml_context * ctx_layer = ctx_for_layer(i);
  3250. ggml_context * ctx_split = ctx_for_layer_split(i);
  3251. auto & layer = model.layers[i];
  3252. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3253. layer.wq = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd});
  3254. layer.wk = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa});
  3255. layer.wv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa});
  3256. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3257. layer.ffn_gate = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff});
  3258. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd});
  3259. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3260. }
  3261. } break;
  3262. case LLM_ARCH_GPT2:
  3263. {
  3264. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3265. model.pos_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_POS_EMBD, "weight"), {n_embd, hparams.n_ctx_train});
  3266. // output
  3267. {
  3268. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3269. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3270. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3271. }
  3272. for (int i = 0; i < n_layer; ++i) {
  3273. ggml_context * ctx_layer = ctx_for_layer(i);
  3274. ggml_context * ctx_split = ctx_for_layer_split(i);
  3275. auto & layer = model.layers[i];
  3276. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3277. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3278. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3279. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3280. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3281. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3282. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3283. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3284. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3285. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3286. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3287. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3288. }
  3289. } break;
  3290. case LLM_ARCH_CODESHELL:
  3291. {
  3292. model.tok_embd = ml.create_tensor(ctx_input, tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab});
  3293. // output
  3294. {
  3295. model.output_norm = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd});
  3296. model.output_norm_b = ml.create_tensor(ctx_output, tn(LLM_TENSOR_OUTPUT_NORM, "bias"), {n_embd});
  3297. model.output = ml.create_tensor(ctx_output_split, tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab});
  3298. }
  3299. for (int i = 0; i < n_layer; ++i) {
  3300. ggml_context * ctx_layer = ctx_for_layer(i);
  3301. ggml_context * ctx_split = ctx_for_layer_split(i);
  3302. auto & layer = model.layers[i];
  3303. layer.attn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd});
  3304. layer.attn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_NORM, "bias", i), {n_embd});
  3305. layer.wqkv = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_QKV, "weight", i), {n_embd, n_embd + 2*n_embd_gqa});
  3306. layer.bqkv = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_QKV, "bias", i), {n_embd + 2*n_embd_gqa});
  3307. layer.wo = ml.create_tensor(ctx_split, tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd});
  3308. layer.bo = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_ATTN_OUT, "bias", i), {n_embd});
  3309. layer.ffn_norm = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd});
  3310. layer.ffn_norm_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_NORM, "bias", i), {n_embd});
  3311. layer.ffn_down = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd});
  3312. layer.ffn_down_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd});
  3313. layer.ffn_up = ml.create_tensor(ctx_split, tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff});
  3314. layer.ffn_up_b = ml.create_tensor(ctx_layer, tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff});
  3315. }
  3316. } break;
  3317. default:
  3318. throw std::runtime_error("unknown architecture");
  3319. }
  3320. }
  3321. ml.done_getting_tensors();
  3322. ml.init_mapping(true, use_mlock ? &model.mlock_mmap : nullptr);
  3323. // create the backend buffers
  3324. std::vector<std::pair<ggml_context *, ggml_backend_buffer_t>> ctx_bufs;
  3325. for (auto & it : ctx_map) {
  3326. ggml_backend_buffer_type_t buft = it.first;
  3327. ggml_context * ctx = it.second;
  3328. ggml_backend_buffer_t buf = nullptr;
  3329. // only the mmap region containing the tensors in the model is mapped to the backend buffer
  3330. // 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
  3331. // this allows using partial offloading when the model size exceeds the metal buffer size, but not the RAM size
  3332. if (ml.use_mmap && buft == llama_default_buffer_type_cpu(true)) {
  3333. size_t first, last;
  3334. ml.get_mapping_range(&first, &last, ctx);
  3335. buf = ggml_backend_cpu_buffer_from_ptr((char *) ml.mapping->addr + first, last - first);
  3336. }
  3337. #ifdef GGML_USE_METAL
  3338. else if (ml.use_mmap && buft == ggml_backend_metal_buffer_type()) {
  3339. const size_t max_size = ggml_get_max_tensor_size(ctx);
  3340. size_t first, last;
  3341. ml.get_mapping_range(&first, &last, ctx);
  3342. buf = ggml_backend_metal_buffer_from_ptr((char *) ml.mapping->addr + first, last - first, max_size);
  3343. }
  3344. #endif
  3345. else {
  3346. buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx, buft);
  3347. if (buf != nullptr && use_mlock && ggml_backend_buffer_is_host(buf)) {
  3348. model.mlock_bufs.emplace_back(new llama_mlock);
  3349. auto & mlock_buf = model.mlock_bufs.back();
  3350. mlock_buf->init (ggml_backend_buffer_get_base(buf));
  3351. mlock_buf->grow_to(ggml_backend_buffer_get_size(buf));
  3352. }
  3353. }
  3354. if (buf == nullptr) {
  3355. throw std::runtime_error("failed to allocate buffer");
  3356. }
  3357. // indicate that this buffer contains weights
  3358. // 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
  3359. ggml_backend_buffer_set_usage(buf, GGML_BACKEND_BUFFER_USAGE_WEIGHTS);
  3360. model.bufs.push_back(buf);
  3361. ctx_bufs.emplace_back(ctx, buf);
  3362. }
  3363. // print memory requirements
  3364. {
  3365. const int n_gpu = std::min(n_gpu_layers, int(hparams.n_layer));
  3366. LLAMA_LOG_INFO("%s: offloading %d repeating layers to GPU\n", __func__, n_gpu);
  3367. if (n_gpu_layers > (int) hparams.n_layer) {
  3368. LLAMA_LOG_INFO("%s: offloading non-repeating layers to GPU\n", __func__);
  3369. }
  3370. const int max_backend_supported_layers = hparams.n_layer + 1;
  3371. const int max_offloadable_layers = hparams.n_layer + 1;
  3372. LLAMA_LOG_INFO("%s: offloaded %d/%d layers to GPU\n", __func__, std::min(n_gpu_layers, max_offloadable_layers), max_backend_supported_layers);
  3373. for (ggml_backend_buffer_t buf : model.bufs) {
  3374. 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);
  3375. }
  3376. }
  3377. // populate tensors_by_name
  3378. for (ggml_context * ctx : model.ctxs) {
  3379. for (auto * cur = ggml_get_first_tensor(ctx); cur != NULL; cur = ggml_get_next_tensor(ctx, cur)) {
  3380. model.tensors_by_name.emplace_back(ggml_get_name(cur), cur);
  3381. }
  3382. }
  3383. // load tensor data
  3384. for (auto & it : ctx_bufs) {
  3385. ggml_context * ctx = it.first;
  3386. ggml_backend_buffer_t buf = it.second;
  3387. if (!ml.load_all_data(ctx, progress_callback, progress_callback_user_data, buf, use_mlock ? &model.mlock_mmap : NULL)) {
  3388. return false;
  3389. }
  3390. }
  3391. model.mapping = std::move(ml.mapping);
  3392. // loading time will be recalculate after the first eval, so
  3393. // we take page faults deferred by mmap() into consideration
  3394. model.t_load_us = ggml_time_us() - model.t_start_us;
  3395. return true;
  3396. }
  3397. // Returns 0 on success, -1 on error, and -2 on cancellation via llama_progress_callback
  3398. static int llama_model_load(const std::string & fname, llama_model & model, const llama_model_params & params) {
  3399. try {
  3400. llama_model_loader ml(fname, params.use_mmap, params.kv_overrides);
  3401. model.hparams.vocab_only = params.vocab_only;
  3402. llm_load_arch (ml, model);
  3403. llm_load_hparams(ml, model);
  3404. llm_load_vocab (ml, model);
  3405. llm_load_print_meta(ml, model);
  3406. if (model.hparams.n_vocab != model.vocab.id_to_token.size()) {
  3407. throw std::runtime_error("vocab size mismatch");
  3408. }
  3409. if (params.vocab_only) {
  3410. LLAMA_LOG_INFO("%s: vocab only - skipping tensors\n", __func__);
  3411. return 0;
  3412. }
  3413. if (!llm_load_tensors(
  3414. ml, model, params.n_gpu_layers, params.split_mode, params.main_gpu, params.tensor_split, params.use_mlock,
  3415. params.progress_callback, params.progress_callback_user_data
  3416. )) {
  3417. return -2;
  3418. }
  3419. } catch (const std::exception & err) {
  3420. LLAMA_LOG_ERROR("%s: error loading model: %s\n", __func__, err.what());
  3421. return -1;
  3422. }
  3423. return 0;
  3424. }
  3425. //
  3426. // llm_build
  3427. //
  3428. using llm_build_cb = std::function<void(struct ggml_tensor * cur, const char * name, int nl)>;
  3429. enum llm_rope_type {
  3430. LLM_ROPE,
  3431. LLM_ROPE_NEOX,
  3432. LLM_ROPE_GLM,
  3433. };
  3434. enum llm_ffn_op_type {
  3435. LLM_FFN_SILU,
  3436. LLM_FFN_GELU,
  3437. LLM_FFN_RELU,
  3438. LLM_FFN_RELU_SQR,
  3439. };
  3440. enum llm_ffn_gate_type {
  3441. LLM_FFN_SEQ,
  3442. LLM_FFN_PAR, // ffn_gate is parallel to ffn_up
  3443. };
  3444. enum llm_norm_type {
  3445. LLM_NORM,
  3446. LLM_NORM_RMS,
  3447. };
  3448. static struct ggml_tensor * llm_build_inp_embd(
  3449. struct ggml_context * ctx,
  3450. const llama_hparams & hparams,
  3451. const llama_batch & batch,
  3452. struct ggml_tensor * tok_embd,
  3453. const llm_build_cb & cb) {
  3454. const int64_t n_embd = hparams.n_embd;
  3455. struct ggml_tensor * inpL;
  3456. if (batch.token) {
  3457. struct ggml_tensor * inp_tokens = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, batch.n_tokens);
  3458. cb(inp_tokens, "inp_tokens", -1);
  3459. inpL = ggml_get_rows(ctx, tok_embd, inp_tokens);
  3460. } else {
  3461. #ifdef GGML_USE_MPI
  3462. GGML_ASSERT(false && "not implemented");
  3463. #endif
  3464. inpL = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, batch.n_tokens);
  3465. }
  3466. return inpL;
  3467. }
  3468. // Persimmon: n_rot = n_embd_head_k/2
  3469. // Other: n_rot = n_embd_head_k
  3470. static void llm_build_k_shift(
  3471. struct ggml_context * ctx,
  3472. const llama_hparams & hparams,
  3473. const llama_cparams & cparams,
  3474. const llama_kv_cache & kv,
  3475. struct ggml_cgraph * graph,
  3476. llm_rope_type type,
  3477. int64_t n_ctx,
  3478. float freq_base,
  3479. float freq_scale,
  3480. const llm_build_cb & cb) {
  3481. const int64_t n_layer = hparams.n_layer;
  3482. const int64_t n_head_kv = hparams.n_head_kv;
  3483. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  3484. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3485. const int32_t n_rot = hparams.n_rot;
  3486. const int32_t n_orig_ctx = cparams.n_yarn_orig_ctx;
  3487. const float ext_factor = cparams.yarn_ext_factor;
  3488. const float attn_factor = cparams.yarn_attn_factor;
  3489. const float beta_fast = cparams.yarn_beta_fast;
  3490. const float beta_slow = cparams.yarn_beta_slow;
  3491. struct ggml_tensor * K_shift = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, n_ctx);
  3492. cb(K_shift, "K_shift", -1);
  3493. int rope_type = 0;
  3494. switch (type) {
  3495. case LLM_ROPE: rope_type = 0; break;
  3496. case LLM_ROPE_NEOX: rope_type = 2; break;
  3497. case LLM_ROPE_GLM: rope_type = 4; break;
  3498. }
  3499. for (int il = 0; il < n_layer; ++il) {
  3500. struct ggml_tensor * tmp =
  3501. // we rotate only the first n_rot dimensions
  3502. ggml_rope_custom_inplace(ctx,
  3503. ggml_view_3d(ctx, kv.k_l[il],
  3504. n_embd_head_k, n_head_kv, n_ctx,
  3505. ggml_row_size(kv.k_l[il]->type, n_embd_head_k),
  3506. ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa),
  3507. 0),
  3508. K_shift, n_rot, rope_type, 0, n_orig_ctx, freq_base, freq_scale,
  3509. ext_factor, attn_factor, beta_fast, beta_slow);
  3510. cb(tmp, "K_shifted", il);
  3511. ggml_build_forward_expand(graph, tmp);
  3512. }
  3513. }
  3514. static void llm_build_kv_store(
  3515. struct ggml_context * ctx,
  3516. const llama_hparams & hparams,
  3517. const llama_kv_cache & kv,
  3518. struct ggml_cgraph * graph,
  3519. struct ggml_tensor * k_cur,
  3520. struct ggml_tensor * v_cur,
  3521. int64_t n_ctx,
  3522. int32_t n_tokens,
  3523. int32_t kv_head,
  3524. const llm_build_cb & cb,
  3525. int64_t il) {
  3526. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3527. const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa();
  3528. // compute the transposed [n_tokens, n_embd] V matrix
  3529. struct ggml_tensor * v_cur_t = ggml_transpose(ctx, ggml_reshape_2d(ctx, v_cur, n_embd_v_gqa, n_tokens));
  3530. //struct ggml_tensor * v_cur_t = ggml_transpose(ctx, v_cur); // TODO: reshape above is likely not needed
  3531. cb(v_cur_t, "v_cur_t", il);
  3532. struct ggml_tensor * k_cache_view = ggml_view_1d(ctx, kv.k_l[il], n_tokens*n_embd_k_gqa,
  3533. (ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa))*kv_head);
  3534. cb(k_cache_view, "k_cache_view", il);
  3535. struct ggml_tensor * v_cache_view = ggml_view_2d(ctx, kv.v_l[il], n_tokens, n_embd_v_gqa,
  3536. ( n_ctx)*ggml_element_size(kv.v_l[il]),
  3537. (kv_head)*ggml_element_size(kv.v_l[il]));
  3538. cb(v_cache_view, "v_cache_view", il);
  3539. // important: storing RoPE-ed version of K in the KV cache!
  3540. ggml_build_forward_expand(graph, ggml_cpy(ctx, k_cur, k_cache_view));
  3541. ggml_build_forward_expand(graph, ggml_cpy(ctx, v_cur_t, v_cache_view));
  3542. }
  3543. static struct ggml_tensor * llm_build_norm(
  3544. struct ggml_context * ctx,
  3545. struct ggml_tensor * cur,
  3546. const llama_hparams & hparams,
  3547. struct ggml_tensor * mw,
  3548. struct ggml_tensor * mb,
  3549. llm_norm_type type,
  3550. const llm_build_cb & cb,
  3551. int il) {
  3552. switch (type) {
  3553. case LLM_NORM: cur = ggml_norm (ctx, cur, hparams.f_norm_eps); break;
  3554. case LLM_NORM_RMS: cur = ggml_rms_norm(ctx, cur, hparams.f_norm_rms_eps); break;
  3555. }
  3556. if (mw || mb) {
  3557. cb(cur, "norm", il);
  3558. }
  3559. if (mw) {
  3560. cur = ggml_mul(ctx, cur, mw);
  3561. if (mb) {
  3562. cb(cur, "norm_w", il);
  3563. }
  3564. }
  3565. if (mb) {
  3566. cur = ggml_add(ctx, cur, mb);
  3567. }
  3568. return cur;
  3569. }
  3570. static struct ggml_tensor * llm_build_ffn(
  3571. struct ggml_context * ctx,
  3572. struct ggml_tensor * cur,
  3573. struct ggml_tensor * up,
  3574. struct ggml_tensor * up_b,
  3575. struct ggml_tensor * gate,
  3576. struct ggml_tensor * gate_b,
  3577. struct ggml_tensor * down,
  3578. struct ggml_tensor * down_b,
  3579. struct ggml_tensor * act_scales,
  3580. llm_ffn_op_type type_op,
  3581. llm_ffn_gate_type type_gate,
  3582. const llm_build_cb & cb,
  3583. int il) {
  3584. struct ggml_tensor * tmp = ggml_mul_mat(ctx, up, cur);
  3585. cb(tmp, "ffn_up", il);
  3586. if (up_b) {
  3587. tmp = ggml_add(ctx, tmp, up_b);
  3588. cb(tmp, "ffn_up_b", il);
  3589. }
  3590. if (gate) {
  3591. switch (type_gate) {
  3592. case LLM_FFN_SEQ:
  3593. {
  3594. cur = ggml_mul_mat(ctx, gate, tmp);
  3595. cb(cur, "ffn_gate", il);
  3596. } break;
  3597. case LLM_FFN_PAR:
  3598. {
  3599. cur = ggml_mul_mat(ctx, gate, cur);
  3600. cb(cur, "ffn_gate", il);
  3601. } break;
  3602. }
  3603. if (gate_b) {
  3604. cur = ggml_add(ctx, cur, gate_b);
  3605. cb(cur, "ffn_gate_b", il);
  3606. }
  3607. } else {
  3608. cur = tmp;
  3609. }
  3610. switch (type_op) {
  3611. case LLM_FFN_SILU:
  3612. {
  3613. cur = ggml_silu(ctx, cur);
  3614. cb(cur, "ffn_silu", il);
  3615. } break;
  3616. case LLM_FFN_GELU:
  3617. {
  3618. cur = ggml_gelu(ctx, cur);
  3619. cb(cur, "ffn_gelu", il);
  3620. if (act_scales != NULL) {
  3621. cur = ggml_div(ctx, cur, act_scales);
  3622. cb(cur, "ffn_act", il);
  3623. }
  3624. } break;
  3625. case LLM_FFN_RELU:
  3626. {
  3627. cur = ggml_relu(ctx, cur);
  3628. cb(cur, "ffn_relu", il);
  3629. } break;
  3630. case LLM_FFN_RELU_SQR:
  3631. {
  3632. cur = ggml_relu(ctx, cur);
  3633. cb(cur, "ffn_relu", il);
  3634. cur = ggml_sqr(ctx, cur);
  3635. cb(cur, "ffn_sqr(relu)", il);
  3636. } break;
  3637. }
  3638. if (type_gate == LLM_FFN_PAR) {
  3639. cur = ggml_mul(ctx, cur, tmp);
  3640. cb(cur, "ffn_gate_par", il);
  3641. }
  3642. cur = ggml_mul_mat(ctx, down, cur);
  3643. if (down_b) {
  3644. cb(cur, "ffn_down", il);
  3645. }
  3646. if (down_b) {
  3647. cur = ggml_add(ctx, cur, down_b);
  3648. }
  3649. return cur;
  3650. }
  3651. // if max_alibi_bias > 0 then apply ALiBi
  3652. static struct ggml_tensor * llm_build_kqv(
  3653. struct ggml_context * ctx,
  3654. const llama_model & model,
  3655. const llama_hparams & hparams,
  3656. const llama_kv_cache & kv,
  3657. struct ggml_tensor * wo,
  3658. struct ggml_tensor * wo_b,
  3659. struct ggml_tensor * q_cur,
  3660. struct ggml_tensor * kq_mask,
  3661. int64_t n_ctx,
  3662. int32_t n_tokens,
  3663. int32_t n_kv,
  3664. float max_alibi_bias,
  3665. float kq_scale,
  3666. const llm_build_cb & cb,
  3667. int il) {
  3668. const int64_t n_head = hparams.n_head;
  3669. const int64_t n_head_kv = hparams.n_head_kv;
  3670. const int64_t n_embd_head_k = hparams.n_embd_head_k;
  3671. const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa();
  3672. const int64_t n_embd_head_v = hparams.n_embd_head_v;
  3673. struct ggml_tensor * q = ggml_permute(ctx, q_cur, 0, 2, 1, 3);
  3674. cb(q, "q", il);
  3675. struct ggml_tensor * k =
  3676. ggml_view_3d(ctx, kv.k_l[il],
  3677. n_embd_head_k, n_kv, n_head_kv,
  3678. ggml_row_size(kv.k_l[il]->type, n_embd_k_gqa),
  3679. ggml_row_size(kv.k_l[il]->type, n_embd_head_k),
  3680. 0);
  3681. cb(k, "k", il);
  3682. struct ggml_tensor * kq = ggml_mul_mat(ctx, k, q);
  3683. cb(kq, "kq", il);
  3684. if (model.arch == LLM_ARCH_PHI2) {
  3685. // for this arch, we need to perform the KQ multiplication with F32 precision, otherwise we get NaNs
  3686. // ref: https://github.com/ggerganov/llama.cpp/pull/4490#issuecomment-1859055847
  3687. ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
  3688. }
  3689. if (max_alibi_bias > 0.0f) {
  3690. // temporary branch until we figure out how to handle ggml_alibi through ggml_add
  3691. kq = ggml_scale(ctx, kq, kq_scale);
  3692. cb(kq, "kq_scaled", il);
  3693. if (max_alibi_bias > 0.0f) {
  3694. // TODO: n_head or n_head_kv
  3695. // TODO: K-shift is likely not working
  3696. // TODO: change to ggml_add
  3697. kq = ggml_alibi(ctx, kq, /*n_past*/ 0, n_head, max_alibi_bias);
  3698. cb(kq, "kq_scaled_alibi", il);
  3699. }
  3700. kq = ggml_add(ctx, kq, kq_mask);
  3701. cb(kq, "kq_masked", il);
  3702. kq = ggml_soft_max(ctx, kq);
  3703. cb(kq, "kq_soft_max", il);
  3704. } else {
  3705. kq = ggml_soft_max_ext(ctx, kq, kq_mask, kq_scale);
  3706. cb(kq, "kq_soft_max_ext", il);
  3707. }
  3708. // split cached v into n_head heads
  3709. struct ggml_tensor * v =
  3710. ggml_view_3d(ctx, kv.v_l[il],
  3711. n_kv, n_embd_head_v, n_head_kv,
  3712. ggml_element_size(kv.v_l[il])*n_ctx,
  3713. ggml_element_size(kv.v_l[il])*n_ctx*n_embd_head_v,
  3714. 0);
  3715. cb(v, "v", il);
  3716. struct ggml_tensor * kqv = ggml_mul_mat(ctx, v, kq);
  3717. cb(kqv, "kqv", il);
  3718. struct ggml_tensor * kqv_merged = ggml_permute(ctx, kqv, 0, 2, 1, 3);
  3719. cb(kqv_merged, "kqv_merged", il);
  3720. struct ggml_tensor * cur = ggml_cont_2d(ctx, kqv_merged, n_embd_head_k*n_head, n_tokens);
  3721. cb(cur, "kqv_merged_cont", il);
  3722. cur = ggml_mul_mat(ctx, wo, cur);
  3723. if (wo_b) {
  3724. cb(cur, "kqv_wo", il);
  3725. }
  3726. if (wo_b) {
  3727. cur = ggml_add(ctx, cur, wo_b);
  3728. }
  3729. return cur;
  3730. }
  3731. struct llm_build_context {
  3732. const llama_model & model;
  3733. const llama_hparams & hparams;
  3734. const llama_cparams & cparams;
  3735. const llama_batch & batch;
  3736. const llama_kv_cache & kv_self;
  3737. const int64_t n_embd;
  3738. const int64_t n_layer;
  3739. const int64_t n_ctx; // user-specified context size (can be different from n_ctx_train)
  3740. const int64_t n_head;
  3741. const int64_t n_head_kv;
  3742. const int64_t n_embd_head_k;
  3743. const int64_t n_embd_k_gqa;
  3744. const int64_t n_embd_head_v;
  3745. const int64_t n_embd_v_gqa;
  3746. const int64_t n_expert;
  3747. const int64_t n_expert_used;
  3748. const float freq_base;
  3749. const float freq_scale;
  3750. const float ext_factor;
  3751. const float attn_factor;
  3752. const float beta_fast;
  3753. const float beta_slow;
  3754. const float norm_eps;
  3755. const float norm_rms_eps;
  3756. const int32_t n_tokens;
  3757. const int32_t n_kv; // size of KV cache to consider (n_kv <= n_ctx)
  3758. const int32_t kv_head; // index of where we store new KV data in the cache
  3759. const int32_t n_orig_ctx;
  3760. const bool do_rope_shift;
  3761. const llm_build_cb & cb;
  3762. std::vector<uint8_t> & buf_compute_meta;
  3763. struct ggml_context * ctx0 = nullptr;
  3764. // TODO: consider making the entire interface noexcept
  3765. llm_build_context(
  3766. llama_context & lctx,
  3767. const llama_batch & batch,
  3768. const llm_build_cb & cb,
  3769. bool worst_case) :
  3770. model (lctx.model),
  3771. hparams (model.hparams),
  3772. cparams (lctx.cparams),
  3773. batch (batch),
  3774. kv_self (lctx.kv_self),
  3775. n_embd (hparams.n_embd),
  3776. n_layer (hparams.n_layer),
  3777. n_ctx (cparams.n_ctx),
  3778. n_head (hparams.n_head),
  3779. n_head_kv (hparams.n_head_kv),
  3780. n_embd_head_k (hparams.n_embd_head_k),
  3781. n_embd_k_gqa (hparams.n_embd_k_gqa()),
  3782. n_embd_head_v (hparams.n_embd_head_v),
  3783. n_embd_v_gqa (hparams.n_embd_v_gqa()),
  3784. n_expert (hparams.n_expert),
  3785. n_expert_used (hparams.n_expert_used),
  3786. freq_base (cparams.rope_freq_base),
  3787. freq_scale (cparams.rope_freq_scale),
  3788. ext_factor (cparams.yarn_ext_factor),
  3789. attn_factor (cparams.yarn_attn_factor),
  3790. beta_fast (cparams.yarn_beta_fast),
  3791. beta_slow (cparams.yarn_beta_slow),
  3792. norm_eps (hparams.f_norm_eps),
  3793. norm_rms_eps (hparams.f_norm_rms_eps),
  3794. n_tokens (batch.n_tokens),
  3795. n_kv (worst_case ? n_ctx : kv_self.n),
  3796. kv_head (worst_case ? n_ctx - n_tokens : kv_self.head),
  3797. n_orig_ctx (cparams.n_yarn_orig_ctx),
  3798. do_rope_shift (worst_case || kv_self.has_shift),
  3799. cb (cb),
  3800. buf_compute_meta (lctx.buf_compute_meta) {
  3801. // all initializations should be done in init()
  3802. }
  3803. void init() {
  3804. struct ggml_init_params params = {
  3805. /*.mem_size =*/ buf_compute_meta.size(),
  3806. /*.mem_buffer =*/ buf_compute_meta.data(),
  3807. /*.no_alloc =*/ true,
  3808. };
  3809. ctx0 = ggml_init(params);
  3810. }
  3811. void free() {
  3812. if (ctx0) {
  3813. ggml_free(ctx0);
  3814. ctx0 = nullptr;
  3815. }
  3816. }
  3817. struct ggml_cgraph * build_llama() {
  3818. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  3819. const int64_t n_embd_head = hparams.n_embd_head_v;
  3820. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  3821. GGML_ASSERT(n_embd_head == hparams.n_rot);
  3822. struct ggml_tensor * cur;
  3823. struct ggml_tensor * inpL;
  3824. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  3825. cb(inpL, "inp_embd", -1);
  3826. // inp_pos - contains the positions
  3827. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  3828. cb(inp_pos, "inp_pos", -1);
  3829. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  3830. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  3831. cb(KQ_mask, "KQ_mask", -1);
  3832. // shift the entire K-cache if needed
  3833. if (do_rope_shift) {
  3834. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  3835. }
  3836. for (int il = 0; il < n_layer; ++il) {
  3837. struct ggml_tensor * inpSA = inpL;
  3838. // norm
  3839. cur = llm_build_norm(ctx0, inpL, hparams,
  3840. model.layers[il].attn_norm, NULL,
  3841. LLM_NORM_RMS, cb, il);
  3842. cb(cur, "attn_norm", il);
  3843. // self-attention
  3844. {
  3845. // compute Q and K and RoPE them
  3846. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  3847. cb(Qcur, "Qcur", il);
  3848. if (model.layers[il].bq) {
  3849. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  3850. cb(Qcur, "Qcur", il);
  3851. }
  3852. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  3853. cb(Kcur, "Kcur", il);
  3854. if (model.layers[il].bk) {
  3855. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  3856. cb(Kcur, "Kcur", il);
  3857. }
  3858. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  3859. cb(Vcur, "Vcur", il);
  3860. if (model.layers[il].bv) {
  3861. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  3862. cb(Vcur, "Vcur", il);
  3863. }
  3864. // these nodes are added to the graph together so that they are not reordered
  3865. // by doing so, the number of splits in the graph is reduced
  3866. ggml_build_forward_expand(gf, Qcur);
  3867. ggml_build_forward_expand(gf, Kcur);
  3868. ggml_build_forward_expand(gf, Vcur);
  3869. Qcur = ggml_rope_custom(
  3870. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  3871. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  3872. ext_factor, attn_factor, beta_fast, beta_slow
  3873. );
  3874. cb(Qcur, "Qcur", il);
  3875. Kcur = ggml_rope_custom(
  3876. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  3877. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  3878. ext_factor, attn_factor, beta_fast, beta_slow
  3879. );
  3880. cb(Kcur, "Kcur", il);
  3881. llm_build_kv_store(ctx0, hparams, kv_self, gf, Kcur, Vcur, n_ctx, n_tokens, kv_head, cb, il);
  3882. cur = llm_build_kqv(ctx0, model, hparams, kv_self,
  3883. model.layers[il].wo, model.layers[il].bo,
  3884. Qcur, KQ_mask, n_ctx, n_tokens, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  3885. cb(cur, "kqv_out", il);
  3886. }
  3887. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  3888. cb(ffn_inp, "ffn_inp", il);
  3889. // feed-forward network
  3890. if (model.layers[il].ffn_gate_inp == nullptr) {
  3891. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  3892. model.layers[il].ffn_norm, NULL,
  3893. LLM_NORM_RMS, cb, il);
  3894. cb(cur, "ffn_norm", il);
  3895. cur = llm_build_ffn(ctx0, cur,
  3896. model.layers[il].ffn_up, NULL,
  3897. model.layers[il].ffn_gate, NULL,
  3898. model.layers[il].ffn_down, NULL,
  3899. NULL,
  3900. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  3901. cb(cur, "ffn_out", il);
  3902. } else {
  3903. // MoE branch
  3904. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  3905. model.layers[il].ffn_norm, NULL,
  3906. LLM_NORM_RMS, cb, il);
  3907. cb(cur, "ffn_norm", il);
  3908. ggml_tensor * logits = ggml_mul_mat(ctx0, model.layers[il].ffn_gate_inp, cur); // [n_tokens, num_experts]
  3909. cb(logits, "ffn_moe_logits", il);
  3910. ggml_tensor * probs = ggml_soft_max(ctx0, logits); // [n_tokens, num_experts]
  3911. cb(probs, "ffn_moe_probs", il);
  3912. // select experts
  3913. ggml_tensor * selected_experts = ggml_top_k(ctx0, probs, n_expert_used); // [n_tokens, num_experts_per_tok]
  3914. cb(selected_experts->src[0], "ffn_moe_argsort", il);
  3915. ggml_tensor * weights = ggml_get_rows(ctx0,
  3916. ggml_reshape_3d(ctx0, probs, 1, n_expert, n_tokens), selected_experts);
  3917. cb(weights, "ffn_moe_weights", il);
  3918. weights = ggml_reshape_2d(ctx0, weights, n_expert_used, n_tokens); // [n_tokens, num_experts_per_tok]
  3919. ggml_tensor * weights_sum = ggml_sum_rows(ctx0, weights);
  3920. cb(weights_sum, "ffn_moe_weights_sum", il);
  3921. weights = ggml_div(ctx0, weights, weights_sum); // [n_tokens, num_experts_per_tok]
  3922. cb(weights, "ffn_moe_weights_norm", il);
  3923. // compute expert outputs
  3924. ggml_tensor * moe_out = nullptr;
  3925. for (int i = 0; i < n_expert_used; ++i) {
  3926. ggml_tensor * cur_expert;
  3927. ggml_tensor * cur_up = ggml_mul_mat_id(ctx0, model.layers[il].ffn_up_exp, n_expert, selected_experts, i, cur);
  3928. cb(cur_up, "ffn_moe_up", il);
  3929. ggml_tensor * cur_gate = ggml_mul_mat_id(ctx0, model.layers[il].ffn_gate_exp, n_expert, selected_experts, i, cur);
  3930. cb(cur_gate, "ffn_moe_gate", il);
  3931. cur_gate = ggml_silu(ctx0, cur_gate);
  3932. cb(cur_gate, "ffn_moe_silu", il);
  3933. cur_expert = ggml_mul(ctx0, cur_up, cur_gate); // [n_tokens, n_embd]
  3934. cb(cur_expert, "ffn_moe_gate_par", il);
  3935. cur_expert = ggml_mul_mat_id(ctx0, model.layers[il].ffn_down_exp, n_expert, selected_experts, i, cur_expert); // [n_tokens, n_embd]
  3936. cb(cur_expert, "ffn_moe_down", il);
  3937. cur_expert = ggml_mul(ctx0, cur_expert,
  3938. ggml_view_2d(ctx0, weights, 1, n_tokens, weights->nb[1], i*weights->nb[0]));
  3939. cb(cur_expert, "ffn_moe_weighted", il);
  3940. if (i == 0) {
  3941. moe_out = cur_expert;
  3942. } else {
  3943. moe_out = ggml_add(ctx0, moe_out, cur_expert);
  3944. cb(moe_out, "ffn_moe_out", il);
  3945. }
  3946. }
  3947. cur = moe_out;
  3948. }
  3949. cur = ggml_add(ctx0, cur, ffn_inp);
  3950. cb(cur, "l_out", il);
  3951. // input for next layer
  3952. inpL = cur;
  3953. }
  3954. cur = inpL;
  3955. cur = llm_build_norm(ctx0, cur, hparams,
  3956. model.output_norm, NULL,
  3957. LLM_NORM_RMS, cb, -1);
  3958. cb(cur, "result_norm", -1);
  3959. // lm_head
  3960. cur = ggml_mul_mat(ctx0, model.output, cur);
  3961. cb(cur, "result_output", -1);
  3962. ggml_build_forward_expand(gf, cur);
  3963. return gf;
  3964. }
  3965. struct ggml_cgraph * build_baichuan() {
  3966. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  3967. const int64_t n_embd_head = hparams.n_embd_head_v;
  3968. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  3969. GGML_ASSERT(n_embd_head == hparams.n_rot);
  3970. struct ggml_tensor * cur;
  3971. struct ggml_tensor * inpL;
  3972. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  3973. cb(inpL, "inp_embd", -1);
  3974. // inp_pos - contains the positions
  3975. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  3976. cb(inp_pos, "inp_pos", -1);
  3977. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  3978. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  3979. cb(KQ_mask, "KQ_mask", -1);
  3980. // shift the entire K-cache if needed
  3981. if (do_rope_shift) {
  3982. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  3983. }
  3984. for (int il = 0; il < n_layer; ++il) {
  3985. struct ggml_tensor * inpSA = inpL;
  3986. cur = llm_build_norm(ctx0, inpL, hparams,
  3987. model.layers[il].attn_norm, NULL,
  3988. LLM_NORM_RMS, cb, il);
  3989. cb(cur, "attn_norm", il);
  3990. // self-attention
  3991. {
  3992. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  3993. cb(Qcur, "Qcur", il);
  3994. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  3995. cb(Kcur, "Kcur", il);
  3996. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  3997. cb(Vcur, "Vcur", il);
  3998. switch (model.type) {
  3999. case MODEL_7B:
  4000. Qcur = ggml_rope_custom(
  4001. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  4002. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  4003. ext_factor, attn_factor, beta_fast, beta_slow
  4004. );
  4005. Kcur = ggml_rope_custom(
  4006. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  4007. hparams.n_rot, 0, 0, n_orig_ctx, freq_base, freq_scale,
  4008. ext_factor, attn_factor, beta_fast, beta_slow
  4009. );
  4010. break;
  4011. case MODEL_13B:
  4012. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd/n_head, n_head, n_tokens);
  4013. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd/n_head, n_head, n_tokens);
  4014. break;
  4015. default:
  4016. GGML_ASSERT(false);
  4017. }
  4018. cb(Qcur, "Qcur", il);
  4019. cb(Kcur, "Kcur", il);
  4020. llm_build_kv_store(ctx0, hparams, kv_self, gf, Kcur, Vcur, n_ctx, n_tokens, kv_head, cb, il);
  4021. // apply ALiBi for 13B model
  4022. const float max_alibi_bias = model.type == MODEL_13B ? 8.0f : -1.0f;
  4023. cur = llm_build_kqv(ctx0, model, hparams, kv_self,
  4024. model.layers[il].wo, NULL,
  4025. Qcur, KQ_mask, n_ctx, n_tokens, n_kv, max_alibi_bias, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4026. cb(cur, "kqv_out", il);
  4027. }
  4028. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4029. cb(ffn_inp, "ffn_inp", il);
  4030. // feed-forward network
  4031. {
  4032. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4033. model.layers[il].ffn_norm, NULL,
  4034. LLM_NORM_RMS, cb, il);
  4035. cb(cur, "ffn_norm", il);
  4036. cur = llm_build_ffn(ctx0, cur,
  4037. model.layers[il].ffn_up, NULL,
  4038. model.layers[il].ffn_gate, NULL,
  4039. model.layers[il].ffn_down, NULL,
  4040. NULL,
  4041. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4042. cb(cur, "ffn_out", il);
  4043. }
  4044. cur = ggml_add(ctx0, cur, ffn_inp);
  4045. cb(cur, "l_out", il);
  4046. // input for next layer
  4047. inpL = cur;
  4048. }
  4049. cur = inpL;
  4050. cur = llm_build_norm(ctx0, cur, hparams,
  4051. model.output_norm, NULL,
  4052. LLM_NORM_RMS, cb, -1);
  4053. cb(cur, "result_norm", -1);
  4054. // lm_head
  4055. cur = ggml_mul_mat(ctx0, model.output, cur);
  4056. cb(cur, "result_output", -1);
  4057. ggml_build_forward_expand(gf, cur);
  4058. return gf;
  4059. }
  4060. struct ggml_cgraph * build_falcon() {
  4061. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4062. const int64_t n_embd_head = hparams.n_embd_head_v;
  4063. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4064. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4065. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4066. struct ggml_tensor * cur;
  4067. struct ggml_tensor * inpL;
  4068. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  4069. cb(inpL, "inp_embd", -1);
  4070. // inp_pos - contains the positions
  4071. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  4072. cb(inp_pos, "inp_pos", -1);
  4073. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4074. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  4075. cb(KQ_mask, "KQ_mask", -1);
  4076. // shift the entire K-cache if needed
  4077. if (do_rope_shift) {
  4078. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  4079. }
  4080. for (int il = 0; il < n_layer; ++il) {
  4081. struct ggml_tensor * attn_norm;
  4082. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  4083. model.layers[il].attn_norm,
  4084. model.layers[il].attn_norm_b,
  4085. LLM_NORM, cb, il);
  4086. cb(attn_norm, "attn_norm", il);
  4087. // self-attention
  4088. {
  4089. if (model.layers[il].attn_norm_2) {
  4090. // Falcon-40B
  4091. cur = llm_build_norm(ctx0, inpL, hparams,
  4092. model.layers[il].attn_norm_2,
  4093. model.layers[il].attn_norm_2_b,
  4094. LLM_NORM, cb, il);
  4095. cb(cur, "attn_norm_2", il);
  4096. } else {
  4097. cur = attn_norm;
  4098. }
  4099. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4100. cb(cur, "wqkv", il);
  4101. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4102. 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)));
  4103. 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)));
  4104. cb(Qcur, "Qcur", il);
  4105. cb(Kcur, "Kcur", il);
  4106. cb(Vcur, "Vcur", il);
  4107. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4108. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  4109. // using mode = 2 for neox mode
  4110. Qcur = ggml_rope_custom(
  4111. ctx0, Qcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4112. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4113. );
  4114. cb(Qcur, "Qcur", il);
  4115. Kcur = ggml_rope_custom(
  4116. ctx0, Kcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4117. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4118. );
  4119. cb(Kcur, "Kcur", il);
  4120. llm_build_kv_store(ctx0, hparams, kv_self, gf, Kcur, Vcur, n_ctx, n_tokens, kv_head, cb, il);
  4121. cur = llm_build_kqv(ctx0, model, hparams, kv_self,
  4122. model.layers[il].wo, NULL,
  4123. Qcur, KQ_mask, n_ctx, n_tokens, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4124. cb(cur, "kqv_out", il);
  4125. }
  4126. struct ggml_tensor * ffn_inp = cur;
  4127. // feed forward
  4128. {
  4129. cur = llm_build_ffn(ctx0, attn_norm, // !! use the attn norm, not the result
  4130. model.layers[il].ffn_up, NULL,
  4131. NULL, NULL,
  4132. model.layers[il].ffn_down, NULL,
  4133. NULL,
  4134. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4135. cb(cur, "ffn_out", il);
  4136. }
  4137. cur = ggml_add(ctx0, cur, ffn_inp);
  4138. cb(cur, "l_out", il);
  4139. cur = ggml_add(ctx0, cur, inpL);
  4140. cb(cur, "l_out", il);
  4141. // input for next layer
  4142. inpL = cur;
  4143. }
  4144. cur = inpL;
  4145. // norm
  4146. cur = llm_build_norm(ctx0, cur, hparams,
  4147. model.output_norm,
  4148. model.output_norm_b,
  4149. LLM_NORM, cb, -1);
  4150. cb(cur, "result_norm", -1);
  4151. cur = ggml_mul_mat(ctx0, model.output, cur);
  4152. cb(cur, "result_output", -1);
  4153. ggml_build_forward_expand(gf, cur);
  4154. return gf;
  4155. }
  4156. struct ggml_cgraph * build_starcoder() {
  4157. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4158. const int64_t n_embd_head = hparams.n_embd_head_v;
  4159. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4160. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4161. struct ggml_tensor * cur;
  4162. struct ggml_tensor * pos;
  4163. struct ggml_tensor * inpL;
  4164. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  4165. cb(inpL, "inp_embd", -1);
  4166. // inp_pos - contains the positions
  4167. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  4168. cb(inp_pos, "inp_pos", -1);
  4169. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4170. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  4171. cb(KQ_mask, "KQ_mask", -1);
  4172. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  4173. cb(pos, "pos_embd", -1);
  4174. inpL = ggml_add(ctx0, inpL, pos);
  4175. cb(inpL, "inpL", -1);
  4176. for (int il = 0; il < n_layer; ++il) {
  4177. cur = llm_build_norm(ctx0, inpL, hparams,
  4178. model.layers[il].attn_norm,
  4179. model.layers[il].attn_norm_b,
  4180. LLM_NORM, cb, il);
  4181. cb(cur, "attn_norm", il);
  4182. // self-attention
  4183. {
  4184. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4185. cb(cur, "wqkv", il);
  4186. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4187. cb(cur, "bqkv", il);
  4188. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4189. 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)));
  4190. 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)));
  4191. cb(Qcur, "Qcur", il);
  4192. cb(Kcur, "Kcur", il);
  4193. cb(Vcur, "Vcur", il);
  4194. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4195. llm_build_kv_store(ctx0, hparams, kv_self, gf, Kcur, Vcur, n_ctx, n_tokens, kv_head, cb, il);
  4196. cur = llm_build_kqv(ctx0, model, hparams, kv_self,
  4197. model.layers[il].wo, model.layers[il].bo,
  4198. Qcur, KQ_mask, n_ctx, n_tokens, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4199. cb(cur, "kqv_out", il);
  4200. }
  4201. // add the input
  4202. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  4203. cb(ffn_inp, "ffn_inp", il);
  4204. // FF
  4205. {
  4206. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4207. model.layers[il].ffn_norm,
  4208. model.layers[il].ffn_norm_b,
  4209. LLM_NORM, cb, il);
  4210. cb(cur, "ffn_norm", il);
  4211. cur = llm_build_ffn(ctx0, cur,
  4212. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  4213. NULL, NULL,
  4214. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  4215. NULL,
  4216. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4217. cb(cur, "ffn_out", il);
  4218. }
  4219. inpL = ggml_add(ctx0, cur, ffn_inp);
  4220. cb(inpL, "l_out", il);
  4221. }
  4222. cur = llm_build_norm(ctx0, inpL, hparams,
  4223. model.output_norm,
  4224. model.output_norm_b,
  4225. LLM_NORM, cb, -1);
  4226. cb(cur, "result_norm", -1);
  4227. cur = ggml_mul_mat(ctx0, model.output, cur);
  4228. cb(cur, "result_output", -1);
  4229. ggml_build_forward_expand(gf, cur);
  4230. return gf;
  4231. }
  4232. struct ggml_cgraph * build_persimmon() {
  4233. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4234. const int64_t n_embd_head = hparams.n_embd_head_v;
  4235. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4236. GGML_ASSERT(n_embd_head/2 == hparams.n_rot);
  4237. struct ggml_tensor * cur;
  4238. struct ggml_tensor * inpL;
  4239. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  4240. cb(inpL, "inp_embd", -1);
  4241. // inp_pos - contains the positions
  4242. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  4243. cb(inp_pos, "inp_pos", -1);
  4244. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4245. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  4246. cb(KQ_mask, "KQ_mask", -1);
  4247. if (do_rope_shift) {
  4248. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  4249. }
  4250. for (int il = 0; il < n_layer; ++il) {
  4251. struct ggml_tensor * residual = inpL;
  4252. cur = llm_build_norm(ctx0, inpL, hparams,
  4253. model.layers[il].attn_norm,
  4254. model.layers[il].attn_norm_b,
  4255. LLM_NORM, cb, il);
  4256. cb(cur, "attn_norm", il);
  4257. // self attention
  4258. {
  4259. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4260. cb(cur, "wqkv", il);
  4261. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4262. cb(cur, "bqkv", il);
  4263. // split qkv
  4264. GGML_ASSERT(n_head_kv == n_head);
  4265. struct ggml_tensor * tmpqkv = ggml_reshape_4d(ctx0, cur, n_embd_head, 3, n_head, n_tokens);
  4266. cb(tmpqkv, "tmpqkv", il);
  4267. struct ggml_tensor * tmpqkv_perm = ggml_cont(ctx0, ggml_permute(ctx0, tmpqkv, 0, 3, 1, 2));
  4268. cb(tmpqkv_perm, "tmpqkv", il);
  4269. struct ggml_tensor * tmpq = ggml_view_3d(
  4270. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  4271. ggml_element_size(tmpqkv_perm) * n_embd_head,
  4272. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  4273. 0
  4274. );
  4275. cb(tmpq, "tmpq", il);
  4276. struct ggml_tensor * tmpk = ggml_view_3d(
  4277. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  4278. ggml_element_size(tmpqkv_perm) * n_embd_head,
  4279. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  4280. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens
  4281. );
  4282. cb(tmpk, "tmpk", il);
  4283. // Q/K Layernorm
  4284. tmpq = llm_build_norm(ctx0, tmpq, hparams,
  4285. model.layers[il].attn_q_norm,
  4286. model.layers[il].attn_q_norm_b,
  4287. LLM_NORM, cb, il);
  4288. cb(tmpq, "tmpq", il);
  4289. tmpk = llm_build_norm(ctx0, tmpk, hparams,
  4290. model.layers[il].attn_k_norm,
  4291. model.layers[il].attn_k_norm_b,
  4292. LLM_NORM, cb, il);
  4293. cb(tmpk, "tmpk", il);
  4294. // RoPE the first n_rot of q/k, pass the other half, and concat.
  4295. struct ggml_tensor * qrot = ggml_view_3d(
  4296. ctx0, tmpq, hparams.n_rot, n_head, n_tokens,
  4297. ggml_element_size(tmpq) * n_embd_head,
  4298. ggml_element_size(tmpq) * n_embd_head * n_head,
  4299. 0
  4300. );
  4301. cb(qrot, "qrot", il);
  4302. struct ggml_tensor * krot = ggml_view_3d(
  4303. ctx0, tmpk, hparams.n_rot, n_head, n_tokens,
  4304. ggml_element_size(tmpk) * n_embd_head,
  4305. ggml_element_size(tmpk) * n_embd_head * n_head,
  4306. 0
  4307. );
  4308. cb(krot, "krot", il);
  4309. // get the second half of tmpq, e.g tmpq[n_rot:, :, :]
  4310. struct ggml_tensor * qpass = ggml_view_3d(
  4311. ctx0, tmpq, hparams.n_rot, n_head, n_tokens,
  4312. ggml_element_size(tmpq) * n_embd_head,
  4313. ggml_element_size(tmpq) * n_embd_head * n_head,
  4314. ggml_element_size(tmpq) * hparams.n_rot
  4315. );
  4316. cb(qpass, "qpass", il);
  4317. struct ggml_tensor * kpass = ggml_view_3d(
  4318. ctx0, tmpk, hparams.n_rot, n_head, n_tokens,
  4319. ggml_element_size(tmpk) * n_embd_head,
  4320. ggml_element_size(tmpk) * n_embd_head * n_head,
  4321. ggml_element_size(tmpk) * hparams.n_rot
  4322. );
  4323. cb(kpass, "kpass", il);
  4324. struct ggml_tensor * qrotated = ggml_rope_custom(
  4325. ctx0, qrot, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4326. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4327. );
  4328. cb(qrotated, "qrotated", il);
  4329. struct ggml_tensor * krotated = ggml_rope_custom(
  4330. ctx0, krot, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4331. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4332. );
  4333. cb(krotated, "krotated", il);
  4334. // ggml currently only supports concatenation on dim=2
  4335. // so we need to permute qrot, qpass, concat, then permute back.
  4336. qrotated = ggml_cont(ctx0, ggml_permute(ctx0, qrotated, 2, 1, 0, 3));
  4337. cb(qrotated, "qrotated", il);
  4338. krotated = ggml_cont(ctx0, ggml_permute(ctx0, krotated, 2, 1, 0, 3));
  4339. cb(krotated, "krotated", il);
  4340. qpass = ggml_cont(ctx0, ggml_permute(ctx0, qpass, 2, 1, 0, 3));
  4341. cb(qpass, "qpass", il);
  4342. kpass = ggml_cont(ctx0, ggml_permute(ctx0, kpass, 2, 1, 0, 3));
  4343. cb(kpass, "kpass", il);
  4344. struct ggml_tensor * Qcur = ggml_concat(ctx0, qrotated, qpass);
  4345. cb(Qcur, "Qcur", il);
  4346. struct ggml_tensor * Kcur = ggml_concat(ctx0, krotated, kpass);
  4347. cb(Kcur, "Kcur", il);
  4348. struct ggml_tensor * Q = ggml_cont(ctx0, ggml_permute(ctx0, Qcur, 2, 1, 0, 3));
  4349. cb(Q, "Q", il);
  4350. Kcur = ggml_cont(ctx0, ggml_permute(ctx0, Kcur, 2, 1, 0, 3));
  4351. cb(Kcur, "Kcur", il);
  4352. struct ggml_tensor * Vcur = ggml_view_3d(
  4353. ctx0, tmpqkv_perm, n_embd_head, n_head, n_tokens,
  4354. ggml_element_size(tmpqkv_perm) * n_embd_head,
  4355. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head,
  4356. ggml_element_size(tmpqkv_perm) * n_embd_head * n_head * n_tokens * 2
  4357. );
  4358. cb(Vcur, "Vcur", il);
  4359. llm_build_kv_store(ctx0, hparams, kv_self, gf, Kcur, Vcur, n_ctx, n_tokens, kv_head, cb, il);
  4360. // TODO: not tested, could be broken
  4361. cur = llm_build_kqv(ctx0, model, hparams, kv_self,
  4362. model.layers[il].wo, model.layers[il].bo,
  4363. Q, KQ_mask, n_ctx, n_tokens, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4364. cb(cur, "kqv_out", il);
  4365. }
  4366. struct ggml_tensor * ffn_inp = ggml_add(ctx0, residual, cur);
  4367. cb(ffn_inp, "ffn_inp", il);
  4368. // feed-forward network
  4369. {
  4370. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4371. model.layers[il].ffn_norm,
  4372. model.layers[il].ffn_norm_b,
  4373. LLM_NORM, cb, il);
  4374. cb(cur, "ffn_norm", il);
  4375. cur = llm_build_ffn(ctx0, cur,
  4376. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  4377. NULL, NULL,
  4378. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  4379. NULL,
  4380. LLM_FFN_RELU_SQR, LLM_FFN_SEQ, cb, il);
  4381. cb(cur, "ffn_out", il);
  4382. }
  4383. cur = ggml_add(ctx0, cur, ffn_inp);
  4384. cb(cur, "l_out", il);
  4385. inpL = cur;
  4386. }
  4387. cur = inpL;
  4388. cur = llm_build_norm(ctx0, cur, hparams,
  4389. model.output_norm,
  4390. model.output_norm_b,
  4391. LLM_NORM, cb, -1);
  4392. cb(cur, "result_norm", -1);
  4393. cur = ggml_mul_mat(ctx0, model.output, cur);
  4394. cb(cur, "result_output", -1);
  4395. ggml_build_forward_expand(gf, cur);
  4396. return gf;
  4397. }
  4398. struct ggml_cgraph * build_refact() {
  4399. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4400. const int64_t n_embd_head = hparams.n_embd_head_v;
  4401. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4402. struct ggml_tensor * cur;
  4403. struct ggml_tensor * inpL;
  4404. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  4405. cb(inpL, "inp_embd", -1);
  4406. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4407. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  4408. cb(KQ_mask, "KQ_mask", -1);
  4409. for (int il = 0; il < n_layer; ++il) {
  4410. struct ggml_tensor * inpSA = inpL;
  4411. cur = llm_build_norm(ctx0, inpL, hparams,
  4412. model.layers[il].attn_norm, NULL,
  4413. LLM_NORM_RMS, cb, il);
  4414. cb(cur, "attn_norm", il);
  4415. // self-attention
  4416. {
  4417. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4418. cb(Qcur, "Qcur", il);
  4419. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4420. cb(Kcur, "Kcur", il);
  4421. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4422. cb(Vcur, "Vcur", il);
  4423. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  4424. cb(Kcur, "Kcur", il);
  4425. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4426. cb(Qcur, "Qcur", il);
  4427. llm_build_kv_store(ctx0, hparams, kv_self, gf, Kcur, Vcur, n_ctx, n_tokens, kv_head, cb, il);
  4428. cur = llm_build_kqv(ctx0, model, hparams, kv_self,
  4429. model.layers[il].wo, NULL,
  4430. Qcur, KQ_mask, n_ctx, n_tokens, n_kv, 8.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4431. cb(cur, "kqv_out", il);
  4432. }
  4433. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4434. cb(ffn_inp, "ffn_inp", il);
  4435. // feed-forward network
  4436. {
  4437. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4438. model.layers[il].ffn_norm, NULL,
  4439. LLM_NORM_RMS, cb, il);
  4440. cb(cur, "ffn_norm", il);
  4441. cur = llm_build_ffn(ctx0, cur,
  4442. model.layers[il].ffn_up, NULL,
  4443. model.layers[il].ffn_gate, NULL,
  4444. model.layers[il].ffn_down, NULL,
  4445. NULL,
  4446. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4447. cb(cur, "ffn_out", il);
  4448. }
  4449. cur = ggml_add(ctx0, cur, ffn_inp);
  4450. cb(cur, "l_out", il);
  4451. // input for next layer
  4452. inpL = cur;
  4453. }
  4454. cur = inpL;
  4455. cur = llm_build_norm(ctx0, cur, hparams,
  4456. model.output_norm, NULL,
  4457. LLM_NORM_RMS, cb, -1);
  4458. cb(cur, "result_norm", -1);
  4459. // lm_head
  4460. cur = ggml_mul_mat(ctx0, model.output, cur);
  4461. cb(cur, "result_output", -1);
  4462. ggml_build_forward_expand(gf, cur);
  4463. return gf;
  4464. }
  4465. struct ggml_cgraph * build_bloom() {
  4466. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4467. const int64_t n_embd_head = hparams.n_embd_head_v;
  4468. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4469. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4470. struct ggml_tensor * cur;
  4471. struct ggml_tensor * inpL;
  4472. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  4473. cb(inpL, "inp_embd", -1);
  4474. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4475. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  4476. cb(KQ_mask, "KQ_mask", -1);
  4477. inpL = llm_build_norm(ctx0, inpL, hparams,
  4478. model.tok_norm,
  4479. model.tok_norm_b,
  4480. LLM_NORM, cb, -1);
  4481. cb(inpL, "inp_norm", -1);
  4482. for (int il = 0; il < n_layer; ++il) {
  4483. cur = llm_build_norm(ctx0, inpL, hparams,
  4484. model.layers[il].attn_norm,
  4485. model.layers[il].attn_norm_b,
  4486. LLM_NORM, cb, il);
  4487. cb(cur, "attn_norm", il);
  4488. // self-attention
  4489. {
  4490. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4491. cb(cur, "wqkv", il);
  4492. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4493. cb(cur, "bqkv", il);
  4494. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4495. 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)));
  4496. 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)));
  4497. cb(Qcur, "Qcur", il);
  4498. cb(Kcur, "Kcur", il);
  4499. cb(Vcur, "Vcur", il);
  4500. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4501. llm_build_kv_store(ctx0, hparams, kv_self, gf, Kcur, Vcur, n_ctx, n_tokens, kv_head, cb, il);
  4502. cur = llm_build_kqv(ctx0, model, hparams, kv_self,
  4503. model.layers[il].wo, model.layers[il].bo,
  4504. Qcur, KQ_mask, n_ctx, n_tokens, n_kv, 8.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4505. cb(cur, "kqv_out", il);
  4506. }
  4507. // Add the input
  4508. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  4509. cb(ffn_inp, "ffn_inp", il);
  4510. // FF
  4511. {
  4512. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4513. model.layers[il].ffn_norm,
  4514. model.layers[il].ffn_norm_b,
  4515. LLM_NORM, cb, il);
  4516. cb(cur, "ffn_norm", il);
  4517. cur = llm_build_ffn(ctx0, cur,
  4518. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  4519. NULL, NULL,
  4520. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  4521. NULL,
  4522. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4523. cb(cur, "ffn_out", il);
  4524. }
  4525. inpL = ggml_add(ctx0, cur, ffn_inp);
  4526. cb(inpL, "l_out", il);
  4527. }
  4528. cur = llm_build_norm(ctx0, inpL, hparams,
  4529. model.output_norm,
  4530. model.output_norm_b,
  4531. LLM_NORM, cb, -1);
  4532. cb(cur, "result_norm", -1);
  4533. cur = ggml_mul_mat(ctx0, model.output, cur);
  4534. cb(cur, "result_output", -1);
  4535. ggml_build_forward_expand(gf, cur);
  4536. return gf;
  4537. }
  4538. struct ggml_cgraph * build_mpt() {
  4539. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4540. const int64_t n_embd_head = hparams.n_embd_head_v;
  4541. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4542. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4543. struct ggml_tensor * cur;
  4544. struct ggml_tensor * inpL;
  4545. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  4546. cb(inpL, "inp_embd", -1);
  4547. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4548. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  4549. cb(KQ_mask, "KQ_mask", -1);
  4550. for (int il = 0; il < n_layer; ++il) {
  4551. struct ggml_tensor * attn_norm;
  4552. attn_norm = llm_build_norm(ctx0, inpL, hparams,
  4553. model.layers[il].attn_norm,
  4554. NULL,
  4555. LLM_NORM, cb, il);
  4556. cb(attn_norm, "attn_norm", il);
  4557. // self-attention
  4558. {
  4559. cur = attn_norm;
  4560. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4561. cb(cur, "wqkv", il);
  4562. if (hparams.f_clamp_kqv > 0.0f) {
  4563. cur = ggml_clamp(ctx0, cur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
  4564. cb(cur, "wqkv_clamped", il);
  4565. }
  4566. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4567. 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)));
  4568. 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)));
  4569. cb(Qcur, "Qcur", il);
  4570. cb(Kcur, "Kcur", il);
  4571. cb(Vcur, "Vcur", il);
  4572. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4573. llm_build_kv_store(ctx0, hparams, kv_self, gf, Kcur, Vcur, n_ctx, n_tokens, kv_head, cb, il);
  4574. cur = llm_build_kqv(ctx0, model, hparams, kv_self,
  4575. model.layers[il].wo, NULL,
  4576. Qcur, KQ_mask, n_ctx, n_tokens, n_kv, hparams.f_max_alibi_bias, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4577. cb(cur, "kqv_out", il);
  4578. }
  4579. // Add the input
  4580. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  4581. cb(ffn_inp, "ffn_inp", il);
  4582. // feed forward
  4583. {
  4584. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4585. model.layers[il].ffn_norm,
  4586. NULL,
  4587. LLM_NORM, cb, il);
  4588. cb(cur, "ffn_norm", il);
  4589. cur = llm_build_ffn(ctx0, cur,
  4590. model.layers[il].ffn_up, NULL,
  4591. NULL, NULL,
  4592. model.layers[il].ffn_down, NULL,
  4593. model.layers[il].ffn_act,
  4594. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4595. cb(cur, "ffn_out", il);
  4596. }
  4597. cur = ggml_add(ctx0, cur, ffn_inp);
  4598. cb(cur, "l_out", il);
  4599. // input for next layer
  4600. inpL = cur;
  4601. }
  4602. cur = inpL;
  4603. cur = llm_build_norm(ctx0, cur, hparams,
  4604. model.output_norm,
  4605. NULL,
  4606. LLM_NORM, cb, -1);
  4607. cb(cur, "result_norm", -1);
  4608. cur = ggml_mul_mat(ctx0, model.output, cur);
  4609. cb(cur, "result_output", -1);
  4610. ggml_build_forward_expand(gf, cur);
  4611. return gf;
  4612. }
  4613. struct ggml_cgraph * build_stablelm() {
  4614. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  4615. const int64_t n_embd_head = hparams.n_embd_head_v;
  4616. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4617. struct ggml_tensor * cur;
  4618. struct ggml_tensor * inpL;
  4619. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  4620. cb(inpL, "inp_embd", -1);
  4621. // inp_pos - contains the positions
  4622. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  4623. cb(inp_pos, "inp_pos", -1);
  4624. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4625. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  4626. cb(KQ_mask, "KQ_mask", -1);
  4627. // shift the entire K-cache if needed
  4628. if (do_rope_shift) {
  4629. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  4630. }
  4631. for (int il = 0; il < n_layer; ++il) {
  4632. struct ggml_tensor * inpSA = inpL;
  4633. // norm
  4634. cur = llm_build_norm(ctx0, inpL, hparams,
  4635. model.layers[il].attn_norm,
  4636. model.layers[il].attn_norm_b,
  4637. LLM_NORM, cb, il);
  4638. cb(cur, "attn_norm", il);
  4639. // self-attention
  4640. {
  4641. // compute Q and K and RoPE them
  4642. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4643. cb(Qcur, "Qcur", il);
  4644. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4645. cb(Kcur, "Kcur", il);
  4646. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4647. cb(Vcur, "Vcur", il);
  4648. Qcur = ggml_rope_custom(
  4649. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  4650. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  4651. ext_factor, attn_factor, beta_fast, beta_slow
  4652. );
  4653. cb(Qcur, "Qcur", il);
  4654. Kcur = ggml_rope_custom(
  4655. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  4656. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  4657. ext_factor, attn_factor, beta_fast, beta_slow
  4658. );
  4659. cb(Kcur, "Kcur", il);
  4660. llm_build_kv_store(ctx0, hparams, kv_self, gf, Kcur, Vcur, n_ctx, n_tokens, kv_head, cb, il);
  4661. cur = llm_build_kqv(ctx0, model, hparams, kv_self,
  4662. model.layers[il].wo, NULL,
  4663. Qcur, KQ_mask, n_ctx, n_tokens, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4664. cb(cur, "kqv_out", il);
  4665. }
  4666. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4667. cb(ffn_inp, "ffn_inp", il);
  4668. // feed-forward network
  4669. {
  4670. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4671. model.layers[il].ffn_norm,
  4672. model.layers[il].ffn_norm_b,
  4673. LLM_NORM, cb, il);
  4674. cb(cur, "ffn_norm", il);
  4675. cur = llm_build_ffn(ctx0, cur,
  4676. model.layers[il].ffn_up, NULL,
  4677. model.layers[il].ffn_gate, NULL,
  4678. model.layers[il].ffn_down, NULL,
  4679. NULL,
  4680. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4681. cb(cur, "ffn_out", il);
  4682. }
  4683. cur = ggml_add(ctx0, cur, ffn_inp);
  4684. cb(cur, "l_out", il);
  4685. // input for next layer
  4686. inpL = cur;
  4687. }
  4688. cur = inpL;
  4689. cur = llm_build_norm(ctx0, cur, hparams,
  4690. model.output_norm,
  4691. model.output_norm_b,
  4692. LLM_NORM, cb, -1);
  4693. cb(cur, "result_norm", -1);
  4694. // lm_head
  4695. cur = ggml_mul_mat(ctx0, model.output, cur);
  4696. cb(cur, "result_output", -1);
  4697. ggml_build_forward_expand(gf, cur);
  4698. return gf;
  4699. }
  4700. struct ggml_cgraph * build_qwen() {
  4701. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4702. const int64_t n_embd_head = hparams.n_embd_head_v;
  4703. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4704. struct ggml_tensor * cur;
  4705. struct ggml_tensor * inpL;
  4706. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  4707. cb(inpL, "inp_embd", -1);
  4708. // inp_pos - contains the positions
  4709. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  4710. cb(inp_pos, "inp_pos", -1);
  4711. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4712. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  4713. cb(KQ_mask, "KQ_mask", -1);
  4714. // shift the entire K-cache if needed
  4715. if (do_rope_shift) {
  4716. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  4717. }
  4718. for (int il = 0; il < n_layer; ++il) {
  4719. struct ggml_tensor * inpSA = inpL;
  4720. cur = llm_build_norm(ctx0, inpL, hparams,
  4721. model.layers[il].attn_norm, NULL,
  4722. LLM_NORM_RMS, cb, il);
  4723. cb(cur, "attn_norm", il);
  4724. // self-attention
  4725. {
  4726. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  4727. cb(cur, "wqkv", il);
  4728. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4729. cb(cur, "bqkv", il);
  4730. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4731. struct ggml_tensor * Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  4732. struct ggml_tensor * Vcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 2*sizeof(float)*(n_embd)));
  4733. cb(Qcur, "Qcur", il);
  4734. cb(Kcur, "Kcur", il);
  4735. cb(Vcur, "Vcur", il);
  4736. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4737. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  4738. // using mode = 2 for neox mode
  4739. Qcur = ggml_rope_custom(
  4740. ctx0, Qcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4741. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4742. );
  4743. cb(Qcur, "Qcur", il);
  4744. Kcur = ggml_rope_custom(
  4745. ctx0, Kcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4746. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4747. );
  4748. cb(Kcur, "Kcur", il);
  4749. llm_build_kv_store(ctx0, hparams, kv_self, gf, Kcur, Vcur, n_ctx, n_tokens, kv_head, cb, il);
  4750. cur = llm_build_kqv(ctx0, model, hparams, kv_self,
  4751. model.layers[il].wo, NULL,
  4752. Qcur, KQ_mask, n_ctx, n_tokens, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4753. cb(cur, "kqv_out", il);
  4754. }
  4755. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4756. cb(ffn_inp, "ffn_inp", il);
  4757. // feed-forward forward
  4758. {
  4759. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4760. model.layers[il].ffn_norm, NULL,
  4761. LLM_NORM_RMS, cb, il);
  4762. cb(cur, "ffn_norm", il);
  4763. cur = llm_build_ffn(ctx0, cur,
  4764. model.layers[il].ffn_up, NULL,
  4765. model.layers[il].ffn_gate, NULL,
  4766. model.layers[il].ffn_down, NULL,
  4767. NULL,
  4768. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4769. cb(cur, "ffn_out", il);
  4770. }
  4771. cur = ggml_add(ctx0, cur, ffn_inp);
  4772. cb(cur, "l_out", il);
  4773. // input for next layer
  4774. inpL = cur;
  4775. }
  4776. cur = inpL;
  4777. cur = llm_build_norm(ctx0, cur, hparams,
  4778. model.output_norm, NULL,
  4779. LLM_NORM_RMS, cb, -1);
  4780. cb(cur, "result_norm", -1);
  4781. // lm_head
  4782. cur = ggml_mul_mat(ctx0, model.output, cur);
  4783. cb(cur, "result_output", -1);
  4784. ggml_build_forward_expand(gf, cur);
  4785. return gf;
  4786. }
  4787. struct ggml_cgraph * build_qwen2() {
  4788. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4789. const int64_t n_embd_head = hparams.n_embd_head_v;
  4790. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4791. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4792. struct ggml_tensor * cur;
  4793. struct ggml_tensor * inpL;
  4794. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  4795. cb(inpL, "inp_embd", -1);
  4796. // inp_pos - contains the positions
  4797. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  4798. cb(inp_pos, "inp_pos", -1);
  4799. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4800. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  4801. cb(KQ_mask, "KQ_mask", -1);
  4802. // shift the entire K-cache if needed
  4803. if (do_rope_shift) {
  4804. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  4805. }
  4806. for (int il = 0; il < n_layer; ++il) {
  4807. struct ggml_tensor * inpSA = inpL;
  4808. // norm
  4809. cur = llm_build_norm(ctx0, inpL, hparams,
  4810. model.layers[il].attn_norm, NULL,
  4811. LLM_NORM_RMS, cb, il);
  4812. cb(cur, "attn_norm", il);
  4813. // self-attention
  4814. {
  4815. // compute Q and K and RoPE them
  4816. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  4817. cb(Qcur, "Qcur", il);
  4818. Qcur = ggml_add(ctx0, Qcur, model.layers[il].bq);
  4819. cb(Qcur, "Qcur", il);
  4820. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  4821. cb(Kcur, "Kcur", il);
  4822. Kcur = ggml_add(ctx0, Kcur, model.layers[il].bk);
  4823. cb(Kcur, "Kcur", il);
  4824. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  4825. cb(Vcur, "Vcur", il);
  4826. Vcur = ggml_add(ctx0, Vcur, model.layers[il].bv);
  4827. cb(Vcur, "Vcur", il);
  4828. // these nodes are added to the graph together so that they are not reordered
  4829. // by doing so, the number of splits in the graph is reduced
  4830. ggml_build_forward_expand(gf, Qcur);
  4831. ggml_build_forward_expand(gf, Kcur);
  4832. ggml_build_forward_expand(gf, Vcur);
  4833. Qcur = ggml_rope_custom(
  4834. ctx0, ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), inp_pos,
  4835. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  4836. ext_factor, attn_factor, beta_fast, beta_slow
  4837. );
  4838. cb(Qcur, "Qcur", il);
  4839. Kcur = ggml_rope_custom(
  4840. ctx0, ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), inp_pos,
  4841. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  4842. ext_factor, attn_factor, beta_fast, beta_slow
  4843. );
  4844. cb(Kcur, "Kcur", il);
  4845. llm_build_kv_store(ctx0, hparams, kv_self, gf, Kcur, Vcur, n_ctx, n_tokens, kv_head, cb, il);
  4846. cur = llm_build_kqv(ctx0, model, hparams, kv_self,
  4847. model.layers[il].wo, model.layers[il].bo,
  4848. Qcur, KQ_mask, n_ctx, n_tokens, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  4849. cb(cur, "kqv_out", il);
  4850. }
  4851. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
  4852. cb(ffn_inp, "ffn_inp", il);
  4853. // feed-forward network
  4854. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  4855. model.layers[il].ffn_norm, NULL,
  4856. LLM_NORM_RMS, cb, il);
  4857. cb(cur, "ffn_norm", il);
  4858. cur = llm_build_ffn(ctx0, cur,
  4859. model.layers[il].ffn_up, NULL,
  4860. model.layers[il].ffn_gate, NULL,
  4861. model.layers[il].ffn_down, NULL,
  4862. NULL,
  4863. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  4864. cb(cur, "ffn_out", il);
  4865. cur = ggml_add(ctx0, cur, ffn_inp);
  4866. cb(cur, "l_out", il);
  4867. // input for next layer
  4868. inpL = cur;
  4869. }
  4870. cur = inpL;
  4871. cur = llm_build_norm(ctx0, cur, hparams,
  4872. model.output_norm, NULL,
  4873. LLM_NORM_RMS, cb, -1);
  4874. cb(cur, "result_norm", -1);
  4875. // lm_head
  4876. cur = ggml_mul_mat(ctx0, model.output, cur);
  4877. cb(cur, "result_output", -1);
  4878. ggml_build_forward_expand(gf, cur);
  4879. return gf;
  4880. }
  4881. struct ggml_cgraph * build_phi2() {
  4882. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  4883. const int64_t n_embd_head = hparams.n_embd_head_v;
  4884. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  4885. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4886. struct ggml_tensor * cur;
  4887. struct ggml_tensor * attn_norm_output;
  4888. struct ggml_tensor * ffn_output;
  4889. struct ggml_tensor * inpL;
  4890. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  4891. cb(inpL, "inp_embd", -1);
  4892. // inp_pos - contains the positions
  4893. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  4894. cb(inp_pos, "inp_pos", -1);
  4895. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4896. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  4897. cb(KQ_mask, "KQ_mask", -1);
  4898. // shift the entire K-cache if needed
  4899. if (do_rope_shift) {
  4900. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, LLM_ROPE_NEOX, n_ctx, freq_base, freq_scale, cb);
  4901. }
  4902. for (int il = 0; il < n_layer; ++il) {
  4903. attn_norm_output = llm_build_norm(ctx0, inpL, hparams,
  4904. model.layers[il].attn_norm,
  4905. model.layers[il].attn_norm_b,
  4906. LLM_NORM, cb, il);
  4907. cb(attn_norm_output, "attn_norm", il);
  4908. // self-attention
  4909. {
  4910. struct ggml_tensor * Qcur = nullptr;
  4911. struct ggml_tensor * Kcur = nullptr;
  4912. struct ggml_tensor * Vcur = nullptr;
  4913. if (model.layers[il].wqkv) {
  4914. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, attn_norm_output);
  4915. cb(cur, "wqkv", il);
  4916. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  4917. cb(cur, "bqkv", il);
  4918. Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  4919. Kcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd_gqa, n_tokens, cur->nb[1], 1*sizeof(float)*(n_embd)));
  4920. 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)));
  4921. } else {
  4922. Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, attn_norm_output), model.layers[il].bq);
  4923. Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, attn_norm_output), model.layers[il].bk);
  4924. Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, attn_norm_output), model.layers[il].bv);
  4925. }
  4926. cb(Qcur, "Qcur", il);
  4927. cb(Kcur, "Kcur", il);
  4928. cb(Vcur, "Vcur", il);
  4929. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  4930. Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
  4931. Qcur = ggml_rope_custom(
  4932. ctx0, Qcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4933. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4934. );
  4935. cb(Qcur, "Qcur", il);
  4936. // with phi2, we scale the Q to avoid precision issues
  4937. // ref: https://github.com/ml-explore/mlx-examples/blob/08e862336ade809bc37d1035f94b359e7d1a5152/phi2/phi2.py#L64-L66
  4938. Qcur = ggml_scale(ctx0, Qcur, 1.0f/sqrtf(float(n_embd_head)));
  4939. cb(Qcur, "Qcur", il);
  4940. Kcur = ggml_rope_custom(
  4941. ctx0, Kcur, inp_pos, hparams.n_rot, 2, 0, n_orig_ctx,
  4942. freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow
  4943. );
  4944. cb(Kcur, "Kcur", il);
  4945. llm_build_kv_store(ctx0, hparams, kv_self, gf, Kcur, Vcur, n_ctx, n_tokens, kv_head, cb, il);
  4946. cur = llm_build_kqv(ctx0, model, hparams, kv_self,
  4947. model.layers[il].wo, model.layers[il].bo,
  4948. Qcur, KQ_mask, n_ctx, n_tokens, n_kv, -1.0f, 1.0f, cb, il);
  4949. cb(cur, "kqv_out", il);
  4950. }
  4951. // FF
  4952. {
  4953. ffn_output = llm_build_ffn(ctx0, attn_norm_output,
  4954. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  4955. NULL, NULL,
  4956. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  4957. NULL,
  4958. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  4959. cb(ffn_output, "ffn_out", il);
  4960. }
  4961. cur = ggml_add(ctx0, cur, ffn_output);
  4962. cb(cur, "l_out", il);
  4963. cur = ggml_add(ctx0, cur, inpL);
  4964. cb(cur, "l_out", il);
  4965. inpL = cur;
  4966. }
  4967. cur = llm_build_norm(ctx0, inpL, hparams,
  4968. model.output_norm,
  4969. model.output_norm_b,
  4970. LLM_NORM, cb, -1);
  4971. cb(cur, "result_norm", -1);
  4972. cur = ggml_mul_mat(ctx0, model.output, cur);
  4973. cb(cur, "result_output_no_bias", -1);
  4974. cur = ggml_add(ctx0, cur, model.output_b);
  4975. cb(cur, "result_output", -1);
  4976. ggml_build_forward_expand(gf, cur);
  4977. return gf;
  4978. }
  4979. struct ggml_cgraph * build_plamo() {
  4980. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  4981. const int64_t n_embd_head = hparams.n_embd_head_v;
  4982. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  4983. GGML_ASSERT(n_embd_head == hparams.n_rot);
  4984. struct ggml_tensor * cur;
  4985. struct ggml_tensor * inpL;
  4986. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  4987. cb(inpL, "inp_embd", -1);
  4988. // inp_pos - contains the positions
  4989. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  4990. cb(inp_pos, "inp_pos", -1);
  4991. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  4992. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  4993. cb(KQ_mask, "KQ_mask", -1);
  4994. // shift the entire K-cache if needed
  4995. if (do_rope_shift) {
  4996. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  4997. }
  4998. for (int il = 0; il < n_layer; ++il) {
  4999. // norm
  5000. cur = llm_build_norm(ctx0, inpL, hparams,
  5001. model.layers[il].attn_norm, NULL,
  5002. LLM_NORM_RMS, cb, il);
  5003. cb(cur, "attn_norm", il);
  5004. struct ggml_tensor * attention_norm = cur;
  5005. // self-attention
  5006. {
  5007. // compute Q and K and RoPE them
  5008. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
  5009. cb(Qcur, "Qcur", il);
  5010. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0, model.layers[il].wk, cur);
  5011. cb(Kcur, "Kcur", il);
  5012. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0, model.layers[il].wv, cur);
  5013. cb(Vcur, "Vcur", il);
  5014. Qcur = ggml_rope_custom(
  5015. ctx0, ggml_reshape_3d(ctx0, Qcur, hparams.n_rot, n_head, n_tokens), inp_pos,
  5016. n_embd_head, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5017. ext_factor, attn_factor, beta_fast, beta_slow);
  5018. cb(Qcur, "Qcur", il);
  5019. Kcur = ggml_rope_custom(
  5020. ctx0, ggml_reshape_3d(ctx0, Kcur, hparams.n_rot, n_head_kv, n_tokens), inp_pos,
  5021. n_embd_head, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5022. ext_factor, attn_factor, beta_fast, beta_slow);
  5023. cb(Kcur, "Kcur", il);
  5024. llm_build_kv_store(ctx0, hparams, kv_self, gf, Kcur, Vcur, n_ctx, n_tokens, kv_head, cb, il);
  5025. cur = llm_build_kqv(ctx0, model, hparams, kv_self,
  5026. model.layers[il].wo, NULL,
  5027. Qcur, KQ_mask, n_ctx, n_tokens, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5028. cb(cur, "kqv_out", il);
  5029. }
  5030. struct ggml_tensor * sa_out = cur;
  5031. cur = attention_norm;
  5032. // feed-forward network
  5033. {
  5034. cur = llm_build_ffn(ctx0, cur,
  5035. model.layers[il].ffn_up, NULL,
  5036. model.layers[il].ffn_gate, NULL,
  5037. model.layers[il].ffn_down, NULL,
  5038. NULL,
  5039. LLM_FFN_SILU, LLM_FFN_PAR, cb, il);
  5040. cb(cur, "ffn_out", il);
  5041. }
  5042. cur = ggml_add(ctx0, cur, sa_out);
  5043. cb(cur, "l_out", il);
  5044. cur = ggml_add(ctx0, cur, inpL);
  5045. cb(cur, "l_out", il);
  5046. // input for next layer
  5047. inpL = cur;
  5048. }
  5049. cur = inpL;
  5050. cur = llm_build_norm(ctx0, cur, hparams,
  5051. model.output_norm, NULL,
  5052. LLM_NORM_RMS, cb, -1);
  5053. cb(cur, "result_norm", -1);
  5054. // lm_head
  5055. cur = ggml_mul_mat(ctx0, model.output, cur);
  5056. cb(cur, "result_output", -1);
  5057. ggml_build_forward_expand(gf, cur);
  5058. return gf;
  5059. }
  5060. struct ggml_cgraph * build_gpt2() {
  5061. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5062. const int64_t n_embd_head = hparams.n_embd_head_v;
  5063. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5064. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5065. struct ggml_tensor * cur;
  5066. struct ggml_tensor * pos;
  5067. struct ggml_tensor * inpL;
  5068. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  5069. cb(inpL, "inp_embd", -1);
  5070. // inp_pos - contains the positions
  5071. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  5072. cb(inp_pos, "inp_pos", -1);
  5073. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5074. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  5075. cb(KQ_mask, "KQ_mask", -1);
  5076. pos = ggml_get_rows(ctx0, model.pos_embd, inp_pos);
  5077. cb(pos, "pos_embd", -1);
  5078. inpL = ggml_add(ctx0, inpL, pos);
  5079. cb(inpL, "inpL", -1);
  5080. for (int il = 0; il < n_layer; ++il) {
  5081. cur = llm_build_norm(ctx0, inpL, hparams,
  5082. model.layers[il].attn_norm,
  5083. model.layers[il].attn_norm_b,
  5084. LLM_NORM, cb, il);
  5085. cb(cur, "attn_norm", il);
  5086. // self-attention
  5087. {
  5088. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5089. cb(cur, "wqkv", il);
  5090. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5091. cb(cur, "bqkv", il);
  5092. struct ggml_tensor * Qcur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5093. 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)));
  5094. 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)));
  5095. cb(Qcur, "Qcur", il);
  5096. cb(Kcur, "Kcur", il);
  5097. cb(Vcur, "Vcur", il);
  5098. Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
  5099. llm_build_kv_store(ctx0, hparams, kv_self, gf, Kcur, Vcur, n_ctx, n_tokens, kv_head, cb, il);
  5100. cur = llm_build_kqv(ctx0, model, hparams, kv_self,
  5101. model.layers[il].wo, model.layers[il].bo,
  5102. Qcur, KQ_mask, n_ctx, n_tokens, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5103. cb(cur, "kqv_out", il);
  5104. }
  5105. // add the input
  5106. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5107. cb(ffn_inp, "ffn_inp", il);
  5108. // FF
  5109. {
  5110. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5111. model.layers[il].ffn_norm,
  5112. model.layers[il].ffn_norm_b,
  5113. LLM_NORM, cb, il);
  5114. cb(cur, "ffn_norm", il);
  5115. cur = llm_build_ffn(ctx0, cur,
  5116. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5117. NULL, NULL,
  5118. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5119. NULL,
  5120. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5121. cb(cur, "ffn_out", il);
  5122. }
  5123. inpL = ggml_add(ctx0, cur, ffn_inp);
  5124. cb(inpL, "l_out", il);
  5125. }
  5126. cur = llm_build_norm(ctx0, inpL, hparams,
  5127. model.output_norm,
  5128. model.output_norm_b,
  5129. LLM_NORM, cb, -1);
  5130. cb(cur, "result_norm", -1);
  5131. cur = ggml_mul_mat(ctx0, model.output, cur);
  5132. cb(cur, "result_output", -1);
  5133. ggml_build_forward_expand(gf, cur);
  5134. return gf;
  5135. }
  5136. struct ggml_cgraph * build_codeshell() {
  5137. struct ggml_cgraph * gf = ggml_new_graph_custom(ctx0, LLAMA_MAX_NODES, false);
  5138. const int64_t n_embd_head = hparams.n_embd_head_v;
  5139. const int64_t n_embd_gqa = hparams.n_embd_v_gqa();
  5140. GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
  5141. GGML_ASSERT(n_embd_head == hparams.n_rot);
  5142. struct ggml_tensor * cur;
  5143. struct ggml_tensor * inpL;
  5144. inpL = llm_build_inp_embd(ctx0, hparams, batch, model.tok_embd, cb);
  5145. cb(inpL, "inp_embd", -1);
  5146. // inp_pos - contains the positions
  5147. struct ggml_tensor * inp_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_tokens);
  5148. cb(inp_pos, "inp_pos", -1);
  5149. // KQ_mask (mask for 1 head, it will be broadcasted to all heads)
  5150. struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_tokens, 1);
  5151. cb(KQ_mask, "KQ_mask", -1);
  5152. // shift the entire K-cache if needed
  5153. if (do_rope_shift) {
  5154. llm_build_k_shift(ctx0, hparams, cparams, kv_self, gf, LLM_ROPE, n_ctx, freq_base, freq_scale, cb);
  5155. }
  5156. for (int il = 0; il < n_layer; ++il) {
  5157. cur = llm_build_norm(ctx0, inpL, hparams,
  5158. model.layers[il].attn_norm,
  5159. model.layers[il].attn_norm_b,
  5160. LLM_NORM, cb, il);
  5161. cb(cur, "attn_norm", il);
  5162. // self-attention
  5163. {
  5164. cur = ggml_mul_mat(ctx0, model.layers[il].wqkv, cur);
  5165. cb(cur, "wqkv", il);
  5166. cur = ggml_add(ctx0, cur, model.layers[il].bqkv);
  5167. cb(cur, "bqkv", il);
  5168. struct ggml_tensor * tmpq = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*(n_embd)));
  5169. 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)));
  5170. 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)));
  5171. cb(tmpq, "tmpq", il);
  5172. cb(tmpk, "tmpk", il);
  5173. cb(Vcur, "Vcur", il);
  5174. struct ggml_tensor * Qcur = ggml_rope_custom(
  5175. ctx0, ggml_reshape_3d(ctx0, tmpq, n_embd_head, n_head, n_tokens), inp_pos,
  5176. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5177. ext_factor, attn_factor, beta_fast, beta_slow
  5178. );
  5179. cb(Qcur, "Qcur", il);
  5180. struct ggml_tensor * Kcur = ggml_rope_custom(
  5181. ctx0, ggml_reshape_3d(ctx0, tmpk, n_embd_head, n_head_kv, n_tokens), inp_pos,
  5182. hparams.n_rot, 2, 0, n_orig_ctx, freq_base, freq_scale,
  5183. ext_factor, attn_factor, beta_fast, beta_slow
  5184. );
  5185. cb(Kcur, "Kcur", il);
  5186. llm_build_kv_store(ctx0, hparams, kv_self, gf, Kcur, Vcur, n_ctx, n_tokens, kv_head, cb, il);
  5187. cur = llm_build_kqv(ctx0, model, hparams, kv_self,
  5188. model.layers[il].wo, model.layers[il].bo,
  5189. Qcur, KQ_mask, n_ctx, n_tokens, n_kv, -1.0f, 1.0f/sqrtf(float(n_embd_head)), cb, il);
  5190. cb(cur, "kqv_out", il);
  5191. }
  5192. // add the input
  5193. struct ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL);
  5194. cb(ffn_inp, "ffn_inp", il);
  5195. // FF
  5196. {
  5197. cur = llm_build_norm(ctx0, ffn_inp, hparams,
  5198. model.layers[il].ffn_norm,
  5199. model.layers[il].ffn_norm_b,
  5200. LLM_NORM, cb, il);
  5201. cb(cur, "ffn_norm", il);
  5202. cur = llm_build_ffn(ctx0, cur,
  5203. model.layers[il].ffn_up, model.layers[il].ffn_up_b,
  5204. NULL, NULL,
  5205. model.layers[il].ffn_down, model.layers[il].ffn_down_b,
  5206. NULL,
  5207. LLM_FFN_GELU, LLM_FFN_SEQ, cb, il);
  5208. cb(cur, "ffn_out", il);
  5209. }
  5210. inpL = ggml_add(ctx0, cur, ffn_inp);
  5211. cb(inpL, "l_out", il);
  5212. }
  5213. cur = llm_build_norm(ctx0, inpL, hparams,
  5214. model.output_norm,
  5215. model.output_norm_b,
  5216. LLM_NORM, cb, -1);
  5217. cb(cur, "result_norm", -1);
  5218. cur = ggml_mul_mat(ctx0, model.output, cur);
  5219. cb(cur, "result_output", -1);
  5220. ggml_build_forward_expand(gf, cur);
  5221. return gf;
  5222. }
  5223. };
  5224. static struct ggml_cgraph * llama_build_graph(
  5225. llama_context & lctx,
  5226. const llama_batch & batch) {
  5227. const auto & model = lctx.model;
  5228. // check if we should build the worst-case graph (for memory measurement)
  5229. const bool worst_case = ggml_tallocr_is_measure(lctx.alloc);
  5230. // keep track of the input that has already been allocated
  5231. bool alloc_inp_tokens = false;
  5232. bool alloc_inp_embd = false;
  5233. bool alloc_inp_pos = false;
  5234. bool alloc_inp_KQ_mask = false;
  5235. bool alloc_inp_K_shift = false;
  5236. // this callback allows us to apply custom logic to each tensor (e.g. ggml-alloc, offloading, etc.)
  5237. // TODO: improve handling of input and output tensors, then replace this with ggml_set_name
  5238. llm_build_cb cb = [&](struct ggml_tensor * cur, const char * name, int il) {
  5239. if (il >= 0) {
  5240. ggml_format_name(cur, "%s-%d", name, il);
  5241. } else {
  5242. ggml_set_name(cur, name);
  5243. }
  5244. //
  5245. // allocate input tensors and set input data
  5246. //
  5247. if (!alloc_inp_tokens && strcmp(name, "inp_tokens") == 0) {
  5248. ggml_tallocr_alloc(lctx.alloc, cur);
  5249. if (!ggml_tallocr_is_measure(lctx.alloc) && batch.token) {
  5250. const int64_t n_tokens = cur->ne[0];
  5251. ggml_backend_tensor_set(cur, batch.token, 0, n_tokens*ggml_element_size(cur));
  5252. }
  5253. alloc_inp_tokens = true;
  5254. }
  5255. if (!alloc_inp_embd && strcmp(name, "inp_embd") == 0 && batch.embd) {
  5256. ggml_tallocr_alloc(lctx.alloc, cur);
  5257. if (!ggml_tallocr_is_measure(lctx.alloc) && batch.embd) {
  5258. const int64_t n_embd = cur->ne[0];
  5259. const int64_t n_tokens = cur->ne[1];
  5260. ggml_backend_tensor_set(cur, batch.embd, 0, n_tokens*n_embd*ggml_element_size(cur));
  5261. }
  5262. alloc_inp_embd = true;
  5263. }
  5264. if (!alloc_inp_pos && strcmp(name, "inp_pos") == 0) {
  5265. ggml_tallocr_alloc(lctx.alloc, cur);
  5266. if (!ggml_tallocr_is_measure(lctx.alloc) && batch.pos) {
  5267. const int64_t n_tokens = cur->ne[0];
  5268. static_assert(std::is_same<llama_pos, int32_t>::value, "llama_pos must be int32_t");
  5269. ggml_backend_tensor_set(cur, batch.pos, 0, n_tokens*ggml_element_size(cur));
  5270. }
  5271. alloc_inp_pos = true;
  5272. }
  5273. if (!alloc_inp_KQ_mask && strcmp(name, "KQ_mask") == 0) {
  5274. ggml_tallocr_alloc(lctx.alloc, cur);
  5275. if (!ggml_tallocr_is_measure(lctx.alloc)) {
  5276. const int64_t n_kv = cur->ne[0];
  5277. const int64_t n_tokens = cur->ne[1];
  5278. float * data;
  5279. if (ggml_backend_buffer_is_host(cur->buffer)) {
  5280. data = (float *) cur->data;
  5281. } else {
  5282. lctx.buf_copy.resize(ggml_nbytes(cur));
  5283. data = (float *) lctx.buf_copy.data();
  5284. }
  5285. for (int h = 0; h < 1; ++h) {
  5286. for (int j = 0; j < n_tokens; ++j) {
  5287. const llama_pos pos = batch.pos[j];
  5288. const llama_seq_id seq_id = batch.seq_id[j][0];
  5289. for (int i = 0; i < n_kv; ++i) {
  5290. float f;
  5291. if (!lctx.kv_self.cells[i].has_seq_id(seq_id) || lctx.kv_self.cells[i].pos > pos) {
  5292. f = -INFINITY;
  5293. } else {
  5294. f = 0;
  5295. }
  5296. data[h*(n_kv*n_tokens) + j*n_kv + i] = f;
  5297. }
  5298. }
  5299. }
  5300. if (data != cur->data) {
  5301. ggml_backend_tensor_set(cur, data, 0, ggml_nbytes(cur));
  5302. }
  5303. }
  5304. alloc_inp_KQ_mask = true;
  5305. }
  5306. if (!alloc_inp_K_shift && strcmp(name, "K_shift") == 0) {
  5307. ggml_tallocr_alloc(lctx.alloc, cur);
  5308. if (!ggml_tallocr_is_measure(lctx.alloc)) {
  5309. const int64_t n_ctx = cur->ne[0];
  5310. int32_t * data;
  5311. if (ggml_backend_buffer_is_host(cur->buffer)) {
  5312. data = (int32_t *) cur->data;
  5313. } else {
  5314. lctx.buf_copy.resize(ggml_nbytes(cur));
  5315. data = (int32_t *) lctx.buf_copy.data();
  5316. }
  5317. for (int i = 0; i < n_ctx; ++i) {
  5318. data[i] = lctx.kv_self.cells[i].delta;
  5319. }
  5320. if (data != cur->data) {
  5321. ggml_backend_tensor_set(cur, data, 0, ggml_nbytes(cur));
  5322. }
  5323. }
  5324. alloc_inp_K_shift = true;
  5325. }
  5326. };
  5327. struct ggml_cgraph * result = NULL;
  5328. struct llm_build_context llm(lctx, batch, cb, worst_case);
  5329. llm.init();
  5330. switch (model.arch) {
  5331. case LLM_ARCH_LLAMA:
  5332. {
  5333. result = llm.build_llama();
  5334. } break;
  5335. case LLM_ARCH_BAICHUAN:
  5336. {
  5337. result = llm.build_baichuan();
  5338. } break;
  5339. case LLM_ARCH_FALCON:
  5340. {
  5341. result = llm.build_falcon();
  5342. } break;
  5343. case LLM_ARCH_STARCODER:
  5344. {
  5345. result = llm.build_starcoder();
  5346. } break;
  5347. case LLM_ARCH_PERSIMMON:
  5348. {
  5349. result = llm.build_persimmon();
  5350. } break;
  5351. case LLM_ARCH_REFACT:
  5352. {
  5353. result = llm.build_refact();
  5354. } break;
  5355. case LLM_ARCH_BLOOM:
  5356. {
  5357. result = llm.build_bloom();
  5358. } break;
  5359. case LLM_ARCH_MPT:
  5360. {
  5361. result = llm.build_mpt();
  5362. } break;
  5363. case LLM_ARCH_STABLELM:
  5364. {
  5365. result = llm.build_stablelm();
  5366. } break;
  5367. case LLM_ARCH_QWEN:
  5368. {
  5369. result = llm.build_qwen();
  5370. } break;
  5371. case LLM_ARCH_QWEN2:
  5372. {
  5373. result = llm.build_qwen2();
  5374. } break;
  5375. case LLM_ARCH_PHI2:
  5376. {
  5377. result = llm.build_phi2();
  5378. } break;
  5379. case LLM_ARCH_PLAMO:
  5380. {
  5381. result = llm.build_plamo();
  5382. } break;
  5383. case LLM_ARCH_GPT2:
  5384. {
  5385. result = llm.build_gpt2();
  5386. } break;
  5387. case LLM_ARCH_CODESHELL:
  5388. {
  5389. result = llm.build_codeshell();
  5390. } break;
  5391. default:
  5392. GGML_ASSERT(false);
  5393. }
  5394. llm.free();
  5395. return result;
  5396. }
  5397. // decode a batch of tokens by evaluating the transformer
  5398. //
  5399. // - lctx: llama context
  5400. // - batch: batch to evaluate
  5401. //
  5402. // return 0 on success
  5403. // return positive int on warning
  5404. // return negative int on error
  5405. //
  5406. static int llama_decode_internal(
  5407. llama_context & lctx,
  5408. llama_batch batch) {
  5409. const uint32_t n_tokens = batch.n_tokens;
  5410. if (n_tokens == 0) {
  5411. LLAMA_LOG_ERROR("%s: n_tokens == 0", __func__);
  5412. return -1;
  5413. }
  5414. const auto & model = lctx.model;
  5415. const auto & hparams = model.hparams;
  5416. const auto & cparams = lctx.cparams;
  5417. const auto n_batch = cparams.n_batch;
  5418. GGML_ASSERT(n_tokens <= n_batch);
  5419. int n_threads = n_tokens == 1 ? cparams.n_threads : cparams.n_threads_batch;
  5420. GGML_ASSERT((!batch.token && batch.embd) || (batch.token && !batch.embd)); // NOLINT
  5421. const int64_t t_start_us = ggml_time_us();
  5422. #ifdef GGML_USE_MPI
  5423. // TODO: needs fix after #3228
  5424. GGML_ASSERT(false && "not implemented");
  5425. //ggml_mpi_eval_init(lctx.ctx_mpi, &n_tokens, &n_past, &n_threads);
  5426. #endif
  5427. GGML_ASSERT(n_threads > 0);
  5428. auto & kv_self = lctx.kv_self;
  5429. const int64_t n_embd = hparams.n_embd;
  5430. const int64_t n_vocab = hparams.n_vocab;
  5431. // helpers for smoother batch API transition
  5432. // after deprecating the llama_eval calls, these will be removed
  5433. std::vector<llama_pos> pos;
  5434. std::vector<int32_t> n_seq_id;
  5435. std::vector<llama_seq_id *> seq_id_arr;
  5436. std::vector<std::vector<llama_seq_id>> seq_id;
  5437. if (batch.pos == nullptr) {
  5438. pos.resize(n_tokens);
  5439. for (uint32_t i = 0; i < n_tokens; i++) {
  5440. pos[i] = batch.all_pos_0 + i*batch.all_pos_1;
  5441. }
  5442. batch.pos = pos.data();
  5443. }
  5444. if (batch.seq_id == nullptr) {
  5445. n_seq_id.resize(n_tokens);
  5446. seq_id.resize(n_tokens);
  5447. seq_id_arr.resize(n_tokens);
  5448. for (uint32_t i = 0; i < n_tokens; i++) {
  5449. n_seq_id[i] = 1;
  5450. seq_id[i].resize(1);
  5451. seq_id[i][0] = batch.all_seq_id;
  5452. seq_id_arr[i] = seq_id[i].data();
  5453. }
  5454. batch.n_seq_id = n_seq_id.data();
  5455. batch.seq_id = seq_id_arr.data();
  5456. }
  5457. // if we have enough unused cells before the current head ->
  5458. // better to start searching from the beginning of the cache, hoping to fill it
  5459. if (kv_self.head > kv_self.used + 2*n_tokens) {
  5460. kv_self.head = 0;
  5461. }
  5462. if (!llama_kv_cache_find_slot(kv_self, batch)) {
  5463. return 1;
  5464. }
  5465. // a heuristic, to avoid attending the full cache if it is not yet utilized
  5466. // after enough generations, the benefit from this heuristic disappears
  5467. // if we start defragmenting the cache, the benefit from this will be more important
  5468. kv_self.n = std::min((int32_t) cparams.n_ctx, std::max(32, GGML_PAD(llama_kv_cache_cell_max(kv_self), 32)));
  5469. //kv_self.n = llama_kv_cache_cell_max(kv_self);
  5470. //printf("kv_self.n = %5d, kv_self.used = %5d, kv_self.head = %5d\n", kv_self.n, kv_self.used, kv_self.head);
  5471. ggml_backend_sched_reset(lctx.sched);
  5472. ggml_backend_sched_set_eval_callback(lctx.sched, lctx.cparams.cb_eval, lctx.cparams.cb_eval_user_data);
  5473. ggml_cgraph * gf = llama_build_graph(lctx, batch);
  5474. // the output is always the last tensor in the graph
  5475. struct ggml_tensor * res = gf->nodes[gf->n_nodes - 1];
  5476. GGML_ASSERT(strcmp(res->name, "result_output") == 0);
  5477. // the embeddings could be the second to last tensor, or the third to last tensor
  5478. struct ggml_tensor * embeddings = gf->nodes[gf->n_nodes - 2];
  5479. if (strcmp(embeddings->name, "result_norm") != 0) {
  5480. embeddings = gf->nodes[gf->n_nodes - 3];
  5481. GGML_ASSERT(strcmp(embeddings->name, "result_norm") == 0);
  5482. }
  5483. // 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);
  5484. // for big prompts, if BLAS is enabled, it is better to use only one thread
  5485. // otherwise, the threads are spin-lock waiting for the BLAS calls and are degrading the performance
  5486. // TODO: this is mostly important for Apple Silicon where CBLAS is still performing very well
  5487. // we still need some threads to process all non-mul_mat ops, but not too much to avoid interfering
  5488. // with the BLAS calls. need a better solution
  5489. if (n_tokens >= 32 && ggml_cpu_has_blas() && !ggml_cpu_has_gpublas()) {
  5490. n_threads = std::min(4, n_threads);
  5491. }
  5492. const bool fully_offloaded = model.n_gpu_layers >= (int) hparams.n_layer + 1;
  5493. if (ggml_cpu_has_cublas() && fully_offloaded) {
  5494. n_threads = 1;
  5495. }
  5496. #ifdef GGML_USE_MPI
  5497. const int64_t n_layer = hparams.n_layer;
  5498. ggml_mpi_graph_compute_pre(lctx.ctx_mpi, gf, n_layer);
  5499. #endif
  5500. #ifdef GGML_USE_METAL
  5501. if (ggml_backend_is_metal(lctx.backend_metal)) {
  5502. ggml_backend_metal_set_n_cb(lctx.backend_metal, n_threads);
  5503. }
  5504. #endif
  5505. if (lctx.backend_cpu != nullptr) {
  5506. ggml_backend_cpu_set_n_threads(lctx.backend_cpu, n_threads);
  5507. }
  5508. ggml_backend_sched_graph_compute(lctx.sched, gf);
  5509. // fprintf(stderr, "splits: %d\n", ggml_backend_sched_get_n_splits(lctx.sched));
  5510. #ifdef GGML_USE_MPI
  5511. ggml_mpi_graph_compute_post(lctx.ctx_mpi, gf, n_layer);
  5512. #endif
  5513. // update the kv ring buffer
  5514. {
  5515. if (kv_self.has_shift) {
  5516. kv_self.has_shift = false;
  5517. for (uint32_t i = 0; i < kv_self.size; ++i) {
  5518. kv_self.cells[i].delta = 0;
  5519. }
  5520. }
  5521. kv_self.head += n_tokens;
  5522. // Ensure kv cache head points to a valid index.
  5523. if (kv_self.head >= kv_self.size) {
  5524. kv_self.head = 0;
  5525. }
  5526. }
  5527. #ifdef GGML_PERF
  5528. // print timing information per ggml operation (for debugging purposes)
  5529. // requires GGML_PERF to be defined
  5530. ggml_graph_print(gf);
  5531. #endif
  5532. // plot the computation graph in dot format (for debugging purposes)
  5533. //if (n_past%100 == 0) {
  5534. // ggml_graph_dump_dot(gf, NULL, "llama.dot");
  5535. //}
  5536. // extract logits
  5537. // TODO: do not compute and extract logits if only embeddings are needed
  5538. // need to update the graphs to skip "result_output"
  5539. {
  5540. auto & logits_out = lctx.logits;
  5541. #ifndef NDEBUG
  5542. auto & logits_valid = lctx.logits_valid;
  5543. logits_valid.clear();
  5544. logits_valid.resize(n_tokens);
  5545. logits_out.clear();
  5546. #endif
  5547. ggml_backend_t res_backend = ggml_backend_sched_get_node_backend(lctx.sched, res);
  5548. GGML_ASSERT(res_backend != nullptr);
  5549. if (batch.logits) {
  5550. logits_out.resize(n_vocab * n_tokens);
  5551. for (uint32_t i = 0; i < n_tokens; i++) {
  5552. if (batch.logits[i] == 0) {
  5553. continue;
  5554. }
  5555. ggml_backend_tensor_get_async(res_backend, res, logits_out.data() + (n_vocab*i), (n_vocab*i)*sizeof(float), n_vocab*sizeof(float));
  5556. #ifndef NDEBUG
  5557. logits_valid[i] = true;
  5558. #endif
  5559. }
  5560. } else if (lctx.logits_all) {
  5561. logits_out.resize(n_vocab * n_tokens);
  5562. ggml_backend_tensor_get_async(res_backend, res, logits_out.data(), 0, n_vocab*n_tokens*sizeof(float));
  5563. #ifndef NDEBUG
  5564. std::fill(logits_valid.begin(), logits_valid.end(), true);
  5565. #endif
  5566. } else {
  5567. logits_out.resize(n_vocab);
  5568. ggml_backend_tensor_get_async(res_backend, res, logits_out.data(), (n_vocab*(n_tokens - 1))*sizeof(float), n_vocab*sizeof(float));
  5569. #ifndef NDEBUG
  5570. logits_valid[0] = true;
  5571. #endif
  5572. }
  5573. ggml_backend_synchronize(res_backend);
  5574. }
  5575. // extract embeddings
  5576. if (!lctx.embedding.empty()) {
  5577. auto & embedding_out = lctx.embedding;
  5578. embedding_out.resize(n_embd);
  5579. ggml_backend_t embeddings_backend = ggml_backend_sched_get_node_backend(lctx.sched, embeddings);
  5580. ggml_backend_tensor_get_async(embeddings_backend, embeddings, embedding_out.data(), (n_embd*(n_tokens - 1))*sizeof(float), n_embd*sizeof(float));
  5581. ggml_backend_synchronize(embeddings_backend);
  5582. }
  5583. // measure the performance only for the single-token evals
  5584. if (n_tokens == 1) {
  5585. lctx.t_eval_us += ggml_time_us() - t_start_us;
  5586. lctx.n_eval++;
  5587. }
  5588. else if (n_tokens > 1) {
  5589. lctx.t_p_eval_us += ggml_time_us() - t_start_us;
  5590. lctx.n_p_eval += n_tokens;
  5591. }
  5592. // get a more accurate load time, upon first eval
  5593. // TODO: fix this
  5594. if (!lctx.has_evaluated_once) {
  5595. lctx.t_load_us = ggml_time_us() - lctx.t_start_us;
  5596. lctx.has_evaluated_once = true;
  5597. }
  5598. return 0;
  5599. }
  5600. //
  5601. // tokenizer
  5602. //
  5603. static enum llama_vocab_type llama_vocab_get_type(const llama_vocab & vocab) {
  5604. return vocab.type;
  5605. }
  5606. static bool llama_is_normal_token(const llama_vocab & vocab, llama_token id) {
  5607. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_NORMAL;
  5608. }
  5609. static bool llama_is_unknown_token(const llama_vocab & vocab, llama_token id) {
  5610. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_UNKNOWN;
  5611. }
  5612. static bool llama_is_control_token(const llama_vocab & vocab, llama_token id) {
  5613. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_CONTROL;
  5614. }
  5615. static bool llama_is_byte_token(const llama_vocab & vocab, llama_token id) {
  5616. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_BYTE;
  5617. }
  5618. static bool llama_is_user_defined_token(const llama_vocab& vocab, llama_token id) {
  5619. return vocab.id_to_token[id].type == LLAMA_TOKEN_TYPE_USER_DEFINED;
  5620. }
  5621. static uint8_t llama_token_to_byte(const llama_vocab& vocab, llama_token id) {
  5622. GGML_ASSERT(llama_is_byte_token(vocab, id));
  5623. const auto& token_data = vocab.id_to_token.at(id);
  5624. switch (llama_vocab_get_type(vocab)) {
  5625. case LLAMA_VOCAB_TYPE_SPM: {
  5626. auto buf = token_data.text.substr(3, 2);
  5627. return strtol(buf.c_str(), NULL, 16);
  5628. }
  5629. case LLAMA_VOCAB_TYPE_BPE: {
  5630. GGML_ASSERT(false);
  5631. return unicode_to_bytes_bpe(token_data.text);
  5632. }
  5633. default:
  5634. GGML_ASSERT(false);
  5635. }
  5636. }
  5637. static llama_token llama_byte_to_token(const llama_vocab & vocab, uint8_t ch) {
  5638. static const char * hex = "0123456789ABCDEF";
  5639. switch (llama_vocab_get_type(vocab)) {
  5640. case LLAMA_VOCAB_TYPE_SPM: {
  5641. const char buf[7] = { '<', '0', 'x', hex[ch >> 4], hex[ch & 15], '>', 0 };
  5642. return vocab.token_to_id.at(buf);
  5643. }
  5644. case LLAMA_VOCAB_TYPE_BPE: {
  5645. return vocab.token_to_id.at(bytes_to_unicode_bpe(ch));
  5646. }
  5647. default:
  5648. GGML_ASSERT(false);
  5649. }
  5650. }
  5651. static void llama_escape_whitespace(std::string & text) {
  5652. replace_all(text, " ", "\xe2\x96\x81");
  5653. }
  5654. static void llama_unescape_whitespace(std::string & word) {
  5655. replace_all(word, "\xe2\x96\x81", " ");
  5656. }
  5657. struct llm_symbol {
  5658. using index = int;
  5659. index prev;
  5660. index next;
  5661. const char * text;
  5662. size_t n;
  5663. };
  5664. static_assert(std::is_trivially_copyable<llm_symbol>::value, "llm_symbol is not trivially copyable");
  5665. // SPM tokenizer
  5666. // original implementation:
  5667. // https://github.com/ggerganov/llama.cpp/commit/074bea2eb1f1349a0118239c4152914aecaa1be4
  5668. struct llm_bigram_spm {
  5669. struct comparator {
  5670. bool operator()(llm_bigram_spm & l, llm_bigram_spm & r) {
  5671. return (l.score < r.score) || (l.score == r.score && l.left > r.left);
  5672. }
  5673. };
  5674. using queue_storage = std::vector<llm_bigram_spm>;
  5675. using queue = std::priority_queue<llm_bigram_spm, queue_storage, comparator>;
  5676. llm_symbol::index left;
  5677. llm_symbol::index right;
  5678. float score;
  5679. size_t size;
  5680. };
  5681. struct llm_tokenizer_spm {
  5682. llm_tokenizer_spm(const llama_vocab & vocab): vocab(vocab) {}
  5683. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  5684. // split string into utf8 chars
  5685. int index = 0;
  5686. size_t offs = 0;
  5687. while (offs < text.size()) {
  5688. llm_symbol sym;
  5689. size_t len = utf8_len(text[offs]);
  5690. sym.text = text.c_str() + offs;
  5691. sym.n = std::min(len, text.size() - offs);
  5692. offs += sym.n;
  5693. sym.prev = index - 1;
  5694. sym.next = offs == text.size() ? -1 : index + 1;
  5695. index++;
  5696. symbols.emplace_back(sym);
  5697. }
  5698. // seed the work queue with all possible 2-character tokens.
  5699. for (size_t i = 1; i < symbols.size(); ++i) {
  5700. try_add_bigram(i - 1, i);
  5701. }
  5702. // keep substituting the highest frequency pairs for as long as we can.
  5703. while (!work_queue.empty()) {
  5704. auto bigram = work_queue.top();
  5705. work_queue.pop();
  5706. auto & left_sym = symbols[bigram.left];
  5707. auto & right_sym = symbols[bigram.right];
  5708. // if one of the symbols already got merged, skip it.
  5709. if (left_sym.n == 0 || right_sym.n == 0 ||
  5710. left_sym.n + right_sym.n != bigram.size) {
  5711. continue;
  5712. }
  5713. // merge the right sym into the left one
  5714. left_sym.n += right_sym.n;
  5715. right_sym.n = 0;
  5716. //LLAMA_LOG_INFO("left = '%*s' size = %zu\n", (int) left_sym.n, left_sym.text, bigram.size);
  5717. // remove the right sym from the chain
  5718. left_sym.next = right_sym.next;
  5719. if (right_sym.next >= 0) {
  5720. symbols[right_sym.next].prev = bigram.left;
  5721. }
  5722. // find more substitutions
  5723. try_add_bigram(left_sym.prev, bigram.left);
  5724. try_add_bigram(bigram.left, left_sym.next);
  5725. }
  5726. for (int i = 0; i != -1; i = symbols[i].next) {
  5727. auto & symbol = symbols[i];
  5728. resegment(symbol, output);
  5729. }
  5730. }
  5731. private:
  5732. void resegment(llm_symbol & symbol, std::vector<llama_vocab::id> & output) {
  5733. auto text = std::string(symbol.text, symbol.n);
  5734. auto token = vocab.token_to_id.find(text);
  5735. // Do we need to support is_unused?
  5736. if (token != vocab.token_to_id.end()) {
  5737. output.push_back((*token).second);
  5738. return;
  5739. }
  5740. const auto p = rev_merge.find(text);
  5741. if (p == rev_merge.end()) {
  5742. // output any symbols that did not form tokens as bytes.
  5743. for (int j = 0; j < (int)symbol.n; ++j) {
  5744. llama_vocab::id token_id = llama_byte_to_token(vocab, symbol.text[j]);
  5745. output.push_back(token_id);
  5746. }
  5747. return;
  5748. }
  5749. resegment(symbols[p->second.first], output);
  5750. resegment(symbols[p->second.second], output);
  5751. }
  5752. void try_add_bigram(int left, int right) {
  5753. if (left == -1 || right == -1) {
  5754. return;
  5755. }
  5756. const std::string text = std::string(symbols[left].text, symbols[left].n + symbols[right].n);
  5757. auto token = vocab.token_to_id.find(text);
  5758. if (token == vocab.token_to_id.end()) {
  5759. return;
  5760. }
  5761. if (static_cast<size_t>((*token).second) >= vocab.id_to_token.size()) {
  5762. return;
  5763. }
  5764. const auto & tok_data = vocab.id_to_token[(*token).second];
  5765. llm_bigram_spm bigram;
  5766. bigram.left = left;
  5767. bigram.right = right;
  5768. bigram.score = tok_data.score;
  5769. bigram.size = text.size();
  5770. work_queue.push(bigram);
  5771. // Do we need to support is_unused?
  5772. rev_merge[text] = std::make_pair(left, right);
  5773. }
  5774. const llama_vocab & vocab;
  5775. std::vector<llm_symbol> symbols;
  5776. llm_bigram_spm::queue work_queue;
  5777. std::map<std::string, std::pair<int, int>> rev_merge;
  5778. };
  5779. // BPE tokenizer
  5780. // adapted from https://github.com/cmp-nct/ggllm.cpp [MIT License]
  5781. // tried to simplify unicode stuff, so most likely does not work 100% correctly!
  5782. // TODO: there are a lot of common parts between spm and bpe tokenizers, should be refactored and reused
  5783. struct llm_bigram_bpe {
  5784. struct comparator {
  5785. bool operator()(const llm_bigram_bpe & l, const llm_bigram_bpe & r) const {
  5786. return l.rank > r.rank || (l.rank == r.rank && l.left > r.left);
  5787. }
  5788. };
  5789. using queue_storage = std::vector<llm_bigram_bpe>;
  5790. using queue = std::priority_queue<llm_bigram_bpe, queue_storage, comparator>;
  5791. llm_symbol::index left;
  5792. llm_symbol::index right;
  5793. std::string text;
  5794. int rank;
  5795. size_t size;
  5796. };
  5797. struct llm_tokenizer_bpe {
  5798. llm_tokenizer_bpe(const llama_vocab & vocab): vocab(vocab) {}
  5799. void tokenize(const std::string & text, std::vector<llama_vocab::id> & output) {
  5800. int final_prev_index = -1;
  5801. auto word_collection = bpe_gpt2_preprocess(text);
  5802. symbols_final.clear();
  5803. for (auto & word : word_collection) {
  5804. work_queue = llm_bigram_bpe::queue();
  5805. symbols.clear();
  5806. int index = 0;
  5807. size_t offset = 0;
  5808. while (offset < word.size()) {
  5809. llm_symbol sym;
  5810. size_t char_len = std::min(word.size() - offset, (size_t) ::utf8_len(word[offset]));
  5811. sym.text = word.c_str() + offset;
  5812. sym.n = char_len;
  5813. offset += sym.n;
  5814. sym.prev = index - 1;
  5815. sym.next = offset == word.size() ? -1 : index + 1;
  5816. index++;
  5817. symbols.emplace_back(sym);
  5818. }
  5819. for (size_t i = 1; i < symbols.size(); ++i) {
  5820. add_new_bigram(i - 1, i);
  5821. }
  5822. // build token(s)
  5823. while (!work_queue.empty()) {
  5824. auto bigram = work_queue.top();
  5825. work_queue.pop();
  5826. auto & left_symbol = symbols[bigram.left];
  5827. auto & right_symbol = symbols[bigram.right];
  5828. if (left_symbol.n == 0 || right_symbol.n == 0) {
  5829. continue;
  5830. }
  5831. std::string left_token = std::string(left_symbol.text, left_symbol.n);
  5832. std::string right_token = std::string(right_symbol.text, right_symbol.n);
  5833. if (left_token + right_token != bigram.text) {
  5834. continue; // Skip this bigram if it's outdated
  5835. }
  5836. // merge the right sym into the left one
  5837. left_symbol.n += right_symbol.n;
  5838. right_symbol.n = 0;
  5839. // remove the right sym from the chain
  5840. left_symbol.next = right_symbol.next;
  5841. if (right_symbol.next >= 0) {
  5842. symbols[right_symbol.next].prev = bigram.left;
  5843. }
  5844. add_new_bigram(left_symbol.prev, bigram.left); // left side of current symbol
  5845. add_new_bigram(bigram.left, left_symbol.next); // right side of current symbol
  5846. }
  5847. // add the fnished tokens to the final list keeping correct order for next and prev
  5848. for (auto & sym : symbols) {
  5849. if (sym.n > 0) {
  5850. sym.prev = final_prev_index;
  5851. sym.next = -1;
  5852. if (final_prev_index != -1) {
  5853. symbols_final[final_prev_index].next = symbols_final.size();
  5854. }
  5855. symbols_final.emplace_back(sym);
  5856. final_prev_index = symbols_final.size() - 1;
  5857. }
  5858. }
  5859. }
  5860. symbols = symbols_final;
  5861. if (!symbols.empty()) {
  5862. for (int i = 0; i != -1; i = symbols[i].next) {
  5863. auto & symbol = symbols[i];
  5864. if (symbol.n == 0) {
  5865. continue;
  5866. }
  5867. const std::string str = std::string(symbol.text, symbol.n);
  5868. const auto token = vocab.token_to_id.find(str);
  5869. if (token == vocab.token_to_id.end()) {
  5870. for (auto j = str.begin(); j != str.end(); ++j) {
  5871. std::string byte_str(1, *j);
  5872. auto token_multibyte = vocab.token_to_id.find(byte_str);
  5873. if (token_multibyte == vocab.token_to_id.end()) {
  5874. throw std::runtime_error("ERROR: byte not found in vocab");
  5875. }
  5876. output.push_back((*token_multibyte).second);
  5877. }
  5878. } else {
  5879. output.push_back((*token).second);
  5880. }
  5881. }
  5882. }
  5883. }
  5884. private:
  5885. void add_new_bigram(int left, int right) {
  5886. if (left == -1 || right == -1) {
  5887. return;
  5888. }
  5889. std::string left_token = std::string(symbols[left].text, symbols[left].n);
  5890. std::string right_token = std::string(symbols[right].text, symbols[right].n);
  5891. int rank_found = -1;
  5892. rank_found = vocab.find_bpe_rank(left_token, right_token);
  5893. if (rank_found < 0) {
  5894. return;
  5895. }
  5896. llm_bigram_bpe bigram;
  5897. bigram.left = left;
  5898. bigram.right = right;
  5899. bigram.text = left_token + right_token;
  5900. bigram.size = left_token.size() + right_token.size();
  5901. bigram.rank = rank_found;
  5902. work_queue.push(bigram);
  5903. }
  5904. std::vector<std::string> bpe_gpt2_preprocess(const std::string & text) {
  5905. std::vector<std::string> bpe_words;
  5906. std::vector<std::string> bpe_encoded_words;
  5907. std::string token = "";
  5908. // GPT2 system regex: 's|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+
  5909. bool collecting_numeric = false;
  5910. bool collecting_letter = false;
  5911. bool collecting_special = false;
  5912. bool collecting_whitespace_lookahead = false;
  5913. bool collecting = false;
  5914. std::vector<std::string> text_utf;
  5915. text_utf.reserve(text.size());
  5916. bpe_words.reserve(text.size());
  5917. bpe_encoded_words.reserve(text.size());
  5918. auto cps = codepoints_from_utf8(text);
  5919. for (size_t i = 0; i < cps.size(); ++i)
  5920. text_utf.emplace_back(codepoint_to_utf8(cps[i]));
  5921. for (int i = 0; i < (int)text_utf.size(); i++) {
  5922. const std::string & utf_char = text_utf[i];
  5923. bool split_condition = false;
  5924. int bytes_remain = text_utf.size() - i;
  5925. // forward backward lookups
  5926. const std::string & utf_char_next = (i + 1 < (int)text_utf.size()) ? text_utf[i + 1] : "";
  5927. const std::string & utf_char_next_next = (i + 2 < (int)text_utf.size()) ? text_utf[i + 2] : "";
  5928. // handling contractions
  5929. if (!split_condition && bytes_remain >= 2) {
  5930. // 's|'t|'m|'d
  5931. if (utf_char == "\'" && (utf_char_next == "s" || utf_char_next == "t" || utf_char_next == "m" || utf_char_next == "d")) {
  5932. split_condition = true;
  5933. }
  5934. if (split_condition) {
  5935. if (token.size()) {
  5936. bpe_words.emplace_back(token); // push previous content as token
  5937. }
  5938. token = utf_char + utf_char_next;
  5939. bpe_words.emplace_back(token);
  5940. token = "";
  5941. i++;
  5942. continue;
  5943. }
  5944. }
  5945. if (!split_condition && bytes_remain >= 3) {
  5946. // 're|'ve|'ll
  5947. if (utf_char == "\'" && (
  5948. (utf_char_next == "r" && utf_char_next_next == "e") ||
  5949. (utf_char_next == "v" && utf_char_next_next == "e") ||
  5950. (utf_char_next == "l" && utf_char_next_next == "l"))
  5951. ) {
  5952. split_condition = true;
  5953. }
  5954. if (split_condition) {
  5955. // current token + next token can be defined
  5956. if (token.size()) {
  5957. bpe_words.emplace_back(token); // push previous content as token
  5958. }
  5959. token = utf_char + utf_char_next + utf_char_next_next;
  5960. bpe_words.emplace_back(token); // the contraction
  5961. token = "";
  5962. i += 2;
  5963. continue;
  5964. }
  5965. }
  5966. if (!split_condition && !collecting) {
  5967. if (codepoint_type(utf_char) == CODEPOINT_TYPE_LETTER || (!token.size() && utf_char == " " && codepoint_type(utf_char_next) == CODEPOINT_TYPE_LETTER)) {
  5968. collecting_letter = true;
  5969. collecting = true;
  5970. }
  5971. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_DIGIT || (!token.size() && utf_char == " " && codepoint_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  5972. collecting_numeric = true;
  5973. collecting = true;
  5974. }
  5975. else if (
  5976. ((codepoint_type(utf_char) != CODEPOINT_TYPE_LETTER && codepoint_type(utf_char) != CODEPOINT_TYPE_DIGIT) && (codepoint_type(utf_char) != CODEPOINT_TYPE_WHITESPACE)) ||
  5977. (!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)
  5978. ) {
  5979. collecting_special = true;
  5980. collecting = true;
  5981. }
  5982. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_WHITESPACE && codepoint_type(utf_char_next) == CODEPOINT_TYPE_WHITESPACE) {
  5983. collecting_whitespace_lookahead = true;
  5984. collecting = true;
  5985. }
  5986. else if (codepoint_type(utf_char) == CODEPOINT_TYPE_WHITESPACE) {
  5987. split_condition = true;
  5988. }
  5989. }
  5990. else if (!split_condition && collecting) {
  5991. if (collecting_letter && codepoint_type(utf_char) != CODEPOINT_TYPE_LETTER) {
  5992. split_condition = true;
  5993. }
  5994. else if (collecting_numeric && codepoint_type(utf_char) != CODEPOINT_TYPE_DIGIT) {
  5995. split_condition = true;
  5996. }
  5997. 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)) {
  5998. split_condition = true;
  5999. }
  6000. else if (collecting_whitespace_lookahead && (codepoint_type(utf_char_next) == CODEPOINT_TYPE_LETTER || codepoint_type(utf_char_next) == CODEPOINT_TYPE_DIGIT)) {
  6001. split_condition = true;
  6002. }
  6003. }
  6004. if (utf_char_next == "") {
  6005. split_condition = true; // final
  6006. token += utf_char;
  6007. }
  6008. if (split_condition) {
  6009. if (token.size()) {
  6010. bpe_words.emplace_back(token);
  6011. }
  6012. token = utf_char;
  6013. collecting = false;
  6014. collecting_letter = false;
  6015. collecting_numeric = false;
  6016. collecting_special = false;
  6017. collecting_whitespace_lookahead = false;
  6018. }
  6019. else {
  6020. token += utf_char;
  6021. }
  6022. }
  6023. for (std::string & word : bpe_words) {
  6024. std::string encoded_token = "";
  6025. for (char & c : word) {
  6026. encoded_token += bytes_to_unicode_bpe(c);
  6027. }
  6028. bpe_encoded_words.emplace_back(encoded_token);
  6029. }
  6030. return bpe_encoded_words;
  6031. }
  6032. const llama_vocab & vocab;
  6033. std::vector<llm_symbol> symbols;
  6034. std::vector<llm_symbol> symbols_final;
  6035. llm_bigram_bpe::queue work_queue;
  6036. };
  6037. typedef enum FRAGMENT_BUFFER_VARIANT_TYPE{
  6038. FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN,
  6039. FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT
  6040. } FRAGMENT_BUFFER_VARIANT_TYPE;
  6041. struct fragment_buffer_variant{
  6042. fragment_buffer_variant(llama_vocab::id _token)
  6043. :
  6044. type(FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN),
  6045. token(_token),
  6046. raw_text(_dummy),
  6047. offset(0),
  6048. length(0){}
  6049. fragment_buffer_variant(const std::string & _raw_text, int64_t _offset, int64_t _length)
  6050. :
  6051. type(FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT),
  6052. token((llama_vocab::id)-1),
  6053. raw_text(_raw_text),
  6054. offset(_offset),
  6055. length(_length){
  6056. GGML_ASSERT( _offset >= 0 );
  6057. GGML_ASSERT( _length >= 1 );
  6058. GGML_ASSERT( offset + length <= raw_text.length() );
  6059. }
  6060. const FRAGMENT_BUFFER_VARIANT_TYPE type;
  6061. const llama_vocab::id token;
  6062. const std::string _dummy;
  6063. const std::string & raw_text;
  6064. const uint64_t offset;
  6065. const uint64_t length;
  6066. };
  6067. // #define PRETOKENIZERDEBUG
  6068. static void tokenizer_st_partition(const llama_vocab & vocab, std::forward_list<fragment_buffer_variant> & buffer)
  6069. {
  6070. // for each special token
  6071. for (const auto & st: vocab.special_tokens_cache) {
  6072. const auto & special_token = st.first;
  6073. const auto & special_id = st.second;
  6074. // for each text fragment
  6075. std::forward_list<fragment_buffer_variant>::iterator it = buffer.begin();
  6076. while (it != buffer.end()) {
  6077. auto & fragment = (*it);
  6078. // if a fragment is text ( not yet processed )
  6079. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT) {
  6080. auto * raw_text = &(fragment.raw_text);
  6081. auto raw_text_base_offset = fragment.offset;
  6082. auto raw_text_base_length = fragment.length;
  6083. // loop over the text
  6084. while (true) {
  6085. // find the first occurrence of a given special token in this fragment
  6086. // passing offset argument only limit the "search area" but match coordinates
  6087. // are still relative to the source full raw_text
  6088. auto match = raw_text->find(special_token, raw_text_base_offset);
  6089. // no occurrences found, stop processing this fragment for a given special token
  6090. if (match == std::string::npos) break;
  6091. // check if match is within bounds of offset <-> length
  6092. if (match + special_token.length() > raw_text_base_offset + raw_text_base_length) break;
  6093. #ifdef PRETOKENIZERDEBUG
  6094. 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());
  6095. #endif
  6096. auto source = std::distance(buffer.begin(), it);
  6097. // if match is further than base offset
  6098. // then we have some text to the left of it
  6099. if (match > raw_text_base_offset) {
  6100. // left
  6101. const int64_t left_reminder_offset = raw_text_base_offset + 0;
  6102. const int64_t left_reminder_length = match - raw_text_base_offset;
  6103. buffer.emplace_after(it, (*raw_text), left_reminder_offset, left_reminder_length);
  6104. #ifdef PRETOKENIZERDEBUG
  6105. 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());
  6106. #endif
  6107. it++;
  6108. }
  6109. // special token
  6110. buffer.emplace_after(it, special_id);
  6111. it++;
  6112. // right
  6113. if (match + special_token.length() < raw_text_base_offset + raw_text_base_length) {
  6114. const int64_t right_reminder_offset = match + special_token.length();
  6115. const int64_t right_reminder_length = raw_text_base_length - ((match - raw_text_base_offset) + special_token.length());
  6116. buffer.emplace_after(it, (*raw_text), right_reminder_offset, right_reminder_length);
  6117. #ifdef PRETOKENIZERDEBUG
  6118. 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());
  6119. #endif
  6120. it++;
  6121. if (source == 0) {
  6122. buffer.erase_after(buffer.before_begin());
  6123. } else {
  6124. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  6125. }
  6126. // repeat for the right side
  6127. raw_text_base_offset = right_reminder_offset;
  6128. raw_text_base_length = right_reminder_length;
  6129. #ifdef PRETOKENIZERDEBUG
  6130. 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());
  6131. #endif
  6132. } else {
  6133. if (source == 0) {
  6134. buffer.erase_after(buffer.before_begin());
  6135. } else {
  6136. buffer.erase_after(std::next(buffer.begin(), (source-1)));
  6137. }
  6138. break;
  6139. }
  6140. }
  6141. }
  6142. it++;
  6143. }
  6144. }
  6145. }
  6146. static std::vector<llama_vocab::id> llama_tokenize_internal(const llama_vocab & vocab, std::string raw_text, bool bos, bool special) {
  6147. std::vector<llama_vocab::id> output;
  6148. // OG tokenizer behavior:
  6149. //
  6150. // tokenizer.encode('', add_bos=True) returns [1]
  6151. // tokenizer.encode('', add_bos=False) returns []
  6152. if (bos && vocab.special_bos_id != -1) {
  6153. output.push_back(vocab.special_bos_id);
  6154. }
  6155. if (raw_text.empty()) {
  6156. return output;
  6157. }
  6158. std::forward_list<fragment_buffer_variant> fragment_buffer;
  6159. fragment_buffer.emplace_front( raw_text, 0, raw_text.length() );
  6160. if (special) tokenizer_st_partition( vocab, fragment_buffer );
  6161. switch (vocab.type) {
  6162. case LLAMA_VOCAB_TYPE_SPM:
  6163. {
  6164. for (const auto & fragment: fragment_buffer)
  6165. {
  6166. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT)
  6167. {
  6168. // without adding this leading whitespace, we do not get the same results as the original tokenizer
  6169. // TODO: It's likely possible to get rid of this string copy entirely
  6170. // by modifying llm_tokenizer_x to operate with string offsets like pre-tokenizer
  6171. // and passing 'add space prefix' as bool argument
  6172. //
  6173. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  6174. if (&fragment == &fragment_buffer.front()) {
  6175. raw_text = " " + raw_text; // prefix with space if the first token is not special
  6176. }
  6177. #ifdef PRETOKENIZERDEBUG
  6178. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  6179. #endif
  6180. llm_tokenizer_spm tokenizer(vocab);
  6181. llama_escape_whitespace(raw_text);
  6182. tokenizer.tokenize(raw_text, output);
  6183. }
  6184. else // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  6185. {
  6186. output.push_back(fragment.token);
  6187. }
  6188. }
  6189. } break;
  6190. case LLAMA_VOCAB_TYPE_BPE:
  6191. {
  6192. for (const auto & fragment: fragment_buffer)
  6193. {
  6194. if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_RAW_TEXT)
  6195. {
  6196. auto raw_text = fragment.raw_text.substr(fragment.offset, fragment.length);
  6197. #ifdef PRETOKENIZERDEBUG
  6198. LLAMA_LOG_WARN("TT: (%ld %ld %ld) '%s'\n", raw_text.length(), fragment.offset, fragment.length, raw_text.c_str());
  6199. #endif
  6200. llm_tokenizer_bpe tokenizer(vocab);
  6201. tokenizer.tokenize(raw_text, output);
  6202. }
  6203. else // if (fragment.type == FRAGMENT_BUFFER_VARIANT_TYPE_TOKEN)
  6204. {
  6205. output.push_back(fragment.token);
  6206. }
  6207. }
  6208. } break;
  6209. }
  6210. return output;
  6211. }
  6212. //
  6213. // grammar - internal
  6214. //
  6215. struct llama_partial_utf8 {
  6216. uint32_t value; // bit value so far (unshifted)
  6217. int n_remain; // num bytes remaining; -1 indicates invalid sequence
  6218. };
  6219. struct llama_grammar {
  6220. const std::vector<std::vector<llama_grammar_element>> rules;
  6221. std::vector<std::vector<const llama_grammar_element *>> stacks;
  6222. // buffer for partially generated UTF-8 sequence from accepted tokens
  6223. llama_partial_utf8 partial_utf8;
  6224. };
  6225. struct llama_grammar_candidate {
  6226. size_t index;
  6227. const uint32_t * code_points;
  6228. llama_partial_utf8 partial_utf8;
  6229. };
  6230. // Decodes a UTF-8 string which may end in an incomplete sequence. Adds a terminating 0 for use as
  6231. // pointer. If an invalid sequence is encountered, returns `llama_partial_utf8.n_remain == -1`.
  6232. static std::pair<std::vector<uint32_t>, llama_partial_utf8> decode_utf8(
  6233. const std::string & src,
  6234. llama_partial_utf8 partial_start) {
  6235. static const int lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 3, 4 };
  6236. const char * pos = src.c_str();
  6237. std::vector<uint32_t> code_points;
  6238. // common english strings have the same number of codepoints and bytes. `+ 1` for the terminating 0.
  6239. code_points.reserve(src.size() + 1);
  6240. uint32_t value = partial_start.value;
  6241. int n_remain = partial_start.n_remain;
  6242. // continue previous decode, if applicable
  6243. while (*pos != 0 && n_remain > 0) {
  6244. uint8_t next_byte = static_cast<uint8_t>(*pos);
  6245. if ((next_byte >> 6) != 2) {
  6246. // invalid sequence, abort
  6247. code_points.push_back(0);
  6248. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, -1 });
  6249. }
  6250. value = (value << 6) + (next_byte & 0x3F);
  6251. ++pos;
  6252. --n_remain;
  6253. }
  6254. if (partial_start.n_remain > 0 && n_remain == 0) {
  6255. code_points.push_back(value);
  6256. }
  6257. // decode any subsequent utf-8 sequences, which may end in an incomplete one
  6258. while (*pos != 0) {
  6259. uint8_t first_byte = static_cast<uint8_t>(*pos);
  6260. uint8_t highbits = first_byte >> 4;
  6261. n_remain = lookup[highbits] - 1;
  6262. if (n_remain < 0) {
  6263. // invalid sequence, abort
  6264. code_points.clear();
  6265. code_points.push_back(0);
  6266. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, n_remain });
  6267. }
  6268. uint8_t mask = (1 << (7 - n_remain)) - 1;
  6269. value = first_byte & mask;
  6270. ++pos;
  6271. while (*pos != 0 && n_remain > 0) {
  6272. value = (value << 6) + (static_cast<uint8_t>(*pos) & 0x3F);
  6273. ++pos;
  6274. --n_remain;
  6275. }
  6276. if (n_remain == 0) {
  6277. code_points.push_back(value);
  6278. }
  6279. }
  6280. code_points.push_back(0);
  6281. return std::make_pair(std::move(code_points), llama_partial_utf8{ value, n_remain });
  6282. }
  6283. // returns true iff pos points to the end of one of the definitions of a rule
  6284. static bool llama_grammar_is_end_of_sequence(const llama_grammar_element * pos) {
  6285. switch (pos->type) {
  6286. case LLAMA_GRETYPE_END: return true; // NOLINT
  6287. case LLAMA_GRETYPE_ALT: return true; // NOLINT
  6288. default: return false;
  6289. }
  6290. }
  6291. // returns true iff chr satisfies the char range at pos (regular or inverse range)
  6292. // asserts that pos is pointing to a char range element
  6293. static std::pair<bool, const llama_grammar_element *> llama_grammar_match_char(
  6294. const llama_grammar_element * pos,
  6295. const uint32_t chr) {
  6296. bool found = false;
  6297. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  6298. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT); // NOLINT
  6299. do {
  6300. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  6301. // inclusive range, e.g. [a-z]
  6302. found = found || (pos->value <= chr && chr <= pos[1].value);
  6303. pos += 2;
  6304. } else {
  6305. // exact char match, e.g. [a] or "a"
  6306. found = found || pos->value == chr;
  6307. pos += 1;
  6308. }
  6309. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  6310. return std::make_pair(found == is_positive_char, pos);
  6311. }
  6312. // returns true iff some continuation of the given partial UTF-8 sequence could satisfy the char
  6313. // range at pos (regular or inverse range)
  6314. // asserts that pos is pointing to a char range element
  6315. static bool llama_grammar_match_partial_char(
  6316. const llama_grammar_element * pos,
  6317. const llama_partial_utf8 partial_utf8) {
  6318. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR;
  6319. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT);
  6320. uint32_t partial_value = partial_utf8.value;
  6321. int n_remain = partial_utf8.n_remain;
  6322. // invalid sequence or 7-bit char split across 2 bytes (overlong)
  6323. if (n_remain < 0 || (n_remain == 1 && partial_value < 2)) {
  6324. return false;
  6325. }
  6326. // range of possible code points this partial UTF-8 sequence could complete to
  6327. uint32_t low = partial_value << (n_remain * 6);
  6328. uint32_t high = low | ((1 << (n_remain * 6)) - 1);
  6329. if (low == 0) {
  6330. if (n_remain == 2) {
  6331. low = 1 << 11;
  6332. } else if (n_remain == 3) {
  6333. low = 1 << 16;
  6334. }
  6335. }
  6336. do {
  6337. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  6338. // inclusive range, e.g. [a-z]
  6339. if (pos->value <= high && low <= pos[1].value) {
  6340. return is_positive_char;
  6341. }
  6342. pos += 2;
  6343. } else {
  6344. // exact char match, e.g. [a] or "a"
  6345. if (low <= pos->value && pos->value <= high) {
  6346. return is_positive_char;
  6347. }
  6348. pos += 1;
  6349. }
  6350. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  6351. return !is_positive_char;
  6352. }
  6353. // transforms a grammar pushdown stack into N possible stacks, all ending
  6354. // at a character range (terminal element)
  6355. static void llama_grammar_advance_stack(
  6356. const std::vector<std::vector<llama_grammar_element>> & rules,
  6357. const std::vector<const llama_grammar_element *> & stack,
  6358. std::vector<std::vector<const llama_grammar_element *>> & new_stacks) {
  6359. if (stack.empty()) {
  6360. new_stacks.emplace_back(stack);
  6361. return;
  6362. }
  6363. const llama_grammar_element * pos = stack.back();
  6364. switch (pos->type) {
  6365. case LLAMA_GRETYPE_RULE_REF: {
  6366. const size_t rule_id = static_cast<size_t>(pos->value);
  6367. const llama_grammar_element * subpos = rules[rule_id].data();
  6368. do {
  6369. // init new stack without the top (pos)
  6370. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  6371. if (!llama_grammar_is_end_of_sequence(pos + 1)) {
  6372. // if this rule ref is followed by another element, add that to stack
  6373. new_stack.push_back(pos + 1);
  6374. }
  6375. if (!llama_grammar_is_end_of_sequence(subpos)) {
  6376. // if alternate is nonempty, add to stack
  6377. new_stack.push_back(subpos);
  6378. }
  6379. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  6380. while (!llama_grammar_is_end_of_sequence(subpos)) {
  6381. // scan to end of alternate def
  6382. subpos++;
  6383. }
  6384. if (subpos->type == LLAMA_GRETYPE_ALT) {
  6385. // there's another alternate def of this rule to process
  6386. subpos++;
  6387. } else {
  6388. break;
  6389. }
  6390. } while (true);
  6391. break;
  6392. }
  6393. case LLAMA_GRETYPE_CHAR:
  6394. case LLAMA_GRETYPE_CHAR_NOT:
  6395. new_stacks.emplace_back(stack);
  6396. break;
  6397. default:
  6398. // end of alternate (LLAMA_GRETYPE_END, LLAMA_GRETYPE_ALT) or middle of char range
  6399. // (LLAMA_GRETYPE_CHAR_ALT, LLAMA_GRETYPE_CHAR_RNG_UPPER); stack should never be left on
  6400. // those
  6401. GGML_ASSERT(false);
  6402. }
  6403. }
  6404. // takes a set of possible pushdown stacks on a grammar, which are required to
  6405. // be positioned at a character range (see `llama_grammar_advance_stack`), and
  6406. // produces the N possible stacks if the given char is accepted at those
  6407. // positions
  6408. static std::vector<std::vector<const llama_grammar_element *>> llama_grammar_accept(
  6409. const std::vector<std::vector<llama_grammar_element>> & rules,
  6410. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  6411. const uint32_t chr) {
  6412. std::vector<std::vector<const llama_grammar_element *>> new_stacks;
  6413. for (const auto & stack : stacks) {
  6414. if (stack.empty()) {
  6415. continue;
  6416. }
  6417. auto match = llama_grammar_match_char(stack.back(), chr);
  6418. if (match.first) {
  6419. const llama_grammar_element * pos = match.second;
  6420. // update top of stack to next element, if any
  6421. std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
  6422. if (!llama_grammar_is_end_of_sequence(pos)) {
  6423. new_stack.push_back(pos);
  6424. }
  6425. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  6426. }
  6427. }
  6428. return new_stacks;
  6429. }
  6430. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  6431. const std::vector<std::vector<llama_grammar_element>> & rules,
  6432. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  6433. const std::vector<llama_grammar_candidate> & candidates);
  6434. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates_for_stack(
  6435. const std::vector<std::vector<llama_grammar_element>> & rules,
  6436. const std::vector<const llama_grammar_element *> & stack,
  6437. const std::vector<llama_grammar_candidate> & candidates) {
  6438. std::vector<llama_grammar_candidate> rejects;
  6439. if (stack.empty()) {
  6440. for (const auto & tok : candidates) {
  6441. if (*tok.code_points != 0 || tok.partial_utf8.n_remain != 0) {
  6442. rejects.push_back(tok);
  6443. }
  6444. }
  6445. return rejects;
  6446. }
  6447. const llama_grammar_element * stack_pos = stack.back();
  6448. std::vector<llama_grammar_candidate> next_candidates;
  6449. for (const auto & tok : candidates) {
  6450. if (*tok.code_points == 0) {
  6451. // reached end of full codepoints in token, reject iff it ended in a partial sequence
  6452. // that cannot satisfy this position in grammar
  6453. if (tok.partial_utf8.n_remain != 0 &&
  6454. !llama_grammar_match_partial_char(stack_pos, tok.partial_utf8)) {
  6455. rejects.push_back(tok);
  6456. }
  6457. } else if (llama_grammar_match_char(stack_pos, *tok.code_points).first) {
  6458. next_candidates.push_back({ tok.index, tok.code_points + 1, tok.partial_utf8 });
  6459. } else {
  6460. rejects.push_back(tok);
  6461. }
  6462. }
  6463. const auto * stack_pos_after = llama_grammar_match_char(stack_pos, 0).second;
  6464. // update top of stack to next element, if any
  6465. std::vector<const llama_grammar_element *> stack_after(stack.begin(), stack.end() - 1);
  6466. if (!llama_grammar_is_end_of_sequence(stack_pos_after)) {
  6467. stack_after.push_back(stack_pos_after);
  6468. }
  6469. std::vector<std::vector<const llama_grammar_element *>> next_stacks;
  6470. llama_grammar_advance_stack(rules, stack_after, next_stacks);
  6471. auto next_rejects = llama_grammar_reject_candidates(rules, next_stacks, next_candidates);
  6472. for (const auto & tok : next_rejects) {
  6473. rejects.push_back({ tok.index, tok.code_points - 1, tok.partial_utf8 });
  6474. }
  6475. return rejects;
  6476. }
  6477. static std::vector<llama_grammar_candidate> llama_grammar_reject_candidates(
  6478. const std::vector<std::vector<llama_grammar_element>> & rules,
  6479. const std::vector<std::vector<const llama_grammar_element *>> & stacks,
  6480. const std::vector<llama_grammar_candidate> & candidates) {
  6481. GGML_ASSERT(!stacks.empty()); // REVIEW
  6482. if (candidates.empty()) {
  6483. return std::vector<llama_grammar_candidate>();
  6484. }
  6485. auto rejects = llama_grammar_reject_candidates_for_stack(rules, stacks.front(), candidates);
  6486. for (size_t i = 1, size = stacks.size(); i < size; ++i) {
  6487. rejects = llama_grammar_reject_candidates_for_stack(rules, stacks[i], rejects);
  6488. }
  6489. return rejects;
  6490. }
  6491. //
  6492. // grammar - external
  6493. //
  6494. struct llama_grammar * llama_grammar_init(
  6495. const llama_grammar_element ** rules,
  6496. size_t n_rules,
  6497. size_t start_rule_index) {
  6498. const llama_grammar_element * pos;
  6499. // copy rule definitions into vectors
  6500. std::vector<std::vector<llama_grammar_element>> vec_rules(n_rules);
  6501. for (size_t i = 0; i < n_rules; i++) {
  6502. for (pos = rules[i]; pos->type != LLAMA_GRETYPE_END; pos++) {
  6503. vec_rules[i].push_back(*pos);
  6504. }
  6505. vec_rules[i].push_back({LLAMA_GRETYPE_END, 0});
  6506. }
  6507. // loop over alternates of start rule to build initial stacks
  6508. std::vector<std::vector<const llama_grammar_element *>> stacks;
  6509. pos = rules[start_rule_index];
  6510. do {
  6511. std::vector<const llama_grammar_element *> stack;
  6512. if (!llama_grammar_is_end_of_sequence(pos)) {
  6513. // if alternate is nonempty, add to stack
  6514. stack.push_back(pos);
  6515. }
  6516. llama_grammar_advance_stack(vec_rules, stack, stacks);
  6517. while (!llama_grammar_is_end_of_sequence(pos)) {
  6518. // scan to end of alternate def
  6519. pos++;
  6520. }
  6521. if (pos->type == LLAMA_GRETYPE_ALT) {
  6522. // there's another alternate def of this rule to process
  6523. pos++;
  6524. } else {
  6525. break;
  6526. }
  6527. } while (true);
  6528. return new llama_grammar{ std::move(vec_rules), std::move(stacks), {} };
  6529. }
  6530. void llama_grammar_free(struct llama_grammar * grammar) {
  6531. delete grammar;
  6532. }
  6533. struct llama_grammar * llama_grammar_copy(const struct llama_grammar * grammar) {
  6534. llama_grammar * result = new llama_grammar{ grammar->rules, grammar->stacks, grammar->partial_utf8 };
  6535. // redirect elements in stacks to point to new rules
  6536. for (size_t is = 0; is < result->stacks.size(); is++) {
  6537. for (size_t ie = 0; ie < result->stacks[is].size(); ie++) {
  6538. for (size_t ir0 = 0; ir0 < grammar->rules.size(); ir0++) {
  6539. for (size_t ir1 = 0; ir1 < grammar->rules[ir0].size(); ir1++) {
  6540. if (grammar->stacks[is][ie] == &grammar->rules[ir0][ir1]) {
  6541. result->stacks[is][ie] = &result->rules[ir0][ir1];
  6542. }
  6543. }
  6544. }
  6545. }
  6546. }
  6547. return result;
  6548. }
  6549. //
  6550. // sampling
  6551. //
  6552. void llama_set_rng_seed(struct llama_context * ctx, uint32_t seed) {
  6553. if (seed == LLAMA_DEFAULT_SEED) {
  6554. seed = time(NULL);
  6555. }
  6556. ctx->rng.seed(seed);
  6557. }
  6558. void llama_sample_softmax(struct llama_context * ctx, llama_token_data_array * candidates) {
  6559. GGML_ASSERT(candidates->size > 0);
  6560. const int64_t t_start_sample_us = ggml_time_us();
  6561. // Sort the logits in descending order
  6562. if (!candidates->sorted) {
  6563. std::sort(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  6564. return a.logit > b.logit;
  6565. });
  6566. candidates->sorted = true;
  6567. }
  6568. float max_l = candidates->data[0].logit;
  6569. float cum_sum = 0.0f;
  6570. for (size_t i = 0; i < candidates->size; ++i) {
  6571. float p = expf(candidates->data[i].logit - max_l);
  6572. candidates->data[i].p = p;
  6573. cum_sum += p;
  6574. }
  6575. for (size_t i = 0; i < candidates->size; ++i) {
  6576. candidates->data[i].p /= cum_sum;
  6577. }
  6578. if (ctx) {
  6579. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6580. }
  6581. }
  6582. void llama_sample_top_k(struct llama_context * ctx, llama_token_data_array * candidates, int32_t k, size_t min_keep) {
  6583. const int64_t t_start_sample_us = ggml_time_us();
  6584. k = std::max(k, (int) min_keep);
  6585. k = std::min(k, (int) candidates->size);
  6586. // Sort scores in descending order
  6587. if (!candidates->sorted) {
  6588. auto comp = [](const llama_token_data & a, const llama_token_data & b) {
  6589. return a.logit > b.logit;
  6590. };
  6591. if (k == (int) candidates->size) {
  6592. std::sort(candidates->data, candidates->data + candidates->size, comp);
  6593. } else {
  6594. std::partial_sort(candidates->data, candidates->data + k, candidates->data + candidates->size, comp);
  6595. }
  6596. candidates->sorted = true;
  6597. }
  6598. candidates->size = k;
  6599. if (ctx) {
  6600. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6601. }
  6602. }
  6603. void llama_sample_top_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  6604. if (p >= 1.0f) {
  6605. return;
  6606. }
  6607. llama_sample_softmax(ctx, candidates);
  6608. const int64_t t_start_sample_us = ggml_time_us();
  6609. // Compute the cumulative probabilities
  6610. float cum_sum = 0.0f;
  6611. size_t last_idx = candidates->size;
  6612. for (size_t i = 0; i < candidates->size; ++i) {
  6613. cum_sum += candidates->data[i].p;
  6614. // Check if the running sum is at least p or if we have kept at least min_keep tokens
  6615. // we set the last index to i+1 to indicate that the current iterate should be included in the set
  6616. if (cum_sum >= p && i + 1 >= min_keep) {
  6617. last_idx = i + 1;
  6618. break;
  6619. }
  6620. }
  6621. // Resize the output vector to keep only the top-p tokens
  6622. candidates->size = last_idx;
  6623. if (ctx) {
  6624. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6625. }
  6626. }
  6627. void llama_sample_min_p(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  6628. if (p <= 0.0f || !candidates->size) {
  6629. return;
  6630. }
  6631. llama_sample_softmax(ctx, candidates);
  6632. const int64_t t_start_sample_us = ggml_time_us();
  6633. float scale = candidates->data[0].p; // scale by max prob
  6634. size_t i = 1; // first token always matches
  6635. for (; i < candidates->size; ++i) {
  6636. if (candidates->data[i].p < p * scale && i >= min_keep) {
  6637. break; // prob too small
  6638. }
  6639. }
  6640. // Resize the output vector to keep only the matching tokens
  6641. candidates->size = i;
  6642. if (ctx) {
  6643. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6644. }
  6645. }
  6646. void llama_sample_tail_free(struct llama_context * ctx, llama_token_data_array * candidates, float z, size_t min_keep) {
  6647. if (z >= 1.0f || candidates->size <= 2) {
  6648. return;
  6649. }
  6650. llama_sample_softmax(nullptr, candidates);
  6651. const int64_t t_start_sample_us = ggml_time_us();
  6652. // Compute the first and second derivatives
  6653. std::vector<float> first_derivatives(candidates->size - 1);
  6654. std::vector<float> second_derivatives(candidates->size - 2);
  6655. for (size_t i = 0; i < first_derivatives.size(); ++i) {
  6656. first_derivatives[i] = candidates->data[i].p - candidates->data[i + 1].p;
  6657. }
  6658. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  6659. second_derivatives[i] = first_derivatives[i] - first_derivatives[i + 1];
  6660. }
  6661. // Calculate absolute value of second derivatives
  6662. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  6663. second_derivatives[i] = std::abs(second_derivatives[i]);
  6664. }
  6665. // Normalize the second derivatives
  6666. {
  6667. const float second_derivatives_sum = std::accumulate(second_derivatives.begin(), second_derivatives.end(), 0.0f);
  6668. if (second_derivatives_sum > 1e-6f) {
  6669. for (float & value : second_derivatives) {
  6670. value /= second_derivatives_sum;
  6671. }
  6672. } else {
  6673. for (float & value : second_derivatives) {
  6674. value = 1.0f / second_derivatives.size();
  6675. }
  6676. }
  6677. }
  6678. float cum_sum = 0.0f;
  6679. size_t last_idx = candidates->size;
  6680. for (size_t i = 0; i < second_derivatives.size(); ++i) {
  6681. cum_sum += second_derivatives[i];
  6682. // Check if the running sum is greater than z or if we have kept at least min_keep tokens
  6683. if (cum_sum > z && i >= min_keep) {
  6684. last_idx = i;
  6685. break;
  6686. }
  6687. }
  6688. // Resize the output vector to keep only the tokens above the tail location
  6689. candidates->size = last_idx;
  6690. if (ctx) {
  6691. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6692. }
  6693. }
  6694. void llama_sample_typical(struct llama_context * ctx, llama_token_data_array * candidates, float p, size_t min_keep) {
  6695. // Reference implementation:
  6696. // https://github.com/huggingface/transformers/compare/main...cimeister:typical-sampling:typical-pr
  6697. if (p >= 1.0f) {
  6698. return;
  6699. }
  6700. // Compute the softmax of logits and calculate entropy
  6701. llama_sample_softmax(nullptr, candidates);
  6702. const int64_t t_start_sample_us = ggml_time_us();
  6703. float entropy = 0.0f;
  6704. for (size_t i = 0; i < candidates->size; ++i) {
  6705. entropy += -candidates->data[i].p * logf(candidates->data[i].p);
  6706. }
  6707. // Compute the absolute difference between negative log probability and entropy for each candidate
  6708. std::vector<float> shifted_scores;
  6709. for (size_t i = 0; i < candidates->size; ++i) {
  6710. float shifted_score = fabsf(-logf(candidates->data[i].p) - entropy);
  6711. shifted_scores.push_back(shifted_score);
  6712. }
  6713. // Sort tokens based on the shifted_scores and their corresponding indices
  6714. std::vector<size_t> indices(candidates->size);
  6715. std::iota(indices.begin(), indices.end(), 0);
  6716. std::sort(indices.begin(), indices.end(), [&](size_t a, size_t b) {
  6717. return shifted_scores[a] < shifted_scores[b];
  6718. });
  6719. // Compute the cumulative probabilities
  6720. float cum_sum = 0.0f;
  6721. size_t last_idx = indices.size();
  6722. for (size_t i = 0; i < indices.size(); ++i) {
  6723. size_t idx = indices[i];
  6724. cum_sum += candidates->data[idx].p;
  6725. // Check if the running sum is greater than typical or if we have kept at least min_keep tokens
  6726. if (cum_sum > p && i >= min_keep - 1) {
  6727. last_idx = i + 1;
  6728. break;
  6729. }
  6730. }
  6731. // Resize the output vector to keep only the locally typical tokens
  6732. std::vector<llama_token_data> new_candidates;
  6733. for (size_t i = 0; i < last_idx; ++i) {
  6734. size_t idx = indices[i];
  6735. new_candidates.push_back(candidates->data[idx]);
  6736. }
  6737. // Replace the data in candidates with the new_candidates data
  6738. std::copy(new_candidates.begin(), new_candidates.end(), candidates->data);
  6739. candidates->size = new_candidates.size();
  6740. candidates->sorted = false;
  6741. if (ctx) {
  6742. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6743. }
  6744. }
  6745. void llama_sample_temp(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  6746. const int64_t t_start_sample_us = ggml_time_us();
  6747. for (size_t i = 0; i < candidates_p->size; ++i) {
  6748. candidates_p->data[i].logit /= temp;
  6749. }
  6750. if (ctx) {
  6751. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6752. }
  6753. }
  6754. void llama_sample_temperature(struct llama_context * ctx, llama_token_data_array * candidates_p, float temp) {
  6755. llama_sample_temp(ctx, candidates_p, temp);
  6756. }
  6757. void llama_sample_repetition_penalties(
  6758. struct llama_context * ctx,
  6759. llama_token_data_array * candidates,
  6760. const llama_token * last_tokens,
  6761. size_t penalty_last_n,
  6762. float penalty_repeat,
  6763. float penalty_freq,
  6764. float penalty_present) {
  6765. if (penalty_last_n == 0 || (penalty_repeat == 1.0f && penalty_freq == 0.0f && penalty_present == 0.0f)) {
  6766. return;
  6767. }
  6768. const int64_t t_start_sample_us = ggml_time_us();
  6769. // Create a frequency map to count occurrences of each token in last_tokens
  6770. std::unordered_map<llama_token, int> token_count;
  6771. for (size_t i = 0; i < penalty_last_n; ++i) {
  6772. token_count[last_tokens[i]]++;
  6773. }
  6774. // Apply frequency and presence penalties to the candidates
  6775. for (size_t i = 0; i < candidates->size; ++i) {
  6776. const auto token_iter = token_count.find(candidates->data[i].id);
  6777. if (token_iter == token_count.end()) {
  6778. continue;
  6779. }
  6780. const int count = token_iter->second;
  6781. // 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.
  6782. // This is common fix for this problem, which is to multiply by the penalty instead of dividing.
  6783. if (candidates->data[i].logit <= 0) {
  6784. candidates->data[i].logit *= penalty_repeat;
  6785. } else {
  6786. candidates->data[i].logit /= penalty_repeat;
  6787. }
  6788. candidates->data[i].logit -= float(count) * penalty_freq + float(count > 0) * penalty_present;
  6789. }
  6790. candidates->sorted = false;
  6791. if (ctx) {
  6792. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6793. }
  6794. }
  6795. void llama_sample_grammar(struct llama_context * ctx, llama_token_data_array * candidates, const struct llama_grammar * grammar) {
  6796. GGML_ASSERT(ctx);
  6797. const int64_t t_start_sample_us = ggml_time_us();
  6798. bool allow_eos = false;
  6799. for (const auto & stack : grammar->stacks) {
  6800. if (stack.empty()) {
  6801. allow_eos = true;
  6802. break;
  6803. }
  6804. }
  6805. const llama_token eos = llama_token_eos(&ctx->model);
  6806. std::vector<std::pair<std::vector<uint32_t>, llama_partial_utf8>> candidates_decoded;
  6807. candidates_decoded.reserve(candidates->size);
  6808. std::vector<llama_grammar_candidate> candidates_grammar;
  6809. candidates_grammar.reserve(candidates->size);
  6810. for (size_t i = 0; i < candidates->size; ++i) {
  6811. const llama_token id = candidates->data[i].id;
  6812. const std::string piece = llama_token_to_piece(ctx, id);
  6813. if (id == eos) {
  6814. if (!allow_eos) {
  6815. candidates->data[i].logit = -INFINITY;
  6816. }
  6817. } else if (piece.empty() || piece[0] == 0) {
  6818. candidates->data[i].logit = -INFINITY;
  6819. } else {
  6820. candidates_decoded.push_back(decode_utf8(piece, grammar->partial_utf8));
  6821. candidates_grammar.push_back({ i, candidates_decoded.back().first.data(), candidates_decoded.back().second });
  6822. }
  6823. }
  6824. const auto rejects = llama_grammar_reject_candidates(grammar->rules, grammar->stacks, candidates_grammar);
  6825. for (const auto & reject : rejects) {
  6826. candidates->data[reject.index].logit = -INFINITY;
  6827. }
  6828. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6829. }
  6830. static void llama_log_softmax(float * array, size_t size) {
  6831. float max_l = *std::max_element(array, array + size);
  6832. float sum = 0.f;
  6833. for (size_t i = 0; i < size; ++i) {
  6834. float p = expf(array[i] - max_l);
  6835. sum += p;
  6836. array[i] = p;
  6837. }
  6838. for (size_t i = 0; i < size; ++i) {
  6839. array[i] = logf(array[i] / sum);
  6840. }
  6841. }
  6842. void llama_sample_apply_guidance(
  6843. struct llama_context * ctx,
  6844. float * logits,
  6845. float * logits_guidance,
  6846. float scale) {
  6847. GGML_ASSERT(ctx);
  6848. const auto t_start_sample_us = ggml_time_us();
  6849. const auto n_vocab = llama_n_vocab(llama_get_model(ctx));
  6850. llama_log_softmax(logits, n_vocab);
  6851. llama_log_softmax(logits_guidance, n_vocab);
  6852. for (int i = 0; i < n_vocab; ++i) {
  6853. auto & l = logits[i];
  6854. const auto & g = logits_guidance[i];
  6855. l = scale * (l - g) + g;
  6856. }
  6857. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6858. }
  6859. void llama_sample_classifier_free_guidance(
  6860. struct llama_context * ctx,
  6861. llama_token_data_array * candidates,
  6862. struct llama_context * guidance_ctx,
  6863. float scale) {
  6864. GGML_ASSERT(ctx);
  6865. int64_t t_start_sample_us;
  6866. t_start_sample_us = ggml_time_us();
  6867. const size_t n_vocab = llama_n_vocab(llama_get_model(ctx));
  6868. GGML_ASSERT(n_vocab == candidates->size);
  6869. GGML_ASSERT(!candidates->sorted);
  6870. std::vector<float> logits_base(n_vocab);
  6871. for (size_t i = 0; i < n_vocab; ++i) {
  6872. logits_base[i] = candidates->data[i].logit;
  6873. }
  6874. float * logits_guidance = llama_get_logits(guidance_ctx);
  6875. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6876. llama_sample_apply_guidance(ctx, logits_base.data(), logits_guidance, scale);
  6877. t_start_sample_us = ggml_time_us();
  6878. for (size_t i = 0; i < n_vocab; ++i) {
  6879. candidates->data[i].logit = logits_base[i];
  6880. }
  6881. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6882. }
  6883. llama_token llama_sample_token_mirostat(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, int32_t m, float * mu) {
  6884. GGML_ASSERT(ctx);
  6885. auto N = float(llama_n_vocab(llama_get_model(ctx)));
  6886. int64_t t_start_sample_us;
  6887. t_start_sample_us = ggml_time_us();
  6888. llama_sample_softmax(nullptr, candidates);
  6889. // Estimate s_hat using the most probable m tokens
  6890. float s_hat = 0.0;
  6891. float sum_ti_bi = 0.0;
  6892. float sum_ti_sq = 0.0;
  6893. for (size_t i = 0; i < size_t(m - 1) && i < candidates->size - 1; ++i) {
  6894. float t_i = logf(float(i + 2) / float(i + 1));
  6895. float b_i = logf(candidates->data[i].p / candidates->data[i + 1].p);
  6896. sum_ti_bi += t_i * b_i;
  6897. sum_ti_sq += t_i * t_i;
  6898. }
  6899. s_hat = sum_ti_bi / sum_ti_sq;
  6900. // Compute k from the estimated s_hat and target surprise value
  6901. float epsilon_hat = s_hat - 1;
  6902. float k = powf((epsilon_hat * powf(2, *mu)) / (1 - powf(N, -epsilon_hat)), 1 / s_hat);
  6903. // Sample the next word X using top-k sampling
  6904. llama_sample_top_k(nullptr, candidates, int(k), 1);
  6905. if (ctx) {
  6906. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6907. }
  6908. llama_token X = llama_sample_token(ctx, candidates);
  6909. t_start_sample_us = ggml_time_us();
  6910. // Compute error as the difference between observed surprise and target surprise value
  6911. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  6912. return candidate.id == X;
  6913. }));
  6914. float observed_surprise = -log2f(candidates->data[X_idx].p);
  6915. float e = observed_surprise - tau;
  6916. // Update mu using the learning rate and error
  6917. *mu = *mu - eta * e;
  6918. if (ctx) {
  6919. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6920. }
  6921. return X;
  6922. }
  6923. llama_token llama_sample_token_mirostat_v2(struct llama_context * ctx, llama_token_data_array * candidates, float tau, float eta, float * mu) {
  6924. int64_t t_start_sample_us;
  6925. t_start_sample_us = ggml_time_us();
  6926. llama_sample_softmax(ctx, candidates);
  6927. // Truncate the words with surprise values greater than mu
  6928. candidates->size = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  6929. return -log2f(candidate.p) > *mu;
  6930. }));
  6931. if (candidates->size == 0) {
  6932. candidates->size = 1;
  6933. }
  6934. if (ctx) {
  6935. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6936. }
  6937. // Normalize the probabilities of the remaining words
  6938. llama_sample_softmax(ctx, candidates);
  6939. // Sample the next word X from the remaining words
  6940. llama_token X = llama_sample_token(ctx, candidates);
  6941. t_start_sample_us = ggml_time_us();
  6942. // Compute error as the difference between observed surprise and target surprise value
  6943. size_t X_idx = std::distance(candidates->data, std::find_if(candidates->data, candidates->data + candidates->size, [&](const llama_token_data & candidate) {
  6944. return candidate.id == X;
  6945. }));
  6946. float observed_surprise = -log2f(candidates->data[X_idx].p);
  6947. float e = observed_surprise - tau;
  6948. // Update mu using the learning rate and error
  6949. *mu = *mu - eta * e;
  6950. if (ctx) {
  6951. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6952. }
  6953. return X;
  6954. }
  6955. llama_token llama_sample_token_greedy(struct llama_context * ctx, llama_token_data_array * candidates) {
  6956. const int64_t t_start_sample_us = ggml_time_us();
  6957. // Find max element
  6958. auto * max_iter = std::max_element(candidates->data, candidates->data + candidates->size, [](const llama_token_data & a, const llama_token_data & b) {
  6959. return a.logit < b.logit;
  6960. });
  6961. llama_token result = max_iter->id;
  6962. if (ctx) {
  6963. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6964. ctx->n_sample++;
  6965. }
  6966. return result;
  6967. }
  6968. llama_token llama_sample_token(struct llama_context * ctx, llama_token_data_array * candidates) {
  6969. GGML_ASSERT(ctx);
  6970. const int64_t t_start_sample_us = ggml_time_us();
  6971. llama_sample_softmax(nullptr, candidates);
  6972. std::vector<float> probs;
  6973. probs.reserve(candidates->size);
  6974. for (size_t i = 0; i < candidates->size; ++i) {
  6975. probs.push_back(candidates->data[i].p);
  6976. }
  6977. std::discrete_distribution<> dist(probs.begin(), probs.end());
  6978. auto & rng = ctx->rng;
  6979. int idx = dist(rng);
  6980. llama_token result = candidates->data[idx].id;
  6981. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  6982. ctx->n_sample++;
  6983. return result;
  6984. }
  6985. void llama_grammar_accept_token(struct llama_context * ctx, struct llama_grammar * grammar, llama_token token) {
  6986. const int64_t t_start_sample_us = ggml_time_us();
  6987. if (token == llama_token_eos(&ctx->model)) {
  6988. for (const auto & stack : grammar->stacks) {
  6989. if (stack.empty()) {
  6990. return;
  6991. }
  6992. }
  6993. GGML_ASSERT(false);
  6994. }
  6995. const std::string piece = llama_token_to_piece(ctx, token);
  6996. // Note terminating 0 in decoded string
  6997. const auto decoded = decode_utf8(piece, grammar->partial_utf8);
  6998. const auto & code_points = decoded.first;
  6999. for (auto it = code_points.begin(), end = code_points.end() - 1; it != end; ++it) {
  7000. grammar->stacks = llama_grammar_accept(grammar->rules, grammar->stacks, *it);
  7001. }
  7002. grammar->partial_utf8 = decoded.second;
  7003. GGML_ASSERT(!grammar->stacks.empty());
  7004. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7005. }
  7006. //
  7007. // Beam search
  7008. //
  7009. struct llama_beam {
  7010. std::vector<llama_token> tokens;
  7011. float p; // Cumulative beam probability (renormalized relative to all beams)
  7012. bool eob; // Initialize end-of-beam to false. Callback sets this to true.
  7013. // Sort beams by probability. In case of ties, prefer beams at eob.
  7014. bool operator<(const llama_beam & rhs) const {
  7015. return std::make_pair(p, eob) < std::make_pair(rhs.p, rhs.eob);
  7016. }
  7017. // Shift off first n tokens and discard them.
  7018. void shift_tokens(const size_t n) {
  7019. if (n) {
  7020. std::copy(tokens.begin() + n, tokens.end(), tokens.begin());
  7021. tokens.resize(tokens.size() - n);
  7022. }
  7023. }
  7024. llama_beam_view view() const { return {tokens.data(), tokens.size(), p, eob}; }
  7025. };
  7026. // A struct for calculating logit-related info.
  7027. struct llama_logit_info {
  7028. const float * const logits;
  7029. const int n_vocab;
  7030. const float max_l;
  7031. const float normalizer;
  7032. struct sum_exp {
  7033. float max_l;
  7034. float operator()(float sum, float l) const { return sum + std::exp(l - max_l); }
  7035. };
  7036. llama_logit_info(llama_context * ctx)
  7037. : logits(llama_get_logits(ctx))
  7038. , n_vocab(llama_n_vocab(llama_get_model(ctx)))
  7039. , max_l(*std::max_element(logits, logits + n_vocab))
  7040. , normalizer(1.0f / std::accumulate(logits, logits + n_vocab, 0.0f, sum_exp{max_l}))
  7041. { }
  7042. llama_token_data get_token_data(const llama_token token_id) const {
  7043. constexpr auto p = std::numeric_limits<float>::quiet_NaN(); // never used
  7044. return {token_id, logits[token_id], p};
  7045. }
  7046. // Return top k token_data by logit.
  7047. std::vector<llama_token_data> top_k(size_t k) {
  7048. std::vector<llama_token_data> min_heap; // min-heap by logit
  7049. const llama_token k_min = std::min(static_cast<llama_token>(k), n_vocab);
  7050. min_heap.reserve(k_min);
  7051. for (llama_token token_id = 0 ; token_id < k_min ; ++token_id) {
  7052. min_heap.push_back(get_token_data(token_id));
  7053. }
  7054. auto comp = [](const llama_token_data & a, const llama_token_data & b) { return a.logit > b.logit; };
  7055. std::make_heap(min_heap.begin(), min_heap.end(), comp);
  7056. for (llama_token token_id = k_min ; token_id < n_vocab ; ++token_id) {
  7057. if (min_heap.front().logit < logits[token_id]) {
  7058. std::pop_heap(min_heap.begin(), min_heap.end(), comp);
  7059. min_heap.back().id = token_id;
  7060. min_heap.back().logit = logits[token_id];
  7061. std::push_heap(min_heap.begin(), min_heap.end(), comp);
  7062. }
  7063. }
  7064. return min_heap;
  7065. }
  7066. float probability_from_logit(float logit) const {
  7067. return normalizer * std::exp(logit - max_l);
  7068. }
  7069. };
  7070. struct llama_beam_search_data {
  7071. llama_context * ctx;
  7072. size_t n_beams;
  7073. int n_past;
  7074. int n_predict;
  7075. std::vector<llama_beam> beams;
  7076. std::vector<llama_beam> next_beams;
  7077. // Re-calculated on each loop iteration
  7078. size_t common_prefix_length;
  7079. // Used to communicate to/from callback on beams state.
  7080. std::vector<llama_beam_view> beam_views;
  7081. llama_beam_search_data(llama_context * ctx, size_t n_beams, int n_past, int n_predict)
  7082. : ctx(ctx)
  7083. , n_beams(n_beams)
  7084. , n_past(n_past)
  7085. , n_predict(n_predict)
  7086. , beam_views(n_beams) {
  7087. beams.reserve(n_beams);
  7088. next_beams.reserve(n_beams);
  7089. }
  7090. // Collapse beams to a single beam given by index.
  7091. void collapse_beams(const size_t beam_idx) {
  7092. if (0u < beam_idx) {
  7093. std::swap(beams[0], beams[beam_idx]);
  7094. }
  7095. beams.resize(1);
  7096. }
  7097. // Min-heaps are used to efficiently collect the top-k elements (k=n_beams).
  7098. // The repetitive patterns below reflect the 2 stages of heaps:
  7099. // * Gather elements until the vector is full, then call std::make_heap() on it.
  7100. // * If the heap is full and a new element is found that should be included, pop the
  7101. // least element to the back(), replace it with the new, then push it into the heap.
  7102. void fill_next_beams_by_top_probabilities(llama_beam & beam) {
  7103. // Min-heaps use a greater-than comparator.
  7104. const auto comp = [](const llama_beam & a, const llama_beam & b) { return a.p > b.p; };
  7105. if (beam.eob) {
  7106. // beam is at end-of-sentence, so just copy it to next_beams if its probability is high enough.
  7107. if (next_beams.size() < n_beams) {
  7108. next_beams.push_back(std::move(beam));
  7109. if (next_beams.size() == n_beams) {
  7110. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  7111. }
  7112. } else if (next_beams.front().p < beam.p) {
  7113. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  7114. next_beams.back() = std::move(beam);
  7115. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  7116. }
  7117. } else {
  7118. // beam is not at end-of-sentence, so branch with next top_k tokens.
  7119. if (!beam.tokens.empty()) {
  7120. llama_decode(ctx, llama_batch_get_one(beam.tokens.data(), beam.tokens.size(), n_past, 0));
  7121. }
  7122. llama_logit_info logit_info(ctx);
  7123. std::vector<llama_token_data> next_tokens = logit_info.top_k(n_beams);
  7124. size_t i=0;
  7125. if (next_beams.size() < n_beams) {
  7126. for (; next_beams.size() < n_beams ; ++i) {
  7127. llama_beam next_beam = beam;
  7128. next_beam.tokens.push_back(next_tokens[i].id);
  7129. next_beam.p *= logit_info.probability_from_logit(next_tokens[i].logit);
  7130. next_beams.push_back(std::move(next_beam));
  7131. }
  7132. std::make_heap(next_beams.begin(), next_beams.end(), comp);
  7133. } else {
  7134. for (; next_beams.front().p == 0.0f ; ++i) {
  7135. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  7136. next_beams.back() = beam;
  7137. next_beams.back().tokens.push_back(next_tokens[i].id);
  7138. next_beams.back().p *= logit_info.probability_from_logit(next_tokens[i].logit);
  7139. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  7140. }
  7141. }
  7142. for (; i < n_beams ; ++i) {
  7143. const float next_p = beam.p * logit_info.probability_from_logit(next_tokens[i].logit);
  7144. if (next_beams.front().p < next_p) {
  7145. std::pop_heap(next_beams.begin(), next_beams.end(), comp);
  7146. next_beams.back() = beam;
  7147. next_beams.back().tokens.push_back(next_tokens[i].id);
  7148. next_beams.back().p = next_p;
  7149. std::push_heap(next_beams.begin(), next_beams.end(), comp);
  7150. }
  7151. }
  7152. }
  7153. }
  7154. // Find common_prefix_length based on beams.
  7155. // Requires beams is not empty.
  7156. size_t find_common_prefix_length() {
  7157. size_t common_prefix_length = beams[0].tokens.size();
  7158. for (size_t i = 1 ; i < beams.size() ; ++i) {
  7159. common_prefix_length = std::min(common_prefix_length, beams[i].tokens.size());
  7160. for (size_t j = 0 ; j < common_prefix_length ; ++j) {
  7161. if (beams[0].tokens[j] != beams[i].tokens[j]) {
  7162. common_prefix_length = j;
  7163. break;
  7164. }
  7165. }
  7166. }
  7167. return common_prefix_length;
  7168. }
  7169. // Construct beams_state to send back to caller via the callback function.
  7170. // Side effect: set common_prefix_length = find_common_prefix_length();
  7171. llama_beams_state get_beams_state(const bool last_call) {
  7172. for (size_t i = 0 ; i < beams.size() ; ++i) {
  7173. beam_views[i] = beams[i].view();
  7174. }
  7175. common_prefix_length = find_common_prefix_length();
  7176. return {beam_views.data(), beams.size(), common_prefix_length, last_call};
  7177. }
  7178. // Loop:
  7179. // * while i < n_predict, AND
  7180. // * any of the beams have not yet reached end-of-beam (eob), AND
  7181. // * the highest probability beam(s) (plural in case of ties) are not at end-of-sentence
  7182. // (since all other beam probabilities can only decrease)
  7183. void loop(const llama_beam_search_callback_fn_t callback, void * const callback_data) {
  7184. beams.push_back({{}, 1.0f, false}); // Start with one empty beam w/ probability = 1.0 and !eob.
  7185. const auto not_eob = [](const llama_beam & beam) { return !beam.eob; };
  7186. for (int i = 0 ; i < n_predict && std::any_of(beams.begin(),beams.end(),not_eob) &&
  7187. !beams[top_beam_index()].eob ; ++i) {
  7188. callback(callback_data, get_beams_state(false)); // Sets common_prefix_length
  7189. update_beams_from_beam_views(); // Update values (p,eob) that callback may have changed.
  7190. if (common_prefix_length) {
  7191. llama_decode(ctx, llama_batch_get_one(beams[0].tokens.data(), common_prefix_length, n_past, 0));
  7192. n_past += common_prefix_length;
  7193. }
  7194. // Zero-out next_beam probabilities to place them last in following min-heap.
  7195. std::for_each(next_beams.begin(), next_beams.end(), [](llama_beam & beam) { beam.p = 0.0f; });
  7196. for (llama_beam & beam : beams) {
  7197. beam.shift_tokens(common_prefix_length);
  7198. fill_next_beams_by_top_probabilities(beam);
  7199. }
  7200. // next_beams become the beams of next/final iteration. Swap them to re-use memory.
  7201. beams.swap(next_beams);
  7202. renormalize_beam_probabilities(beams);
  7203. }
  7204. collapse_beams(top_beam_index());
  7205. callback(callback_data, get_beams_state(true));
  7206. }
  7207. // As beams grow, the cumulative probabilities decrease.
  7208. // Renormalize them to avoid floating point underflow.
  7209. static void renormalize_beam_probabilities(std::vector<llama_beam> & beams) {
  7210. const auto sum_p = [](float sum, llama_beam & beam) { return sum + beam.p; };
  7211. const float inv_sum = 1.0f / std::accumulate(beams.begin(), beams.end(), 0.0f, sum_p);
  7212. std::for_each(beams.begin(), beams.end(), [=](llama_beam & beam) { beam.p *= inv_sum; });
  7213. }
  7214. // Assumes beams is non-empty. Uses llama_beam::operator<() for ordering.
  7215. size_t top_beam_index() {
  7216. return std::max_element(beams.begin(), beams.end()) - beams.begin();
  7217. }
  7218. // Copy (p,eob) for each beam which may have been changed by the callback.
  7219. void update_beams_from_beam_views() {
  7220. for (size_t i = 0 ; i < beams.size() ; ++i) {
  7221. beams[i].p = beam_views[i].p;
  7222. beams[i].eob = beam_views[i].eob;
  7223. }
  7224. }
  7225. };
  7226. void llama_beam_search(llama_context * ctx,
  7227. llama_beam_search_callback_fn_t callback, void * callback_data,
  7228. size_t n_beams, int n_past, int n_predict) {
  7229. assert(ctx);
  7230. const int64_t t_start_sample_us = ggml_time_us();
  7231. llama_beam_search_data beam_search_data(ctx, n_beams, n_past, n_predict);
  7232. beam_search_data.loop(callback, callback_data);
  7233. ctx->t_sample_us += ggml_time_us() - t_start_sample_us;
  7234. ctx->n_sample++;
  7235. }
  7236. //
  7237. // quantization
  7238. //
  7239. struct quantize_state_internal {
  7240. const llama_model & model;
  7241. const llama_model_quantize_params * params;
  7242. int n_attention_wv = 0;
  7243. int n_feed_forward_w2 = 0;
  7244. int i_attention_wv = 0;
  7245. int i_feed_forward_w2 = 0;
  7246. int n_k_quantized = 0;
  7247. int n_fallback = 0;
  7248. bool has_imatrix = false;
  7249. quantize_state_internal(const llama_model & model, const llama_model_quantize_params * params)
  7250. : model(model)
  7251. , params(params)
  7252. {}
  7253. };
  7254. static void llama_convert_tensor_internal(
  7255. struct ggml_tensor * tensor, std::vector<no_init<float>> & output, std::vector<std::thread> & workers,
  7256. const size_t nelements, const int nthread
  7257. ) {
  7258. if (output.size() < nelements) {
  7259. output.resize(nelements);
  7260. }
  7261. float * f32_output = (float *) output.data();
  7262. ggml_type_traits_t qtype;
  7263. if (ggml_is_quantized(tensor->type)) {
  7264. qtype = ggml_internal_get_type_traits(tensor->type);
  7265. if (qtype.to_float == NULL) {
  7266. throw std::runtime_error(format("type %s unsupported for integer quantization: no dequantization available", ggml_type_name(tensor->type)));
  7267. }
  7268. } else if (tensor->type != GGML_TYPE_F16) {
  7269. throw std::runtime_error(format("cannot dequantize/convert tensor type %s", ggml_type_name(tensor->type)));
  7270. }
  7271. if (nthread < 2) {
  7272. if (tensor->type == GGML_TYPE_F16) {
  7273. ggml_fp16_to_fp32_row((ggml_fp16_t *)tensor->data, f32_output, nelements);
  7274. } else if (ggml_is_quantized(tensor->type)) {
  7275. qtype.to_float(tensor->data, f32_output, nelements);
  7276. } else {
  7277. GGML_ASSERT(false); // unreachable
  7278. }
  7279. return;
  7280. }
  7281. size_t block_size = tensor->type == GGML_TYPE_F16 ? 1 : (size_t)ggml_blck_size(tensor->type);
  7282. size_t block_size_bytes = ggml_type_size(tensor->type);
  7283. GGML_ASSERT(nelements % block_size == 0);
  7284. size_t nblocks = nelements / block_size;
  7285. size_t blocks_per_thread = nblocks / nthread;
  7286. size_t spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count
  7287. size_t in_buff_offs = 0;
  7288. size_t out_buff_offs = 0;
  7289. for (int tnum = 0; tnum < nthread; tnum++) {
  7290. size_t thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread
  7291. size_t thr_elems = thr_blocks * block_size; // number of elements for this thread
  7292. size_t thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread
  7293. auto compute = [qtype] (ggml_type typ, uint8_t * inbuf, float * outbuf, int nels) {
  7294. if (typ == GGML_TYPE_F16) {
  7295. ggml_fp16_to_fp32_row((ggml_fp16_t *)inbuf, outbuf, nels);
  7296. } else {
  7297. qtype.to_float(inbuf, outbuf, nels);
  7298. }
  7299. };
  7300. workers.emplace_back(compute, tensor->type, (uint8_t *) tensor->data + in_buff_offs, f32_output + out_buff_offs, thr_elems);
  7301. in_buff_offs += thr_block_bytes;
  7302. out_buff_offs += thr_elems;
  7303. }
  7304. for (auto & w : workers) { w.join(); }
  7305. workers.clear();
  7306. }
  7307. static ggml_type get_k_quant_type(quantize_state_internal & qs, ggml_type new_type, const ggml_tensor * tensor, llama_ftype ftype) {
  7308. const std::string name = ggml_get_name(tensor);
  7309. // TODO: avoid hardcoded tensor names - use the TN_* constants
  7310. const llm_arch arch = qs.model.arch;
  7311. const auto tn = LLM_TN(arch);
  7312. auto use_more_bits = [](int i_layer, int num_layers) -> bool {
  7313. return i_layer < num_layers/8 || i_layer >= 7*num_layers/8 || (i_layer - num_layers/8)%3 == 2;
  7314. };
  7315. if (name == tn(LLM_TENSOR_OUTPUT, "weight")) {
  7316. int nx = tensor->ne[0];
  7317. if (arch == LLM_ARCH_FALCON || nx % QK_K != 0) {
  7318. new_type = GGML_TYPE_Q8_0;
  7319. }
  7320. else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS) {
  7321. new_type = GGML_TYPE_Q5_K;
  7322. }
  7323. else if (new_type != GGML_TYPE_Q8_0) {
  7324. new_type = GGML_TYPE_Q6_K;
  7325. }
  7326. } else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS) {
  7327. if (name.find("attn_v.weight") != std::string::npos) {
  7328. if (qs.model.hparams.n_gqa() >= 4 || qs.model.hparams.n_expert >= 4) new_type = GGML_TYPE_Q4_K;
  7329. else new_type = GGML_TYPE_Q2_K;
  7330. ++qs.i_attention_wv;
  7331. }
  7332. else if (name.find("ffn_down") != std::string::npos) {
  7333. if (qs.i_feed_forward_w2 < qs.n_feed_forward_w2/8) new_type = GGML_TYPE_Q2_K;
  7334. ++qs.i_feed_forward_w2;
  7335. }
  7336. else if (name == "token_embd.weight") new_type = GGML_TYPE_Q2_K;
  7337. } else if (name.find("attn_v.weight") != std::string::npos) {
  7338. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) {
  7339. new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K;
  7340. }
  7341. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && qs.model.hparams.n_gqa() >= 4) {
  7342. new_type = GGML_TYPE_Q4_K;
  7343. }
  7344. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  7345. new_type = qs.i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  7346. }
  7347. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  7348. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) &&
  7349. use_more_bits(qs.i_attention_wv, qs.n_attention_wv)) new_type = GGML_TYPE_Q6_K;
  7350. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && qs.i_attention_wv < 4) new_type = GGML_TYPE_Q5_K;
  7351. else if (QK_K == 64 && (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S) &&
  7352. (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;
  7353. if (qs.model.type == MODEL_70B) {
  7354. // In the 70B model we have 8 heads sharing the same attn_v weights. As a result, the attn_v.weight tensor is
  7355. // 8x smaller compared to attn_q.weight. Hence, we can get a nice boost in quantization accuracy with
  7356. // nearly negligible increase in model size by quantizing this tensor with more bits:
  7357. if (new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K) new_type = GGML_TYPE_Q5_K;
  7358. }
  7359. if (qs.model.hparams.n_expert == 8) {
  7360. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  7361. // TODO: explore better strategies
  7362. new_type = GGML_TYPE_Q8_0;
  7363. }
  7364. ++qs.i_attention_wv;
  7365. } else if (name.find("attn_k.weight") != std::string::npos) {
  7366. if (qs.model.hparams.n_expert == 8) {
  7367. // for the 8-expert model, bumping this to Q8_0 trades just ~128MB
  7368. // TODO: explore better strategies
  7369. new_type = GGML_TYPE_Q8_0;
  7370. }
  7371. } else if (name.find("ffn_down") != std::string::npos) {
  7372. const int n_expert = std::max(1, (int)qs.model.hparams.n_expert);
  7373. int i_layer, n_layer;
  7374. if (n_expert == 1) {
  7375. i_layer = qs.i_feed_forward_w2;
  7376. n_layer = qs.n_feed_forward_w2;
  7377. } else {
  7378. // Believe it or not, "experts" in the FFN of Mixtral-8x7B are not consecutive, but iccasionally randomly
  7379. // sprinkled in the model. Hence, simply dividing i_feed_forward_w2 by n_expert does not work
  7380. // for getting the current layer as I initially thought, and we need to resort to parsing the
  7381. // tensor name.
  7382. n_layer = qs.n_feed_forward_w2 / n_expert;
  7383. if (sscanf(name.c_str(), "blk.%d.ffn_down", &i_layer) != 1) {
  7384. throw std::runtime_error(format("Failed to determine layer for tensor %s", name.c_str()));
  7385. }
  7386. if (i_layer < 0 || i_layer >= n_layer) {
  7387. throw std::runtime_error(format("Bad layer %d for tensor %s. Must be in [0, %d)", i_layer, name.c_str(), n_layer));
  7388. }
  7389. }
  7390. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  7391. else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S) {
  7392. if (i_layer < n_layer/8) new_type = GGML_TYPE_Q4_K;
  7393. }
  7394. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
  7395. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q5_K
  7396. : arch != LLM_ARCH_FALCON || use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q4_K
  7397. : GGML_TYPE_Q3_K;
  7398. }
  7399. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) {
  7400. new_type = arch == LLM_ARCH_FALCON ? GGML_TYPE_Q4_K : GGML_TYPE_Q5_K;
  7401. }
  7402. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  7403. if (arch == LLM_ARCH_FALCON) {
  7404. new_type = i_layer < n_layer/16 ? GGML_TYPE_Q6_K :
  7405. use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
  7406. } else {
  7407. if (use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  7408. }
  7409. }
  7410. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M && use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K;
  7411. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && arch != LLM_ARCH_FALCON && i_layer < n_layer/8) {
  7412. new_type = GGML_TYPE_Q5_K;
  7413. }
  7414. else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_0 || ftype == LLAMA_FTYPE_MOSTLY_Q5_0)
  7415. && qs.has_imatrix && i_layer < n_layer/8) {
  7416. // Guard against craziness in the first few ffn_down layers that can happen even with imatrix for Q4_0/Q5_0.
  7417. // We only do it when an imatrix is provided because a) we want to make sure that one can always get the
  7418. // same quantization as before imatrix stuff, and b) Q4_1/Q5_1 do go crazy on ffn_down without an imatrix.
  7419. new_type = ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ? GGML_TYPE_Q4_1 : GGML_TYPE_Q5_1;
  7420. }
  7421. ++qs.i_feed_forward_w2;
  7422. } else if (name.find("attn_output.weight") != std::string::npos) {
  7423. if (arch != LLM_ARCH_FALCON) {
  7424. if (qs.model.hparams.n_expert == 8) {
  7425. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M ||
  7426. ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
  7427. new_type = GGML_TYPE_Q5_K;
  7428. }
  7429. } else {
  7430. if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K ) new_type = GGML_TYPE_Q3_K;
  7431. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) new_type = GGML_TYPE_Q4_K;
  7432. else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K;
  7433. }
  7434. } else {
  7435. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  7436. }
  7437. }
  7438. else if (name.find("attn_qkv.weight") != std::string::npos) {
  7439. if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K;
  7440. else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) new_type = GGML_TYPE_Q5_K;
  7441. else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) new_type = GGML_TYPE_Q6_K;
  7442. }
  7443. // IK: let's remove this, else Q2_K is almost the same as Q3_K_S
  7444. //else if (name.find("ffn_gate") != std::string::npos || name.find("ffn_up") != std::string::npos) {
  7445. // if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K;
  7446. //}
  7447. // This can be used to reduce the size of the Q5_K_S model.
  7448. // The associated PPL increase is fully in line with the size reduction
  7449. //else {
  7450. // if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_S) new_type = GGML_TYPE_Q4_K;
  7451. //}
  7452. bool convert_incompatible_tensor = false;
  7453. if (new_type == GGML_TYPE_Q2_K || new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K ||
  7454. new_type == GGML_TYPE_Q5_K || new_type == GGML_TYPE_Q6_K ||
  7455. new_type == GGML_TYPE_IQ2_XS || new_type == GGML_TYPE_IQ2_XXS) {
  7456. int nx = tensor->ne[0];
  7457. int ny = tensor->ne[1];
  7458. if (nx % QK_K != 0) {
  7459. 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));
  7460. convert_incompatible_tensor = true;
  7461. } else {
  7462. ++qs.n_k_quantized;
  7463. }
  7464. }
  7465. if (convert_incompatible_tensor) {
  7466. switch (new_type) {
  7467. case GGML_TYPE_IQ2_XXS:
  7468. case GGML_TYPE_IQ2_XS:
  7469. case GGML_TYPE_Q2_K: new_type = GGML_TYPE_Q4_0; break;
  7470. case GGML_TYPE_Q3_K: new_type = GGML_TYPE_Q4_1; break;
  7471. case GGML_TYPE_Q4_K: new_type = GGML_TYPE_Q5_0; break;
  7472. case GGML_TYPE_Q5_K: new_type = GGML_TYPE_Q5_1; break;
  7473. case GGML_TYPE_Q6_K: new_type = GGML_TYPE_Q8_0; break;
  7474. default: throw std::runtime_error("\nUnsupported tensor size encountered\n");
  7475. }
  7476. LLAMA_LOG_WARN(" - using fallback quantization %s\n", ggml_type_name(new_type));
  7477. ++qs.n_fallback;
  7478. }
  7479. return new_type;
  7480. }
  7481. static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) {
  7482. ggml_type quantized_type;
  7483. llama_ftype ftype = params->ftype;
  7484. switch (params->ftype) {
  7485. case LLAMA_FTYPE_MOSTLY_Q4_0: quantized_type = GGML_TYPE_Q4_0; break;
  7486. case LLAMA_FTYPE_MOSTLY_Q4_1: quantized_type = GGML_TYPE_Q4_1; break;
  7487. case LLAMA_FTYPE_MOSTLY_Q5_0: quantized_type = GGML_TYPE_Q5_0; break;
  7488. case LLAMA_FTYPE_MOSTLY_Q5_1: quantized_type = GGML_TYPE_Q5_1; break;
  7489. case LLAMA_FTYPE_MOSTLY_Q8_0: quantized_type = GGML_TYPE_Q8_0; break;
  7490. case LLAMA_FTYPE_MOSTLY_F16: quantized_type = GGML_TYPE_F16; break;
  7491. case LLAMA_FTYPE_ALL_F32: quantized_type = GGML_TYPE_F32; break;
  7492. // K-quants
  7493. case LLAMA_FTYPE_MOSTLY_Q2_K: quantized_type = GGML_TYPE_Q2_K; break;
  7494. case LLAMA_FTYPE_MOSTLY_Q2_K_S: quantized_type = GGML_TYPE_Q2_K; break;
  7495. case LLAMA_FTYPE_MOSTLY_Q3_K_S:
  7496. case LLAMA_FTYPE_MOSTLY_Q3_K_M:
  7497. case LLAMA_FTYPE_MOSTLY_Q3_K_L: quantized_type = GGML_TYPE_Q3_K; break;
  7498. case LLAMA_FTYPE_MOSTLY_Q4_K_S:
  7499. case LLAMA_FTYPE_MOSTLY_Q4_K_M: quantized_type = GGML_TYPE_Q4_K; break;
  7500. case LLAMA_FTYPE_MOSTLY_Q5_K_S:
  7501. case LLAMA_FTYPE_MOSTLY_Q5_K_M: quantized_type = GGML_TYPE_Q5_K; break;
  7502. case LLAMA_FTYPE_MOSTLY_Q6_K: quantized_type = GGML_TYPE_Q6_K; break;
  7503. case LLAMA_FTYPE_MOSTLY_IQ2_XXS:quantized_type = GGML_TYPE_IQ2_XXS; break;
  7504. case LLAMA_FTYPE_MOSTLY_IQ2_XS :quantized_type = GGML_TYPE_IQ2_XS; break;
  7505. default: throw std::runtime_error(format("invalid output file type %d\n", ftype));
  7506. }
  7507. int nthread = params->nthread;
  7508. if (nthread <= 0) {
  7509. nthread = std::thread::hardware_concurrency();
  7510. }
  7511. // mmap consistently increases speed Linux, and also increases speed on Windows with
  7512. // hot cache. It may cause a slowdown on macOS, possibly related to free memory.
  7513. #if defined(__linux__) || defined(_WIN32)
  7514. constexpr bool use_mmap = true;
  7515. #else
  7516. constexpr bool use_mmap = false;
  7517. #endif
  7518. llama_model_loader ml(fname_inp, use_mmap, NULL);
  7519. ml.init_mapping(false); // no prefetching?
  7520. llama_model model;
  7521. llm_load_arch(ml, model);
  7522. llm_load_hparams(ml, model);
  7523. struct quantize_state_internal qs(model, params);
  7524. if (params->only_copy) {
  7525. ftype = model.ftype;
  7526. }
  7527. const std::unordered_map<std::string, std::vector<float>> * imatrix_data = nullptr;
  7528. if (params->imatrix) {
  7529. imatrix_data = static_cast<const std::unordered_map<std::string, std::vector<float>>*>(params->imatrix);
  7530. if (imatrix_data) {
  7531. LLAMA_LOG_INFO("================================ Have weights data with %d entries\n",int(imatrix_data->size()));
  7532. qs.has_imatrix = true;
  7533. }
  7534. }
  7535. const size_t align = GGUF_DEFAULT_ALIGNMENT;
  7536. struct gguf_context * ctx_out = gguf_init_empty();
  7537. // copy the KV pairs from the input file
  7538. gguf_set_kv (ctx_out, ml.ctx_gguf);
  7539. gguf_set_val_u32(ctx_out, "general.quantization_version", GGML_QNT_VERSION);
  7540. gguf_set_val_u32(ctx_out, "general.file_type", ftype);
  7541. for (int i = 0; i < ml.n_tensors; ++i) {
  7542. struct ggml_tensor * meta = ml.get_tensor_meta(i);
  7543. const std::string name = ggml_get_name(meta);
  7544. // TODO: avoid hardcoded tensor names - use the TN_* constants
  7545. if (name.find("attn_v.weight") != std::string::npos || name.find("attn_qkv.weight") != std::string::npos) {
  7546. ++qs.n_attention_wv;
  7547. }
  7548. else if (name.find("ffn_down") != std::string::npos) {
  7549. ++qs.n_feed_forward_w2;
  7550. }
  7551. }
  7552. if (qs.n_attention_wv != qs.n_feed_forward_w2 || (uint32_t)qs.n_attention_wv != model.hparams.n_layer) {
  7553. LLAMA_LOG_WARN("%s ============ Strange model: n_attention_wv = %d, n_feed_forward_w2 = %d, hparams.n_layer = %d\n",
  7554. __func__, qs.n_attention_wv, qs.n_feed_forward_w2, model.hparams.n_layer);
  7555. }
  7556. size_t total_size_org = 0;
  7557. size_t total_size_new = 0;
  7558. std::vector<int64_t> hist_all(1 << 4, 0);
  7559. std::vector<std::thread> workers;
  7560. workers.reserve(nthread);
  7561. std::mutex mutex;
  7562. int idx = 0;
  7563. std::vector<no_init<uint8_t>> read_data;
  7564. std::vector<no_init<uint8_t>> work;
  7565. std::vector<no_init<float>> f32_conv_buf;
  7566. // populate the original tensors so we get an initial meta data
  7567. for (int i = 0; i < ml.n_tensors; ++i) {
  7568. struct ggml_tensor * meta = ml.get_tensor_meta(i);
  7569. gguf_add_tensor(ctx_out, meta);
  7570. }
  7571. std::ofstream fout(fname_out, std::ios::binary);
  7572. fout.exceptions(std::ofstream::failbit); // fail fast on write errors
  7573. const size_t meta_size = gguf_get_meta_size(ctx_out);
  7574. LLAMA_LOG_INFO("%s: meta size = %zu bytes\n", __func__, meta_size);
  7575. // placeholder for the meta data
  7576. ::zeros(fout, meta_size);
  7577. for (int i = 0; i < ml.n_tensors; ++i) {
  7578. struct ggml_tensor * tensor = ml.get_tensor_meta(i);
  7579. const std::string name = ggml_get_name(tensor);
  7580. if (!ml.use_mmap) {
  7581. if (read_data.size() < ggml_nbytes(tensor)) {
  7582. read_data.resize(ggml_nbytes(tensor));
  7583. }
  7584. tensor->data = read_data.data();
  7585. }
  7586. ml.load_data_for(tensor);
  7587. LLAMA_LOG_INFO("[%4d/%4d] %36s - [%s], type = %6s, ",
  7588. ++idx, ml.n_tensors,
  7589. ggml_get_name(tensor),
  7590. llama_format_tensor_shape(tensor).c_str(),
  7591. ggml_type_name(tensor->type));
  7592. // This used to be a regex, but <regex> has an extreme cost to compile times.
  7593. bool quantize = name.rfind("weight") == name.size() - 6; // ends with 'weight'?
  7594. // quantize only 2D tensors
  7595. quantize &= (ggml_n_dims(tensor) == 2);
  7596. quantize &= params->quantize_output_tensor || name != "output.weight";
  7597. quantize &= !params->only_copy;
  7598. // do not quantize expert gating tensors
  7599. quantize &= name.find("ffn_gate_inp.weight") == std::string::npos;
  7600. enum ggml_type new_type;
  7601. void * new_data;
  7602. size_t new_size;
  7603. if (quantize) {
  7604. new_type = quantized_type;
  7605. if (!params->pure) {
  7606. new_type = get_k_quant_type(qs, new_type, tensor, ftype);
  7607. }
  7608. // If we've decided to quantize to the same type the tensor is already
  7609. // in then there's nothing to do.
  7610. quantize = tensor->type != new_type;
  7611. }
  7612. if (!quantize) {
  7613. new_type = tensor->type;
  7614. new_data = tensor->data;
  7615. new_size = ggml_nbytes(tensor);
  7616. LLAMA_LOG_INFO("size = %8.3f MB\n", ggml_nbytes(tensor)/1024.0/1024.0);
  7617. } else {
  7618. const size_t nelements = ggml_nelements(tensor);
  7619. const float * imatrix = nullptr;
  7620. if (imatrix_data) {
  7621. auto it = imatrix_data->find(tensor->name);
  7622. if (it == imatrix_data->end()) {
  7623. LLAMA_LOG_INFO("\n====== %s: did not find weights for %s\n", __func__, tensor->name);
  7624. } else {
  7625. if (it->second.size() == (size_t)tensor->ne[0]) {
  7626. imatrix = it->second.data();
  7627. } else {
  7628. LLAMA_LOG_INFO("\n====== %s: imatrix size %d is different from tensor size %d for %s\n", __func__,
  7629. int(it->second.size()), int(tensor->ne[0]), tensor->name);
  7630. }
  7631. }
  7632. }
  7633. if ((new_type == GGML_TYPE_IQ2_XXS ||
  7634. new_type == GGML_TYPE_IQ2_XS ||
  7635. (new_type == GGML_TYPE_Q2_K && params->ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && strcmp(tensor->name, "token_embd.weight") != 0)) && !imatrix) {
  7636. LLAMA_LOG_ERROR("\n\n============================================================\n");
  7637. LLAMA_LOG_ERROR("Missing importance matrix for tensor %s in a very low-bit quantization\n", tensor->name);
  7638. LLAMA_LOG_ERROR("The result will be garbage, so bailing out\n");
  7639. LLAMA_LOG_ERROR("============================================================\n\n");
  7640. throw std::runtime_error(format("Missing importance matrix for tensor %s in a very low-bit quantization", tensor->name));
  7641. }
  7642. float * f32_data;
  7643. if (tensor->type == GGML_TYPE_F32) {
  7644. f32_data = (float *) tensor->data;
  7645. } else if (ggml_is_quantized(tensor->type) && !params->allow_requantize) {
  7646. throw std::runtime_error(format("requantizing from type %s is disabled", ggml_type_name(tensor->type)));
  7647. } else {
  7648. llama_convert_tensor_internal(tensor, f32_conv_buf, workers, nelements, nthread);
  7649. f32_data = (float *) f32_conv_buf.data();
  7650. }
  7651. LLAMA_LOG_INFO("quantizing to %s .. ", ggml_type_name(new_type));
  7652. fflush(stdout);
  7653. if (work.size() < nelements * 4) {
  7654. work.resize(nelements * 4); // upper bound on size
  7655. }
  7656. new_data = work.data();
  7657. std::array<int64_t, 1 << 4> hist_cur = {};
  7658. const int n_per_row = tensor->ne[0];
  7659. const int nrows = nelements / n_per_row;
  7660. static const int min_chunk_size = 32 * 512;
  7661. 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);
  7662. const int nchunk = (nelements + chunk_size - 1)/chunk_size;
  7663. const int nthread_use = nthread > 1 ? std::max(1, std::min(nthread, nchunk)) : 1;
  7664. if (nthread_use < 2) {
  7665. new_size = ggml_quantize_chunk(new_type, f32_data, new_data, 0, nrows, n_per_row, hist_cur.data(), imatrix);
  7666. } else {
  7667. int counter = 0;
  7668. new_size = 0;
  7669. auto compute = [&mutex, &counter, &hist_cur, &new_size, new_type, f32_data, new_data, chunk_size,
  7670. nrows, n_per_row, imatrix]() {
  7671. std::array<int64_t, 1 << 4> local_hist = {};
  7672. const int nrows_per_chunk = chunk_size / n_per_row;
  7673. size_t local_size = 0;
  7674. while (true) {
  7675. std::unique_lock<std::mutex> lock(mutex);
  7676. int first_row = counter; counter += nrows_per_chunk;
  7677. if (first_row >= nrows) {
  7678. if (local_size > 0) {
  7679. for (int j=0; j<int(local_hist.size()); ++j) {
  7680. hist_cur[j] += local_hist[j];
  7681. }
  7682. new_size += local_size;
  7683. }
  7684. break;
  7685. }
  7686. lock.unlock();
  7687. const int this_nrow = std::min(nrows - first_row, nrows_per_chunk);
  7688. local_size += ggml_quantize_chunk(new_type, f32_data, new_data,
  7689. first_row * n_per_row, this_nrow, n_per_row, local_hist.data(), imatrix);
  7690. }
  7691. };
  7692. for (int it = 0; it < nthread_use - 1; ++it) {
  7693. workers.emplace_back(compute);
  7694. }
  7695. compute();
  7696. for (auto & w : workers) { w.join(); }
  7697. workers.clear();
  7698. }
  7699. LLAMA_LOG_INFO("size = %8.2f MiB -> %8.2f MiB", ggml_nbytes(tensor)/1024.0/1024.0, new_size/1024.0/1024.0);
  7700. int64_t tot_count = 0;
  7701. for (size_t i = 0; i < hist_cur.size(); i++) {
  7702. hist_all[i] += hist_cur[i];
  7703. tot_count += hist_cur[i];
  7704. }
  7705. if (tot_count > 0) {
  7706. LLAMA_LOG_INFO(" | hist: ");
  7707. for (size_t i = 0; i < hist_cur.size(); i++) {
  7708. LLAMA_LOG_INFO("%5.3f ", hist_cur[i] / float(nelements));
  7709. }
  7710. }
  7711. LLAMA_LOG_INFO("\n");
  7712. }
  7713. total_size_org += ggml_nbytes(tensor);
  7714. total_size_new += new_size;
  7715. // update the gguf meta data as we go
  7716. gguf_set_tensor_type(ctx_out, name.c_str(), new_type);
  7717. gguf_set_tensor_data(ctx_out, name.c_str(), new_data, new_size);
  7718. // write tensor data + padding
  7719. fout.write((const char *) new_data, new_size);
  7720. zeros(fout, GGML_PAD(new_size, align) - new_size);
  7721. }
  7722. // go back to beginning of file and write the updated meta data
  7723. {
  7724. fout.seekp(0);
  7725. std::vector<uint8_t> data(gguf_get_meta_size(ctx_out));
  7726. gguf_get_meta_data(ctx_out, data.data());
  7727. fout.write((const char *) data.data(), data.size());
  7728. }
  7729. fout.close();
  7730. gguf_free(ctx_out);
  7731. LLAMA_LOG_INFO("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
  7732. LLAMA_LOG_INFO("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
  7733. // print histogram for all tensors
  7734. {
  7735. int64_t sum_all = 0;
  7736. for (size_t i = 0; i < hist_all.size(); i++) {
  7737. sum_all += hist_all[i];
  7738. }
  7739. if (sum_all > 0) {
  7740. LLAMA_LOG_INFO("%s: hist: ", __func__);
  7741. for (size_t i = 0; i < hist_all.size(); i++) {
  7742. LLAMA_LOG_INFO("%5.3f ", hist_all[i] / float(sum_all));
  7743. }
  7744. LLAMA_LOG_INFO("\n");
  7745. }
  7746. }
  7747. if (qs.n_fallback > 0) {
  7748. LLAMA_LOG_WARN("%s: WARNING: %d of %d tensor(s) incompatible with k-quants and required fallback quantization\n",
  7749. __func__, qs.n_fallback, qs.n_k_quantized + qs.n_fallback);
  7750. }
  7751. }
  7752. static int llama_apply_lora_from_file_internal(
  7753. const struct llama_model & model, const char * path_lora, float scale, const char * path_base_model, int n_threads
  7754. ) {
  7755. LLAMA_LOG_INFO("%s: applying lora adapter from '%s' - please wait ...\n", __func__, path_lora);
  7756. const int64_t t_start_lora_us = ggml_time_us();
  7757. llama_file fin(path_lora, "rb");
  7758. // verify magic and version
  7759. {
  7760. uint32_t magic = fin.read_u32();
  7761. if (magic != LLAMA_FILE_MAGIC_GGLA) {
  7762. LLAMA_LOG_ERROR("%s: bad file magic\n", __func__);
  7763. return 1;
  7764. }
  7765. uint32_t format_version = fin.read_u32();
  7766. if (format_version != 1) {
  7767. LLAMA_LOG_ERROR("%s: unsupported file version\n", __func__ );
  7768. return 1;
  7769. }
  7770. }
  7771. int32_t lora_r = fin.read_u32();
  7772. int32_t lora_alpha = fin.read_u32();
  7773. float scaling = scale * (float)lora_alpha / (float)lora_r;
  7774. LLAMA_LOG_INFO("%s: r = %d, alpha = %d, scaling = %.2f\n", __func__, lora_r, lora_alpha, scaling);
  7775. // load base model
  7776. std::unique_ptr<llama_model_loader> ml;
  7777. if (path_base_model) {
  7778. LLAMA_LOG_INFO("%s: loading base model from '%s'\n", __func__, path_base_model);
  7779. ml.reset(new llama_model_loader(path_base_model, /*use_mmap*/ true, /*kv_overrides*/ nullptr));
  7780. ml->init_mapping(/*prefetch*/ false); // no prefetching
  7781. }
  7782. struct tensor_meta {
  7783. std::string name;
  7784. ggml_type type;
  7785. int32_t ne[2];
  7786. size_t offset;
  7787. };
  7788. std::map<std::string, tensor_meta> tensor_meta_map;
  7789. // load all tensor meta
  7790. while (true) {
  7791. if (fin.tell() == fin.size) {
  7792. // eof
  7793. break;
  7794. }
  7795. int32_t n_dims;
  7796. int32_t name_len;
  7797. int32_t ftype;
  7798. fin.read_raw(&n_dims, sizeof(n_dims));
  7799. fin.read_raw(&name_len, sizeof(name_len));
  7800. fin.read_raw(&ftype, sizeof(ftype));
  7801. if (n_dims != 1 && n_dims != 2) {
  7802. LLAMA_LOG_ERROR("%s: unsupported tensor dimension %d\n", __func__, n_dims);
  7803. return 1;
  7804. }
  7805. int32_t ne[2] = { 1, 1 };
  7806. for (int i = 0; i < n_dims; ++i) {
  7807. fin.read_raw(&ne[i], sizeof(ne[i]));
  7808. }
  7809. std::string name;
  7810. {
  7811. GGML_ASSERT(name_len < GGML_MAX_NAME);
  7812. char buf[GGML_MAX_NAME];
  7813. fin.read_raw(buf, name_len);
  7814. name = std::string(buf, name_len);
  7815. }
  7816. // check for lora suffix
  7817. std::string lora_suffix;
  7818. if (name.length() > 6) {
  7819. lora_suffix = name.substr(name.length() - 6);
  7820. }
  7821. if (lora_suffix != ".loraA" && lora_suffix != ".loraB") {
  7822. LLAMA_LOG_ERROR("%s: error: '%s' is not a lora tensor\n", __func__, name.c_str());
  7823. return 1;
  7824. }
  7825. // tensor type
  7826. ggml_type wtype;
  7827. switch (ftype) {
  7828. case 0: wtype = GGML_TYPE_F32; break;
  7829. case 1: wtype = GGML_TYPE_F16; break;
  7830. default:
  7831. {
  7832. LLAMA_LOG_ERROR("%s: invalid tensor data type '%d'\n",
  7833. __func__, ftype);
  7834. return false;
  7835. }
  7836. }
  7837. // data offset
  7838. size_t offset = fin.tell();
  7839. offset = (offset + 31) & -32;
  7840. // skip tensor data
  7841. fin.seek(offset + ggml_row_size(wtype, ne[0]) * ne[1], SEEK_SET);
  7842. tensor_meta_map.emplace(name, tensor_meta{ name, wtype, { ne[0], ne[1] }, offset });
  7843. }
  7844. bool warned = false;
  7845. int n_tensors = 0;
  7846. // apply
  7847. ggml_backend_t backend_cpu = ggml_backend_cpu_init();
  7848. if (backend_cpu == nullptr) {
  7849. LLAMA_LOG_ERROR("%s: error: failed to initialize cpu backend\n", __func__);
  7850. return 1;
  7851. }
  7852. ggml_backend_cpu_set_n_threads(backend_cpu, n_threads);
  7853. std::vector<no_init<uint8_t>> read_buf;
  7854. for (const auto & it : model.tensors_by_name) {
  7855. const std::string & base_name = it.first;
  7856. ggml_tensor * model_t = it.second;
  7857. if (tensor_meta_map.find(base_name + ".loraA") == tensor_meta_map.end() ||
  7858. tensor_meta_map.find(base_name + ".loraB") == tensor_meta_map.end()) {
  7859. continue;
  7860. }
  7861. tensor_meta & metaA = tensor_meta_map.at(base_name + ".loraA");
  7862. tensor_meta & metaB = tensor_meta_map.at(base_name + ".loraB");
  7863. ggml_init_params lora_init_params = {
  7864. /* .mem_size */ ggml_tensor_overhead()*128 + ggml_graph_overhead(),
  7865. /* .mem_buffer */ nullptr,
  7866. /* .no_alloc */ true,
  7867. };
  7868. ggml_context * lora_ctx = ggml_init(lora_init_params);
  7869. if (lora_ctx == nullptr) {
  7870. LLAMA_LOG_ERROR("%s: error: failed to initialize lora context\n", __func__);
  7871. ggml_backend_free(backend_cpu);
  7872. return 1;
  7873. }
  7874. // create tensors
  7875. ggml_tensor * loraA = ggml_new_tensor_2d(lora_ctx, metaA.type, metaA.ne[0], metaA.ne[1]);
  7876. ggml_tensor * loraB = ggml_new_tensor_2d(lora_ctx, metaB.type, metaB.ne[0], metaB.ne[1]);
  7877. ggml_set_name(loraA, metaA.name.c_str());
  7878. ggml_set_name(loraB, metaB.name.c_str());
  7879. ggml_tensor * base_t;
  7880. if (ml) {
  7881. if (gguf_find_tensor(ml->ctx_gguf, base_name.c_str()) < 0) {
  7882. LLAMA_LOG_ERROR("%s: error: tensor '%s' not found in base model\n", __func__, base_name.c_str());
  7883. return 1;
  7884. }
  7885. base_t = ggml_dup_tensor(lora_ctx, ml->get_tensor_meta(base_name.c_str()));
  7886. } else {
  7887. base_t = ggml_dup_tensor(lora_ctx, model_t);
  7888. }
  7889. ggml_set_name(base_t, base_name.c_str());
  7890. // allocate in backend buffer
  7891. ggml_backend_buffer_t lora_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  7892. if (lora_buf == nullptr) {
  7893. LLAMA_LOG_ERROR("%s: error: failed to allocate lora tensors\n", __func__);
  7894. return 1;
  7895. }
  7896. // load tensor data
  7897. auto load_tensor = [&read_buf, &fin](const tensor_meta & tensor_meta, ggml_tensor * tensor) {
  7898. read_buf.resize(ggml_nbytes(tensor));
  7899. fin.seek(tensor_meta.offset, SEEK_SET);
  7900. fin.read_raw(read_buf.data(), ggml_nbytes(tensor));
  7901. ggml_backend_tensor_set(tensor, read_buf.data(), 0, read_buf.size());
  7902. };
  7903. load_tensor(metaA, loraA);
  7904. load_tensor(metaB, loraB);
  7905. // load base model tensor data
  7906. if (ml) {
  7907. ml->load_data_for(base_t);
  7908. } else {
  7909. ggml_backend_tensor_copy(model_t, base_t);
  7910. }
  7911. if (ggml_is_quantized(base_t->type) && !warned) {
  7912. LLAMA_LOG_WARN("%s: warning: using a lora adapter with a quantized model may result in poor quality, "
  7913. "use a f16 or f32 base model with --lora-base\n", __func__);
  7914. warned = true;
  7915. }
  7916. if (base_t->ne[0] != loraA->ne[1] || base_t->ne[1] != loraB->ne[1]) {
  7917. LLAMA_LOG_ERROR("%s: incompatible tensor dimensions (%" PRId64 " and %" PRId64 ");"
  7918. " are you sure that this adapter is for this model?\n", __func__, base_t->ne[0], loraA->ne[1]);
  7919. ggml_free(lora_ctx);
  7920. ggml_backend_buffer_free(lora_buf);
  7921. ggml_backend_free(backend_cpu);
  7922. return 1;
  7923. }
  7924. auto build_lora_graph = [&]() {
  7925. // w = w + BA*s
  7926. ggml_tensor * BA = ggml_mul_mat(lora_ctx, loraA, loraB);
  7927. ggml_set_name(BA, "BA");
  7928. if (scaling != 1.0f) {
  7929. BA = ggml_scale(lora_ctx, BA, scaling);
  7930. ggml_set_name(BA, "BA_scaled");
  7931. }
  7932. ggml_tensor * r;
  7933. r = ggml_add_inplace(lora_ctx, base_t, BA);
  7934. ggml_set_name(r, "r_add");
  7935. if (base_t->type != model_t->type) {
  7936. // convert the result to the model type
  7937. r = ggml_cast(lora_ctx, r, model_t->type);
  7938. ggml_set_name(r, "r_cast");
  7939. }
  7940. return r;
  7941. };
  7942. ggml_cgraph * gf = ggml_new_graph(lora_ctx);
  7943. ggml_tensor * r = build_lora_graph();
  7944. ggml_build_forward_expand(gf, r);
  7945. ggml_backend_buffer_t graph_buf = ggml_backend_alloc_ctx_tensors_from_buft(lora_ctx, ggml_backend_cpu_buffer_type());
  7946. if (graph_buf == nullptr) {
  7947. LLAMA_LOG_ERROR("%s: error: failed to allocate graph tensors\n", __func__);
  7948. ggml_free(lora_ctx);
  7949. ggml_backend_buffer_free(lora_buf);
  7950. ggml_backend_free(backend_cpu);
  7951. return 1;
  7952. }
  7953. ggml_backend_graph_compute(backend_cpu, gf);
  7954. ggml_backend_tensor_set(model_t, r->data, 0, ggml_nbytes(r));
  7955. #if 0
  7956. // TODO: use scheduler with fallback to CPU for less copies between CPU and GPU
  7957. //ggml_backend_sched_t sched = ggml_backend_sched_new(backends.data(), backends.size(), GGML_DEFAULT_GRAPH_SIZE);
  7958. // sched compute
  7959. ggml_build_forward_expand(gf, build_graph());
  7960. ggml_backend_sched_init_measure(sched, gf);
  7961. // create the graph again, since the previous one was destroyed by the measure
  7962. ggml_graph_clear(gf);
  7963. ggml_build_forward_expand(gf, build_graph());
  7964. ggml_backend_sched_graph_compute(sched, gf);
  7965. ggml_backend_sched_free(sched);
  7966. #endif
  7967. ggml_backend_buffer_free(lora_buf);
  7968. ggml_backend_buffer_free(graph_buf);
  7969. ggml_free(lora_ctx);
  7970. n_tensors++;
  7971. if (n_tensors % 4 == 0) {
  7972. LLAMA_LOG_INFO(".");
  7973. }
  7974. }
  7975. ggml_backend_free(backend_cpu);
  7976. const int64_t t_lora_us = ggml_time_us() - t_start_lora_us;
  7977. LLAMA_LOG_INFO(" done (%.2f ms)\n", t_lora_us / 1000.0);
  7978. return 0;
  7979. }
  7980. //
  7981. // interface implementation
  7982. //
  7983. struct llama_model_params llama_model_default_params() {
  7984. struct llama_model_params result = {
  7985. /*.n_gpu_layers =*/ 0,
  7986. /*.split_mode =*/ LLAMA_SPLIT_LAYER,
  7987. /*.main_gpu =*/ 0,
  7988. /*.tensor_split =*/ nullptr,
  7989. /*.progress_callback =*/ nullptr,
  7990. /*.progress_callback_user_data =*/ nullptr,
  7991. /*.kv_overrides =*/ nullptr,
  7992. /*.vocab_only =*/ false,
  7993. /*.use_mmap =*/ true,
  7994. /*.use_mlock =*/ false,
  7995. };
  7996. #ifdef GGML_USE_METAL
  7997. // note: we usually have plenty of VRAM, so by default offload all layers to the GPU
  7998. result.n_gpu_layers = 999;
  7999. #endif
  8000. return result;
  8001. }
  8002. struct llama_context_params llama_context_default_params() {
  8003. struct llama_context_params result = {
  8004. /*.seed =*/ LLAMA_DEFAULT_SEED,
  8005. /*.n_ctx =*/ 512,
  8006. /*.n_batch =*/ 512,
  8007. /*.n_threads =*/ GGML_DEFAULT_N_THREADS, // TODO: better default
  8008. /*.n_threads_batch =*/ GGML_DEFAULT_N_THREADS,
  8009. /*.rope_scaling_type =*/ LLAMA_ROPE_SCALING_UNSPECIFIED,
  8010. /*.rope_freq_base =*/ 0.0f,
  8011. /*.rope_freq_scale =*/ 0.0f,
  8012. /*.yarn_ext_factor =*/ -1.0f,
  8013. /*.yarn_attn_factor =*/ 1.0f,
  8014. /*.yarn_beta_fast =*/ 32.0f,
  8015. /*.yarn_beta_slow =*/ 1.0f,
  8016. /*.yarn_orig_ctx =*/ 0,
  8017. /*.cb_eval =*/ nullptr,
  8018. /*.cb_eval_user_data =*/ nullptr,
  8019. /*.type_k =*/ GGML_TYPE_F16,
  8020. /*.type_v =*/ GGML_TYPE_F16,
  8021. /*.mul_mat_q =*/ true,
  8022. /*.logits_all =*/ false,
  8023. /*.embedding =*/ false,
  8024. /*.offload_kqv =*/ true,
  8025. };
  8026. return result;
  8027. }
  8028. struct llama_model_quantize_params llama_model_quantize_default_params() {
  8029. struct llama_model_quantize_params result = {
  8030. /*.nthread =*/ 0,
  8031. /*.ftype =*/ LLAMA_FTYPE_MOSTLY_Q5_1,
  8032. /*.allow_requantize =*/ false,
  8033. /*.quantize_output_tensor =*/ true,
  8034. /*.only_copy =*/ false,
  8035. /*.pure =*/ false,
  8036. /*.imatrix =*/ nullptr,
  8037. };
  8038. return result;
  8039. }
  8040. int32_t llama_max_devices(void) {
  8041. return LLAMA_MAX_DEVICES;
  8042. }
  8043. bool llama_mmap_supported(void) {
  8044. return llama_mmap::SUPPORTED;
  8045. }
  8046. bool llama_mlock_supported(void) {
  8047. return llama_mlock::SUPPORTED;
  8048. }
  8049. void llama_backend_init(bool numa) {
  8050. ggml_time_init();
  8051. // needed to initialize f16 tables
  8052. {
  8053. struct ggml_init_params params = { 0, NULL, false };
  8054. struct ggml_context * ctx = ggml_init(params);
  8055. ggml_free(ctx);
  8056. }
  8057. if (numa) {
  8058. ggml_numa_init();
  8059. }
  8060. #ifdef GGML_USE_MPI
  8061. ggml_mpi_backend_init();
  8062. #endif
  8063. }
  8064. void llama_backend_free(void) {
  8065. #ifdef GGML_USE_MPI
  8066. ggml_mpi_backend_free();
  8067. #endif
  8068. ggml_quantize_free();
  8069. }
  8070. int64_t llama_time_us(void) {
  8071. return ggml_time_us();
  8072. }
  8073. struct llama_model * llama_load_model_from_file(
  8074. const char * path_model,
  8075. struct llama_model_params params) {
  8076. ggml_time_init();
  8077. llama_model * model = new llama_model;
  8078. unsigned cur_percentage = 0;
  8079. if (params.progress_callback == NULL) {
  8080. params.progress_callback_user_data = &cur_percentage;
  8081. params.progress_callback = [](float progress, void * ctx) {
  8082. unsigned * cur_percentage_p = (unsigned *) ctx;
  8083. unsigned percentage = (unsigned) (100 * progress);
  8084. while (percentage > *cur_percentage_p) {
  8085. *cur_percentage_p = percentage;
  8086. LLAMA_LOG_INFO(".");
  8087. if (percentage >= 100) {
  8088. LLAMA_LOG_INFO("\n");
  8089. }
  8090. }
  8091. return true;
  8092. };
  8093. }
  8094. int status = llama_model_load(path_model, *model, params);
  8095. GGML_ASSERT(status <= 0);
  8096. if (status < 0) {
  8097. if (status == -1) {
  8098. LLAMA_LOG_ERROR("%s: failed to load model\n", __func__);
  8099. } else if (status == -2) {
  8100. LLAMA_LOG_INFO("%s: cancelled model load\n", __func__);
  8101. }
  8102. delete model;
  8103. return nullptr;
  8104. }
  8105. return model;
  8106. }
  8107. void llama_free_model(struct llama_model * model) {
  8108. delete model;
  8109. }
  8110. struct llama_context * llama_new_context_with_model(
  8111. struct llama_model * model,
  8112. struct llama_context_params params) {
  8113. if (!model) {
  8114. return nullptr;
  8115. }
  8116. llama_context * ctx = new llama_context(*model);
  8117. const auto & hparams = model->hparams;
  8118. auto & cparams = ctx->cparams;
  8119. cparams.n_batch = params.n_batch;
  8120. cparams.n_threads = params.n_threads;
  8121. cparams.n_threads_batch = params.n_threads_batch;
  8122. cparams.yarn_ext_factor = params.yarn_ext_factor;
  8123. cparams.yarn_attn_factor = params.yarn_attn_factor;
  8124. cparams.yarn_beta_fast = params.yarn_beta_fast;
  8125. cparams.yarn_beta_slow = params.yarn_beta_slow;
  8126. cparams.mul_mat_q = params.mul_mat_q;
  8127. cparams.offload_kqv = params.offload_kqv;
  8128. cparams.n_ctx = params.n_ctx == 0 ? hparams.n_ctx_train : params.n_ctx;
  8129. cparams.rope_freq_base = params.rope_freq_base == 0.0f ? hparams.rope_freq_base_train : params.rope_freq_base;
  8130. cparams.rope_freq_scale = params.rope_freq_scale == 0.0f ? hparams.rope_freq_scale_train : params.rope_freq_scale;
  8131. cparams.n_yarn_orig_ctx = params.yarn_orig_ctx != 0 ? params.yarn_orig_ctx :
  8132. hparams.n_yarn_orig_ctx != 0 ? hparams.n_yarn_orig_ctx :
  8133. hparams.n_ctx_train;
  8134. cparams.cb_eval = params.cb_eval;
  8135. cparams.cb_eval_user_data = params.cb_eval_user_data;
  8136. auto rope_scaling_type = params.rope_scaling_type;
  8137. if (rope_scaling_type == LLAMA_ROPE_SCALING_UNSPECIFIED) {
  8138. rope_scaling_type = hparams.rope_scaling_type_train;
  8139. }
  8140. if (rope_scaling_type == LLAMA_ROPE_SCALING_NONE) {
  8141. cparams.rope_freq_scale = 1.0f; // never scale if scaling type is none
  8142. }
  8143. if (cparams.yarn_ext_factor < 0.0f) { // negative indicates 'not set'
  8144. cparams.yarn_ext_factor = rope_scaling_type == LLAMA_ROPE_SCALING_YARN ? 1.0f : 0.0f;
  8145. }
  8146. if (params.seed == LLAMA_DEFAULT_SEED) {
  8147. params.seed = time(NULL);
  8148. }
  8149. LLAMA_LOG_INFO("%s: n_ctx = %u\n", __func__, cparams.n_ctx);
  8150. LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, cparams.rope_freq_base);
  8151. LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, cparams.rope_freq_scale);
  8152. ctx->rng = std::mt19937(params.seed);
  8153. ctx->logits_all = params.logits_all;
  8154. const ggml_type type_k = params.type_k;
  8155. const ggml_type type_v = params.type_v;
  8156. GGML_ASSERT(hparams.n_embd_head_k % ggml_blck_size(type_k) == 0);
  8157. GGML_ASSERT(hparams.n_embd_head_v % ggml_blck_size(type_v) == 0);
  8158. if (!hparams.vocab_only) {
  8159. // initialize backends
  8160. #ifdef GGML_USE_METAL
  8161. if (model->n_gpu_layers > 0) {
  8162. ctx->backend_metal = ggml_backend_metal_init();
  8163. if (ctx->backend_metal == nullptr) {
  8164. LLAMA_LOG_ERROR("%s: failed to initialize Metal backend\n", __func__);
  8165. llama_free(ctx);
  8166. return nullptr;
  8167. }
  8168. ctx->backends.push_back(ctx->backend_metal);
  8169. }
  8170. #elif defined(GGML_USE_CUBLAS)
  8171. if (model->n_gpu_layers > 0) {
  8172. // with split_mode LLAMA_SPLIT_NONE or LLAMA_SPLIT_ROW, only the main GPU backend is used
  8173. if (model->split_mode == LLAMA_SPLIT_NONE || model->split_mode == LLAMA_SPLIT_ROW) {
  8174. ggml_backend_t backend = ggml_backend_cuda_init(model->main_gpu);
  8175. if (backend == nullptr) {
  8176. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, model->main_gpu);
  8177. llama_free(ctx);
  8178. return nullptr;
  8179. }
  8180. ctx->backends.push_back(backend);
  8181. } else {
  8182. // LLAMA_SPLIT_LAYER requires a backend for each GPU
  8183. for (int device = 0; device < ggml_backend_cuda_get_device_count(); ++device) {
  8184. ggml_backend_t backend = ggml_backend_cuda_init(device);
  8185. if (backend == nullptr) {
  8186. LLAMA_LOG_ERROR("%s: failed to initialize CUDA%d backend\n", __func__, device);
  8187. llama_free(ctx);
  8188. return nullptr;
  8189. }
  8190. ctx->backends.push_back(backend);
  8191. }
  8192. }
  8193. }
  8194. #endif
  8195. ctx->backend_cpu = ggml_backend_cpu_init();
  8196. if (ctx->backend_cpu == nullptr) {
  8197. LLAMA_LOG_ERROR("%s: failed to initialize CPU backend\n", __func__);
  8198. llama_free(ctx);
  8199. return nullptr;
  8200. }
  8201. ctx->backends.push_back(ctx->backend_cpu);
  8202. if (!llama_kv_cache_init(ctx->kv_self, ctx->model, type_k, type_v,
  8203. cparams.n_ctx, cparams.offload_kqv)) {
  8204. LLAMA_LOG_ERROR("%s: llama_kv_cache_init() failed for self-attention cache\n", __func__);
  8205. llama_free(ctx);
  8206. return nullptr;
  8207. }
  8208. {
  8209. size_t memory_size_k = 0;
  8210. size_t memory_size_v = 0;
  8211. for (auto & k : ctx->kv_self.k_l) {
  8212. memory_size_k += ggml_nbytes(k);
  8213. }
  8214. for (auto & v : ctx->kv_self.v_l) {
  8215. memory_size_v += ggml_nbytes(v);
  8216. }
  8217. LLAMA_LOG_INFO("%s: KV self size = %7.2f MiB, K (%s): %7.2f MiB, V (%s): %7.2f MiB\n", __func__,
  8218. (float)(memory_size_k + memory_size_v) / (1024.0f * 1024.0f),
  8219. ggml_type_name(type_k), (float)memory_size_k / (1024.0f * 1024.0f),
  8220. ggml_type_name(type_v), (float)memory_size_v / (1024.0f * 1024.0f));
  8221. }
  8222. // resized during inference, reserve maximum
  8223. ctx->logits.reserve(hparams.n_vocab*cparams.n_batch);
  8224. if (params.embedding){
  8225. ctx->embedding.resize(hparams.n_embd);
  8226. }
  8227. {
  8228. // buffer types used for the compute buffer of each backend
  8229. std::vector<ggml_backend_buffer_type_t> backend_buft;
  8230. for (auto * backend : ctx->backends) {
  8231. if (ggml_backend_is_cpu(backend)) {
  8232. // use host buffers for the CPU backend compute buffer
  8233. backend_buft.push_back(llama_default_buffer_type_cpu(true));
  8234. } else {
  8235. backend_buft.push_back(ggml_backend_get_default_buffer_type(backend));
  8236. }
  8237. }
  8238. // buffer used to store the computation graph and the tensor meta data
  8239. ctx->buf_compute_meta.resize(ggml_tensor_overhead()*LLAMA_MAX_NODES + ggml_graph_overhead());
  8240. ctx->sched = ggml_backend_sched_new(ctx->backends.data(), backend_buft.data(), ctx->backends.size(), LLAMA_MAX_NODES);
  8241. ctx->alloc = ggml_backend_sched_get_tallocr(ctx->sched, ctx->backend_cpu);
  8242. // build worst-case graph
  8243. int n_tokens = (int)std::min(cparams.n_ctx, cparams.n_batch);
  8244. int n_past = cparams.n_ctx - n_tokens;
  8245. 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
  8246. ggml_cgraph * gf = llama_build_graph(*ctx, llama_batch_get_one(&token, n_tokens, n_past, 0));
  8247. // initialize scheduler with the worst-case graph
  8248. ggml_backend_sched_init_measure(ctx->sched, gf);
  8249. // note: the number of splits during measure is higher than during inference due to the kv shift
  8250. int n_splits = ggml_backend_sched_get_n_splits(ctx->sched);
  8251. LLAMA_LOG_INFO("%s: graph splits (measure): %d\n", __func__, n_splits);
  8252. ctx->alloc = ggml_backend_sched_get_tallocr(ctx->sched, ctx->backend_cpu);
  8253. for (ggml_backend_t backend : ctx->backends) {
  8254. ggml_backend_buffer_t buf = ggml_backend_sched_get_buffer(ctx->sched, backend);
  8255. LLAMA_LOG_INFO("%s: %10s compute buffer size = %8.2f MiB\n", __func__,
  8256. ggml_backend_buffer_name(buf),
  8257. ggml_backend_buffer_get_size(buf) / 1024.0 / 1024.0);
  8258. }
  8259. }
  8260. }
  8261. #ifdef GGML_USE_MPI
  8262. ctx->ctx_mpi = ggml_mpi_init();
  8263. if (ggml_mpi_rank(ctx->ctx_mpi) > 0) {
  8264. // Enter a blocking eval loop with dummy input, letting rank=0 drive the process
  8265. // TODO: needs fix after #3228
  8266. GGML_ASSERT(false && "not implemented");
  8267. //const std::vector<llama_token> tmp(ctx->model.hparams.n_ctx, llama_token_bos(ctx));
  8268. //while (!llama_eval(ctx, tmp.data(), tmp.size(), 0, 0)) {};
  8269. llama_backend_free();
  8270. exit(1);
  8271. }
  8272. #endif
  8273. return ctx;
  8274. }
  8275. void llama_free(struct llama_context * ctx) {
  8276. delete ctx;
  8277. }
  8278. const llama_model * llama_get_model(const struct llama_context * ctx) {
  8279. return &ctx->model;
  8280. }
  8281. uint32_t llama_n_ctx(const struct llama_context * ctx) {
  8282. return ctx->cparams.n_ctx;
  8283. }
  8284. uint32_t llama_n_batch(const struct llama_context * ctx) {
  8285. return ctx->cparams.n_batch;
  8286. }
  8287. enum llama_vocab_type llama_vocab_type(const struct llama_model * model) {
  8288. return model->vocab.type;
  8289. }
  8290. int32_t llama_n_vocab(const struct llama_model * model) {
  8291. return model->vocab.id_to_token.size();
  8292. }
  8293. int32_t llama_n_ctx_train(const struct llama_model * model) {
  8294. return model->hparams.n_ctx_train;
  8295. }
  8296. int32_t llama_n_embd(const struct llama_model * model) {
  8297. return model->hparams.n_embd;
  8298. }
  8299. float llama_rope_freq_scale_train(const struct llama_model * model) {
  8300. return model->hparams.rope_freq_scale_train;
  8301. }
  8302. int32_t llama_model_meta_val_str(const struct llama_model * model, const char * key, char * buf, size_t buf_size) {
  8303. const auto & it = model->gguf_kv.find(key);
  8304. if (it == model->gguf_kv.end()) {
  8305. if (buf_size > 0) {
  8306. buf[0] = '\0';
  8307. }
  8308. return -1;
  8309. }
  8310. return snprintf(buf, buf_size, "%s", it->second.c_str());
  8311. }
  8312. int32_t llama_model_meta_count(const struct llama_model * model) {
  8313. return (int)model->gguf_kv.size();
  8314. }
  8315. int32_t llama_model_meta_key_by_index(const struct llama_model * model, int i, char * buf, size_t buf_size) {
  8316. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  8317. if (buf_size > 0) {
  8318. buf[0] = '\0';
  8319. }
  8320. return -1;
  8321. }
  8322. auto it = model->gguf_kv.begin();
  8323. std::advance(it, i);
  8324. return snprintf(buf, buf_size, "%s", it->first.c_str());
  8325. }
  8326. int32_t llama_model_meta_val_str_by_index(const struct llama_model * model, int32_t i, char * buf, size_t buf_size) {
  8327. if (i < 0 || i >= (int)model->gguf_kv.size()) {
  8328. if (buf_size > 0) {
  8329. buf[0] = '\0';
  8330. }
  8331. return -1;
  8332. }
  8333. auto it = model->gguf_kv.begin();
  8334. std::advance(it, i);
  8335. return snprintf(buf, buf_size, "%s", it->second.c_str());
  8336. }
  8337. int32_t llama_model_desc(const struct llama_model * model, char * buf, size_t buf_size) {
  8338. return snprintf(buf, buf_size, "%s %s %s",
  8339. llama_model_arch_name(model->arch).c_str(),
  8340. llama_model_type_name(model->type),
  8341. llama_model_ftype_name(model->ftype).c_str());
  8342. }
  8343. uint64_t llama_model_size(const struct llama_model * model) {
  8344. uint64_t size = 0;
  8345. for (const auto & it : model->tensors_by_name) {
  8346. size += ggml_nbytes(it.second);
  8347. }
  8348. return size;
  8349. }
  8350. uint64_t llama_model_n_params(const struct llama_model * model) {
  8351. uint64_t nparams = 0;
  8352. for (const auto & it : model->tensors_by_name) {
  8353. nparams += ggml_nelements(it.second);
  8354. }
  8355. return nparams;
  8356. }
  8357. struct ggml_tensor * llama_get_model_tensor(struct llama_model * model, const char * name) {
  8358. auto it = std::find_if(model->tensors_by_name.begin(), model->tensors_by_name.end(),
  8359. [name](const std::pair<std::string, struct ggml_tensor *> & it) {
  8360. return it.first == name;
  8361. });
  8362. if (it == model->tensors_by_name.end()) {
  8363. return nullptr;
  8364. }
  8365. return it->second;
  8366. }
  8367. uint32_t llama_model_quantize(
  8368. const char * fname_inp,
  8369. const char * fname_out,
  8370. const llama_model_quantize_params * params) {
  8371. try {
  8372. llama_model_quantize_internal(fname_inp, fname_out, params);
  8373. return 0;
  8374. } catch (const std::exception & err) {
  8375. LLAMA_LOG_ERROR("%s: failed to quantize: %s\n", __func__, err.what());
  8376. return 1;
  8377. }
  8378. }
  8379. 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) {
  8380. try {
  8381. return llama_apply_lora_from_file_internal(ctx->model, path_lora, scale, path_base_model, n_threads);
  8382. } catch (const std::exception & err) {
  8383. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  8384. return 1;
  8385. }
  8386. }
  8387. 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) {
  8388. try {
  8389. return llama_apply_lora_from_file_internal(*model, path_lora, scale, path_base_model, n_threads);
  8390. } catch (const std::exception & err) {
  8391. LLAMA_LOG_ERROR("%s: failed to apply lora adapter: %s\n", __func__, err.what());
  8392. return 1;
  8393. }
  8394. }
  8395. struct llama_kv_cache_view llama_kv_cache_view_init(const struct llama_context * ctx, int32_t n_max_seq) {
  8396. struct llama_kv_cache_view result = {
  8397. /*.n_cells = */ 0,
  8398. /*.n_max_seq = */ n_max_seq,
  8399. /*.token_count = */ 0,
  8400. /*.used_cells = */ llama_get_kv_cache_used_cells(ctx),
  8401. /*.max_contiguous = */ 0,
  8402. /*.max_contiguous_idx = */ -1,
  8403. /*.cells = */ nullptr,
  8404. /*.cells_sequences = */ nullptr,
  8405. };
  8406. return result;
  8407. }
  8408. void llama_kv_cache_view_free(struct llama_kv_cache_view * view) {
  8409. if (view->cells != nullptr) {
  8410. free(view->cells);
  8411. view->cells = nullptr;
  8412. }
  8413. if (view->cells_sequences != nullptr) {
  8414. free(view->cells_sequences);
  8415. view->cells_sequences = nullptr;
  8416. }
  8417. }
  8418. void llama_kv_cache_view_update(const struct llama_context * ctx, struct llama_kv_cache_view * view) {
  8419. if (uint32_t(view->n_cells) < ctx->kv_self.size || view->cells == nullptr) {
  8420. view->n_cells = int32_t(ctx->kv_self.size);
  8421. void * p = realloc(view->cells, sizeof(struct llama_kv_cache_view_cell) * view->n_cells);
  8422. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells");
  8423. view->cells = (struct llama_kv_cache_view_cell *)p;
  8424. p = realloc(view->cells_sequences, sizeof(llama_seq_id) * view->n_max_seq * view->n_cells);
  8425. GGML_ASSERT(p != nullptr && "Failed to alloc kv_cache_view cells sequences");
  8426. view->cells_sequences = (llama_seq_id *)p;
  8427. }
  8428. const std::vector<llama_kv_cell> & kv_cells = ctx->kv_self.cells;
  8429. llama_kv_cache_view_cell * c_curr = view->cells;
  8430. llama_seq_id * cs_curr = view->cells_sequences;
  8431. int32_t used_cells = 0;
  8432. int32_t token_count = 0;
  8433. int32_t curr_contig_idx = -1;
  8434. uint32_t max_contig = 0;
  8435. int32_t max_contig_idx = -1;
  8436. for (int32_t i = 0; i < int32_t(ctx->kv_self.size); i++, c_curr++, cs_curr += view->n_max_seq) {
  8437. const size_t curr_size = kv_cells[i].seq_id.size();
  8438. token_count += curr_size;
  8439. c_curr->pos = kv_cells[i].pos + kv_cells[i].delta;
  8440. if (curr_size > 0) {
  8441. if (curr_contig_idx >= 0 && uint32_t(i - curr_contig_idx) > max_contig) {
  8442. max_contig = i - curr_contig_idx;
  8443. max_contig_idx = curr_contig_idx;
  8444. }
  8445. curr_contig_idx = -1;
  8446. } else if (curr_contig_idx < 0) {
  8447. curr_contig_idx = i;
  8448. }
  8449. int seq_idx = 0;
  8450. for (const llama_seq_id it : kv_cells[i].seq_id) {
  8451. if (seq_idx >= view->n_max_seq) {
  8452. break;
  8453. }
  8454. cs_curr[seq_idx] = it;
  8455. seq_idx++;
  8456. }
  8457. if (seq_idx != 0) {
  8458. used_cells++;
  8459. }
  8460. for (; seq_idx < view->n_max_seq; seq_idx++) {
  8461. cs_curr[seq_idx] = -1;
  8462. }
  8463. }
  8464. if (curr_contig_idx >= 0 && kv_cells.size() - curr_contig_idx > max_contig) {
  8465. max_contig_idx = curr_contig_idx;
  8466. max_contig = kv_cells.size() - curr_contig_idx;
  8467. }
  8468. view->max_contiguous = max_contig;
  8469. view->max_contiguous_idx = max_contig_idx;
  8470. view->token_count = token_count;
  8471. view->used_cells = used_cells;
  8472. if (uint32_t(used_cells) != ctx->kv_self.used) {
  8473. LLAMA_LOG_ERROR("%s: used cells mismatch. kv_cache says %d but we calculated %d\n",
  8474. __func__, ctx->kv_self.used, used_cells);
  8475. }
  8476. }
  8477. int32_t llama_get_kv_cache_token_count(const struct llama_context * ctx) {
  8478. int result = 0;
  8479. for (uint32_t i = 0; i < ctx->kv_self.size; i++) {
  8480. result += ctx->kv_self.cells[i].seq_id.size();
  8481. }
  8482. return result;
  8483. }
  8484. int32_t llama_get_kv_cache_used_cells(const struct llama_context * ctx) {
  8485. return ctx->kv_self.used;
  8486. }
  8487. void llama_kv_cache_clear(struct llama_context * ctx) {
  8488. llama_kv_cache_clear(ctx->kv_self);
  8489. }
  8490. void llama_kv_cache_seq_rm(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
  8491. llama_kv_cache_seq_rm(ctx->kv_self, seq_id, p0, p1);
  8492. }
  8493. 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) {
  8494. if (seq_id_src == seq_id_dst) {
  8495. return;
  8496. }
  8497. llama_kv_cache_seq_cp(ctx->kv_self, seq_id_src, seq_id_dst, p0, p1);
  8498. }
  8499. void llama_kv_cache_seq_keep(struct llama_context * ctx, llama_seq_id seq_id) {
  8500. llama_kv_cache_seq_keep(ctx->kv_self, seq_id);
  8501. }
  8502. void llama_kv_cache_seq_shift(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos delta) {
  8503. if (delta == 0) {
  8504. return;
  8505. }
  8506. llama_kv_cache_seq_shift(ctx->kv_self, seq_id, p0, p1, delta);
  8507. }
  8508. void llama_kv_cache_seq_div(struct llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) {
  8509. if (d == 1) {
  8510. return;
  8511. }
  8512. llama_kv_cache_seq_div(ctx->kv_self, seq_id, p0, p1, d);
  8513. }
  8514. // Returns the *maximum* size of the state
  8515. size_t llama_get_state_size(const struct llama_context * ctx) {
  8516. // we don't know size of rng until we actually serialize it. so reserve more than enough memory for its serialized state.
  8517. // for reference, std::mt19937(1337) serializes to 6701 bytes.
  8518. const size_t s_rng_size = sizeof(size_t);
  8519. const size_t s_rng = LLAMA_MAX_RNG_STATE;
  8520. const size_t s_logits_size = sizeof(size_t);
  8521. // assume worst case for logits although only currently set ones are serialized
  8522. const size_t s_logits = ctx->logits.capacity() * sizeof(float);
  8523. const size_t s_embedding_size = sizeof(size_t);
  8524. const size_t s_embedding = ctx->embedding.size() * sizeof(float);
  8525. const size_t s_kv_size = sizeof(size_t);
  8526. const size_t s_kv_ntok = sizeof(int);
  8527. const size_t s_kv = ctx->kv_self.total_size();
  8528. const size_t s_total = (
  8529. + s_rng_size
  8530. + s_rng
  8531. + s_logits_size
  8532. + s_logits
  8533. + s_embedding_size
  8534. + s_embedding
  8535. + s_kv_size
  8536. + s_kv_ntok
  8537. + s_kv
  8538. );
  8539. return s_total;
  8540. }
  8541. // llama_context_data
  8542. struct llama_data_context {
  8543. virtual void write(const void * src, size_t size) = 0;
  8544. virtual size_t get_size_written() = 0;
  8545. virtual ~llama_data_context() = default;
  8546. };
  8547. struct llama_data_buffer_context : llama_data_context {
  8548. uint8_t * ptr;
  8549. size_t size_written = 0;
  8550. llama_data_buffer_context(uint8_t * p) : ptr(p) {}
  8551. void write(const void * src, size_t size) override {
  8552. memcpy(ptr, src, size);
  8553. ptr += size;
  8554. size_written += size;
  8555. }
  8556. size_t get_size_written() override {
  8557. return size_written;
  8558. }
  8559. };
  8560. struct llama_data_file_context : llama_data_context {
  8561. llama_file * file;
  8562. size_t size_written = 0;
  8563. llama_data_file_context(llama_file * f) : file(f) {}
  8564. void write(const void * src, size_t size) override {
  8565. file->write_raw(src, size);
  8566. size_written += size;
  8567. }
  8568. size_t get_size_written() override {
  8569. return size_written;
  8570. }
  8571. };
  8572. /** copy state data into either a buffer or file depending on the passed in context
  8573. *
  8574. * file context:
  8575. * llama_file file("/path", "wb");
  8576. * llama_data_file_context data_ctx(&file);
  8577. * llama_copy_state_data(ctx, &data_ctx);
  8578. *
  8579. * buffer context:
  8580. * std::vector<uint8_t> buf(max_size, 0);
  8581. * llama_data_buffer_context data_ctx(&buf.data());
  8582. * llama_copy_state_data(ctx, &data_ctx);
  8583. *
  8584. */
  8585. static void llama_copy_state_data_internal(struct llama_context * ctx, llama_data_context * data_ctx) {
  8586. // copy rng
  8587. {
  8588. std::ostringstream rng_ss;
  8589. rng_ss << ctx->rng;
  8590. const std::string & rng_str = rng_ss.str();
  8591. const size_t rng_size = rng_str.size();
  8592. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  8593. data_ctx->write(&rng_size, sizeof(rng_size));
  8594. data_ctx->write(rng_str.data(), rng_size);
  8595. }
  8596. // copy logits
  8597. {
  8598. const size_t logits_size = ctx->logits.size();
  8599. data_ctx->write(&logits_size, sizeof(logits_size));
  8600. if (logits_size) {
  8601. data_ctx->write(ctx->logits.data(), logits_size * sizeof(float));
  8602. }
  8603. }
  8604. // copy embeddings
  8605. {
  8606. const size_t embedding_size = ctx->embedding.size();
  8607. data_ctx->write(&embedding_size, sizeof(embedding_size));
  8608. if (embedding_size) {
  8609. data_ctx->write(ctx->embedding.data(), embedding_size * sizeof(float));
  8610. }
  8611. }
  8612. // copy kv cache
  8613. {
  8614. const auto & kv_self = ctx->kv_self;
  8615. const auto & hparams = ctx->model.hparams;
  8616. const auto & cparams = ctx->cparams;
  8617. const auto n_layer = hparams.n_layer;
  8618. const auto n_embd_k_gqa = hparams.n_embd_k_gqa();
  8619. const auto n_embd_v_gqa = hparams.n_embd_v_gqa();
  8620. const auto n_ctx = cparams.n_ctx;
  8621. const size_t kv_buf_size = kv_self.total_size();
  8622. const uint32_t kv_head = kv_self.head;
  8623. const uint32_t kv_size = kv_self.size;
  8624. const uint32_t kv_used = kv_self.used;
  8625. data_ctx->write(&kv_buf_size, sizeof(kv_buf_size));
  8626. data_ctx->write(&kv_head, sizeof(kv_head));
  8627. data_ctx->write(&kv_size, sizeof(kv_size));
  8628. data_ctx->write(&kv_used, sizeof(kv_used));
  8629. if (kv_buf_size) {
  8630. const size_t elt_size = ggml_element_size(kv_self.k_l[0]);
  8631. std::vector<uint8_t> tmp_buf;
  8632. for (int il = 0; il < (int) n_layer; ++il) {
  8633. tmp_buf.resize(elt_size*n_embd_k_gqa*kv_head);
  8634. ggml_backend_tensor_get(kv_self.k_l[il], tmp_buf.data(), 0, tmp_buf.size());
  8635. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  8636. // v is not contiguous, copy row by row
  8637. tmp_buf.resize(elt_size*kv_head);
  8638. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  8639. ggml_backend_tensor_get(kv_self.v_l[il], tmp_buf.data(), ir*elt_size*n_ctx, tmp_buf.size());
  8640. data_ctx->write(tmp_buf.data(), tmp_buf.size());
  8641. }
  8642. }
  8643. }
  8644. for (uint32_t i = 0; i < kv_size; ++i) {
  8645. const auto & cell = kv_self.cells[i];
  8646. const llama_pos pos = cell.pos;
  8647. const size_t seq_id_size = cell.seq_id.size();
  8648. data_ctx->write(&pos, sizeof(pos));
  8649. data_ctx->write(&seq_id_size, sizeof(seq_id_size));
  8650. for (auto seq_id : cell.seq_id) {
  8651. data_ctx->write(&seq_id, sizeof(seq_id));
  8652. }
  8653. }
  8654. }
  8655. }
  8656. size_t llama_copy_state_data(struct llama_context * ctx, uint8_t * dst) {
  8657. llama_data_buffer_context data_ctx(dst);
  8658. llama_copy_state_data_internal(ctx, &data_ctx);
  8659. return data_ctx.get_size_written();
  8660. }
  8661. // Sets the state reading from the specified source address
  8662. size_t llama_set_state_data(struct llama_context * ctx, uint8_t * src) {
  8663. uint8_t * inp = src;
  8664. // set rng
  8665. {
  8666. size_t rng_size;
  8667. memcpy(&rng_size, inp, sizeof(rng_size)); inp += sizeof(rng_size);
  8668. GGML_ASSERT(rng_size <= LLAMA_MAX_RNG_STATE);
  8669. std::string rng_str((char *)inp, rng_size); inp += rng_size;
  8670. std::istringstream rng_ss(rng_str);
  8671. rng_ss >> ctx->rng;
  8672. GGML_ASSERT(!rng_ss.fail());
  8673. }
  8674. // set logits
  8675. {
  8676. size_t logits_size;
  8677. memcpy(&logits_size, inp, sizeof(logits_size)); inp += sizeof(logits_size);
  8678. GGML_ASSERT(ctx->logits.capacity() >= logits_size);
  8679. if (logits_size) {
  8680. ctx->logits.resize(logits_size);
  8681. memcpy(ctx->logits.data(), inp, logits_size * sizeof(float));
  8682. inp += logits_size * sizeof(float);
  8683. }
  8684. }
  8685. // set embeddings
  8686. {
  8687. size_t embedding_size;
  8688. memcpy(&embedding_size, inp, sizeof(embedding_size)); inp += sizeof(embedding_size);
  8689. GGML_ASSERT(ctx->embedding.capacity() == embedding_size);
  8690. if (embedding_size) {
  8691. memcpy(ctx->embedding.data(), inp, embedding_size * sizeof(float));
  8692. inp += embedding_size * sizeof(float);
  8693. }
  8694. }
  8695. // set kv cache
  8696. {
  8697. const auto & kv_self = ctx->kv_self;
  8698. const auto & hparams = ctx->model.hparams;
  8699. const auto & cparams = ctx->cparams;
  8700. const int n_layer = hparams.n_layer;
  8701. const int n_embd_k_gqa = hparams.n_embd_k_gqa();
  8702. const int n_embd_v_gqa = hparams.n_embd_v_gqa();
  8703. const int n_ctx = cparams.n_ctx;
  8704. size_t kv_buf_size;
  8705. uint32_t kv_head;
  8706. uint32_t kv_size;
  8707. uint32_t kv_used;
  8708. memcpy(&kv_buf_size, inp, sizeof(kv_buf_size)); inp += sizeof(kv_buf_size);
  8709. memcpy(&kv_head, inp, sizeof(kv_head)); inp += sizeof(kv_head);
  8710. memcpy(&kv_size, inp, sizeof(kv_size)); inp += sizeof(kv_size);
  8711. memcpy(&kv_used, inp, sizeof(kv_used)); inp += sizeof(kv_used);
  8712. if (kv_buf_size) {
  8713. GGML_ASSERT(kv_self.total_size() == kv_buf_size);
  8714. const size_t elt_size = ggml_element_size(kv_self.k_l[0]);
  8715. for (int il = 0; il < (int) n_layer; ++il) {
  8716. size_t k_size = elt_size*n_embd_k_gqa*kv_head;
  8717. ggml_backend_tensor_set(kv_self.k_l[il], inp, 0, k_size);
  8718. inp += k_size;
  8719. // v is not contiguous, copy row by row
  8720. size_t v_row_size = elt_size*kv_head;
  8721. for (int ir = 0; ir < (int) n_embd_v_gqa; ++ir) {
  8722. ggml_backend_tensor_set(kv_self.v_l[il], inp, ir*elt_size*n_ctx, v_row_size);
  8723. inp += v_row_size;
  8724. }
  8725. }
  8726. }
  8727. ctx->kv_self.head = kv_head;
  8728. ctx->kv_self.size = kv_size;
  8729. ctx->kv_self.used = kv_used;
  8730. ctx->kv_self.cells.resize(kv_size);
  8731. for (uint32_t i = 0; i < kv_size; ++i) {
  8732. llama_pos pos;
  8733. size_t seq_id_size;
  8734. memcpy(&pos, inp, sizeof(pos)); inp += sizeof(pos);
  8735. memcpy(&seq_id_size, inp, sizeof(seq_id_size)); inp += sizeof(seq_id_size);
  8736. ctx->kv_self.cells[i].pos = pos;
  8737. llama_seq_id seq_id;
  8738. for (size_t j = 0; j < seq_id_size; ++j) {
  8739. memcpy(&seq_id, inp, sizeof(seq_id)); inp += sizeof(seq_id);
  8740. ctx->kv_self.cells[i].seq_id.insert(seq_id);
  8741. }
  8742. }
  8743. }
  8744. const size_t nread = inp - src;
  8745. const size_t max_size = llama_get_state_size(ctx);
  8746. GGML_ASSERT(nread <= max_size);
  8747. return nread;
  8748. }
  8749. 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) {
  8750. llama_file file(path_session, "rb");
  8751. // sanity checks
  8752. {
  8753. const uint32_t magic = file.read_u32();
  8754. const uint32_t version = file.read_u32();
  8755. if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
  8756. LLAMA_LOG_ERROR("%s : unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
  8757. return false;
  8758. }
  8759. llama_hparams session_hparams;
  8760. file.read_raw(&session_hparams, sizeof(llama_hparams));
  8761. if (session_hparams != ctx->model.hparams) {
  8762. LLAMA_LOG_INFO("%s : model hparams didn't match from session file!\n", __func__);
  8763. return false;
  8764. }
  8765. }
  8766. // load the prompt
  8767. {
  8768. const uint32_t n_token_count = file.read_u32();
  8769. if (n_token_count > n_token_capacity) {
  8770. LLAMA_LOG_ERROR("%s : token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
  8771. return false;
  8772. }
  8773. file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
  8774. *n_token_count_out = n_token_count;
  8775. }
  8776. // restore the context state
  8777. {
  8778. const size_t n_state_size_cur = file.size - file.tell();
  8779. const size_t n_state_size_max = llama_get_state_size(ctx);
  8780. if (n_state_size_cur > n_state_size_max) {
  8781. 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);
  8782. return false;
  8783. }
  8784. std::vector<uint8_t> state_data(n_state_size_max);
  8785. file.read_raw(state_data.data(), n_state_size_cur);
  8786. llama_set_state_data(ctx, state_data.data());
  8787. }
  8788. return true;
  8789. }
  8790. 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) {
  8791. try {
  8792. return llama_load_session_file_internal(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
  8793. } catch (const std::exception & err) {
  8794. LLAMA_LOG_ERROR("error loading session file: %s\n", err.what());
  8795. return false;
  8796. }
  8797. }
  8798. bool llama_save_session_file(struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
  8799. llama_file file(path_session, "wb");
  8800. file.write_u32(LLAMA_SESSION_MAGIC);
  8801. file.write_u32(LLAMA_SESSION_VERSION);
  8802. file.write_raw(&ctx->model.hparams, sizeof(llama_hparams));
  8803. // save the prompt
  8804. file.write_u32((uint32_t) n_token_count);
  8805. file.write_raw(tokens, sizeof(llama_token) * n_token_count);
  8806. // save the context state using stream saving
  8807. llama_data_file_context data_ctx(&file);
  8808. llama_copy_state_data_internal(ctx, &data_ctx);
  8809. return true;
  8810. }
  8811. int llama_eval(
  8812. struct llama_context * ctx,
  8813. llama_token * tokens,
  8814. int32_t n_tokens,
  8815. int32_t n_past) {
  8816. llama_kv_cache_seq_rm(ctx->kv_self, -1, n_past, -1);
  8817. const int ret = llama_decode_internal(*ctx, llama_batch_get_one(tokens, n_tokens, n_past, 0));
  8818. if (ret < 0) {
  8819. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  8820. }
  8821. return ret;
  8822. }
  8823. int llama_eval_embd(
  8824. struct llama_context * ctx,
  8825. float * embd,
  8826. int32_t n_tokens,
  8827. int32_t n_past) {
  8828. llama_kv_cache_seq_rm(ctx->kv_self, -1, n_past, -1);
  8829. llama_batch batch = { n_tokens, nullptr, embd, nullptr, nullptr, nullptr, nullptr, n_past, 1, 0, };
  8830. const int ret = llama_decode_internal(*ctx, batch);
  8831. if (ret < 0) {
  8832. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  8833. }
  8834. return ret;
  8835. }
  8836. void llama_set_n_threads(struct llama_context * ctx, uint32_t n_threads, uint32_t n_threads_batch) {
  8837. ctx->cparams.n_threads = n_threads;
  8838. ctx->cparams.n_threads_batch = n_threads_batch;
  8839. }
  8840. struct llama_batch llama_batch_get_one(
  8841. llama_token * tokens,
  8842. int32_t n_tokens,
  8843. llama_pos pos_0,
  8844. llama_seq_id seq_id) {
  8845. return {
  8846. /*n_tokens =*/ n_tokens,
  8847. /*tokens =*/ tokens,
  8848. /*embd =*/ nullptr,
  8849. /*pos =*/ nullptr,
  8850. /*n_seq_id =*/ nullptr,
  8851. /*seq_id =*/ nullptr,
  8852. /*logits =*/ nullptr,
  8853. /*all_pos_0 =*/ pos_0,
  8854. /*all_pos_1 =*/ 1,
  8855. /*all_seq_id =*/ seq_id,
  8856. };
  8857. }
  8858. struct llama_batch llama_batch_init(int32_t n_tokens, int32_t embd, int32_t n_seq_max) {
  8859. llama_batch batch = { 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, 0, 0, 0, };
  8860. if (embd) {
  8861. batch.embd = (float *) malloc(sizeof(float) * n_tokens * embd);
  8862. } else {
  8863. batch.token = (llama_token *) malloc(sizeof(llama_token) * n_tokens);
  8864. }
  8865. batch.pos = (llama_pos *) malloc(sizeof(llama_pos) * n_tokens);
  8866. batch.n_seq_id = (int32_t *) malloc(sizeof(int32_t) * n_tokens);
  8867. batch.seq_id = (llama_seq_id **) malloc(sizeof(llama_seq_id *) * n_tokens);
  8868. for (int i = 0; i < n_tokens; ++i) {
  8869. batch.seq_id[i] = (llama_seq_id *) malloc(sizeof(llama_seq_id) * n_seq_max);
  8870. }
  8871. batch.logits = (int8_t *) malloc(sizeof(int8_t) * n_tokens);
  8872. return batch;
  8873. }
  8874. void llama_batch_free(struct llama_batch batch) {
  8875. if (batch.token) free(batch.token);
  8876. if (batch.embd) free(batch.embd);
  8877. if (batch.pos) free(batch.pos);
  8878. if (batch.n_seq_id) free(batch.n_seq_id);
  8879. if (batch.seq_id) {
  8880. for (int i = 0; i < batch.n_tokens; ++i) {
  8881. free(batch.seq_id[i]);
  8882. }
  8883. free(batch.seq_id);
  8884. }
  8885. if (batch.logits) free(batch.logits);
  8886. }
  8887. int32_t llama_decode(
  8888. struct llama_context * ctx,
  8889. struct llama_batch batch) {
  8890. const int ret = llama_decode_internal(*ctx, batch);
  8891. if (ret < 0) {
  8892. LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
  8893. }
  8894. return ret;
  8895. }
  8896. float * llama_get_logits(struct llama_context * ctx) {
  8897. return ctx->logits.data();
  8898. }
  8899. float * llama_get_logits_ith(struct llama_context * ctx, int32_t i) {
  8900. assert(ctx->logits_valid.at(i));
  8901. return ctx->logits.data() + i*ctx->model.hparams.n_vocab;
  8902. }
  8903. float * llama_get_embeddings(struct llama_context * ctx) {
  8904. return ctx->embedding.data();
  8905. }
  8906. const char * llama_token_get_text(const struct llama_model * model, llama_token token) {
  8907. return model->vocab.id_to_token[token].text.c_str();
  8908. }
  8909. float llama_token_get_score(const struct llama_model * model, llama_token token) {
  8910. return model->vocab.id_to_token[token].score;
  8911. }
  8912. llama_token_type llama_token_get_type(const struct llama_model * model, llama_token token) {
  8913. return model->vocab.id_to_token[token].type;
  8914. }
  8915. llama_token llama_token_bos(const struct llama_model * model) {
  8916. return model->vocab.special_bos_id;
  8917. }
  8918. llama_token llama_token_eos(const struct llama_model * model) {
  8919. return model->vocab.special_eos_id;
  8920. }
  8921. llama_token llama_token_nl(const struct llama_model * model) {
  8922. return model->vocab.linefeed_id;
  8923. }
  8924. int32_t llama_add_bos_token(const struct llama_model * model) {
  8925. return model->vocab.special_add_bos;
  8926. }
  8927. int32_t llama_add_eos_token(const struct llama_model * model) {
  8928. return model->vocab.special_add_eos;
  8929. }
  8930. llama_token llama_token_prefix(const struct llama_model * model) {
  8931. return model->vocab.special_prefix_id;
  8932. }
  8933. llama_token llama_token_middle(const struct llama_model * model) {
  8934. return model->vocab.special_middle_id;
  8935. }
  8936. llama_token llama_token_suffix(const struct llama_model * model) {
  8937. return model->vocab.special_suffix_id;
  8938. }
  8939. llama_token llama_token_eot(const struct llama_model * model) {
  8940. return model->vocab.special_eot_id;
  8941. }
  8942. int32_t llama_tokenize(
  8943. const struct llama_model * model,
  8944. const char * text,
  8945. int32_t text_len,
  8946. llama_token * tokens,
  8947. int32_t n_max_tokens,
  8948. bool add_bos,
  8949. bool special) {
  8950. auto res = llama_tokenize_internal(model->vocab, std::string(text, text_len), add_bos, special);
  8951. if (n_max_tokens < (int) res.size()) {
  8952. // LLAMA_LOG_ERROR("%s: too many tokens\n", __func__);
  8953. return -((int) res.size());
  8954. }
  8955. for (size_t i = 0; i < res.size(); i++) {
  8956. tokens[i] = res[i];
  8957. }
  8958. return res.size();
  8959. }
  8960. static std::string llama_decode_text(const std::string & text) {
  8961. std::string decoded_text;
  8962. auto unicode_sequences = codepoints_from_utf8(text);
  8963. for (auto& unicode_sequence : unicode_sequences) {
  8964. decoded_text += unicode_to_bytes_bpe(codepoint_to_utf8(unicode_sequence));
  8965. }
  8966. return decoded_text;
  8967. }
  8968. // does not write null-terminator to buf
  8969. int32_t llama_token_to_piece(const struct llama_model * model, llama_token token, char * buf, int32_t length) {
  8970. if (0 <= token && token < llama_n_vocab(model)) {
  8971. switch (llama_vocab_get_type(model->vocab)) {
  8972. case LLAMA_VOCAB_TYPE_SPM: {
  8973. // NOTE: we accept all unsupported token types,
  8974. // suppressing them like CONTROL tokens.
  8975. if (llama_is_normal_token(model->vocab, token)) {
  8976. std::string result = model->vocab.id_to_token[token].text;
  8977. llama_unescape_whitespace(result);
  8978. if (length < (int) result.length()) {
  8979. return -(int) result.length();
  8980. }
  8981. memcpy(buf, result.c_str(), result.length());
  8982. return result.length();
  8983. } else if (llama_is_user_defined_token(model->vocab, token)) {
  8984. std::string result = model->vocab.id_to_token[token].text;
  8985. if (length < (int) result.length()) {
  8986. return -result.length();
  8987. }
  8988. memcpy(buf, result.c_str(), result.length());
  8989. return result.length();
  8990. } else if (llama_is_unknown_token(model->vocab, token)) { // NOLINT
  8991. if (length < 3) {
  8992. return -3;
  8993. }
  8994. memcpy(buf, "\xe2\x96\x85", 3);
  8995. return 3;
  8996. } else if (llama_is_control_token(model->vocab, token)) {
  8997. ;
  8998. } else if (llama_is_byte_token(model->vocab, token)) {
  8999. if (length < 1) {
  9000. return -1;
  9001. }
  9002. buf[0] = llama_token_to_byte(model->vocab, token);
  9003. return 1;
  9004. }
  9005. break;
  9006. }
  9007. case LLAMA_VOCAB_TYPE_BPE: {
  9008. // NOTE: we accept all unsupported token types,
  9009. // suppressing them like CONTROL tokens.
  9010. if (llama_is_normal_token(model->vocab, token)) {
  9011. std::string result = model->vocab.id_to_token[token].text;
  9012. result = llama_decode_text(result);
  9013. if (length < (int) result.length()) {
  9014. return -(int) result.length();
  9015. }
  9016. memcpy(buf, result.c_str(), result.length());
  9017. return result.length();
  9018. } else if (llama_is_user_defined_token(model->vocab, token)) {
  9019. std::string result = model->vocab.id_to_token[token].text;
  9020. if (length < (int) result.length()) {
  9021. return -result.length();
  9022. }
  9023. memcpy(buf, result.c_str(), result.length());
  9024. return result.length();
  9025. } else if (llama_is_control_token(model->vocab, token)) {
  9026. ;
  9027. }
  9028. break;
  9029. }
  9030. default:
  9031. GGML_ASSERT(false);
  9032. }
  9033. }
  9034. return 0;
  9035. }
  9036. struct llama_timings llama_get_timings(struct llama_context * ctx) {
  9037. struct llama_timings result = {
  9038. /*.t_start_ms =*/ 1e-3 * ctx->t_start_us,
  9039. /*.t_end_ms =*/ 1.00 * ggml_time_ms(),
  9040. /*.t_load_ms =*/ 1e-3 * ctx->t_load_us,
  9041. /*.t_sample_ms =*/ 1e-3 * ctx->t_sample_us,
  9042. /*.t_p_eval_ms =*/ 1e-3 * ctx->t_p_eval_us,
  9043. /*.t_eval_ms =*/ 1e-3 * ctx->t_eval_us,
  9044. /*.n_sample =*/ std::max(1, ctx->n_sample),
  9045. /*.n_p_eval =*/ std::max(1, ctx->n_p_eval),
  9046. /*.n_eval =*/ std::max(1, ctx->n_eval),
  9047. };
  9048. return result;
  9049. }
  9050. void llama_print_timings(struct llama_context * ctx) {
  9051. const llama_timings timings = llama_get_timings(ctx);
  9052. LLAMA_LOG_INFO("\n");
  9053. LLAMA_LOG_INFO("%s: load time = %10.2f ms\n", __func__, timings.t_load_ms);
  9054. LLAMA_LOG_INFO("%s: sample time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  9055. __func__, timings.t_sample_ms, timings.n_sample, timings.t_sample_ms / timings.n_sample, 1e3 / timings.t_sample_ms * timings.n_sample);
  9056. LLAMA_LOG_INFO("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
  9057. __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);
  9058. LLAMA_LOG_INFO("%s: eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n",
  9059. __func__, timings.t_eval_ms, timings.n_eval, timings.t_eval_ms / timings.n_eval, 1e3 / timings.t_eval_ms * timings.n_eval);
  9060. 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));
  9061. }
  9062. void llama_reset_timings(struct llama_context * ctx) {
  9063. ctx->t_start_us = ggml_time_us();
  9064. ctx->t_sample_us = ctx->n_sample = 0;
  9065. ctx->t_eval_us = ctx->n_eval = 0;
  9066. ctx->t_p_eval_us = ctx->n_p_eval = 0;
  9067. }
  9068. const char * llama_print_system_info(void) {
  9069. static std::string s;
  9070. s = "";
  9071. s += "AVX = " + std::to_string(ggml_cpu_has_avx()) + " | ";
  9072. s += "AVX_VNNI = " + std::to_string(ggml_cpu_has_avx_vnni()) + " | ";
  9073. s += "AVX2 = " + std::to_string(ggml_cpu_has_avx2()) + " | ";
  9074. s += "AVX512 = " + std::to_string(ggml_cpu_has_avx512()) + " | ";
  9075. s += "AVX512_VBMI = " + std::to_string(ggml_cpu_has_avx512_vbmi()) + " | ";
  9076. s += "AVX512_VNNI = " + std::to_string(ggml_cpu_has_avx512_vnni()) + " | ";
  9077. s += "FMA = " + std::to_string(ggml_cpu_has_fma()) + " | ";
  9078. s += "NEON = " + std::to_string(ggml_cpu_has_neon()) + " | ";
  9079. s += "ARM_FMA = " + std::to_string(ggml_cpu_has_arm_fma()) + " | ";
  9080. s += "F16C = " + std::to_string(ggml_cpu_has_f16c()) + " | ";
  9081. s += "FP16_VA = " + std::to_string(ggml_cpu_has_fp16_va()) + " | ";
  9082. s += "WASM_SIMD = " + std::to_string(ggml_cpu_has_wasm_simd()) + " | ";
  9083. s += "BLAS = " + std::to_string(ggml_cpu_has_blas()) + " | ";
  9084. s += "SSE3 = " + std::to_string(ggml_cpu_has_sse3()) + " | ";
  9085. s += "SSSE3 = " + std::to_string(ggml_cpu_has_ssse3()) + " | ";
  9086. s += "VSX = " + std::to_string(ggml_cpu_has_vsx()) + " | ";
  9087. return s.c_str();
  9088. }
  9089. void llama_dump_timing_info_yaml(FILE * stream, const llama_context * ctx) {
  9090. fprintf(stream, "\n");
  9091. fprintf(stream, "###########\n");
  9092. fprintf(stream, "# Timings #\n");
  9093. fprintf(stream, "###########\n");
  9094. fprintf(stream, "\n");
  9095. fprintf(stream, "mst_eval: %.2f # ms / token during generation\n",
  9096. 1.0e-3 * ctx->t_eval_us / ctx->n_eval);
  9097. fprintf(stream, "mst_p_eval: %.2f # ms / token during prompt processing\n",
  9098. 1.0e-3 * ctx->t_p_eval_us / ctx->n_p_eval);
  9099. fprintf(stream, "mst_sample: %.2f # ms / token during sampling\n",
  9100. 1.0e-3 * ctx->t_sample_us / ctx->n_sample);
  9101. fprintf(stream, "n_eval: %d # number of tokens generated (excluding the first one)\n", ctx->n_eval);
  9102. fprintf(stream, "n_p_eval: %d # number of tokens processed in batches at the beginning\n", ctx->n_p_eval);
  9103. fprintf(stream, "n_sample: %d # number of sampled tokens\n", ctx->n_sample);
  9104. fprintf(stream, "t_eval_us: %" PRId64 " # total microseconds spent generating tokens\n", ctx->t_eval_us);
  9105. fprintf(stream, "t_load_us: %" PRId64 " # total microseconds spent loading the model\n", ctx->t_load_us);
  9106. fprintf(stream, "t_p_eval_us: %" PRId64 " # total microseconds spent prompt processing\n", ctx->t_p_eval_us);
  9107. fprintf(stream, "t_sample_us: %" PRId64 " # total microseconds spent sampling\n", ctx->t_sample_us);
  9108. fprintf(stream, "ts_eval: %.2f # tokens / second during generation\n",
  9109. 1.0e6 * ctx->n_eval / ctx->t_eval_us);
  9110. fprintf(stream, "ts_p_eval: %.2f # tokens / second during prompt processing\n",
  9111. 1.0e6 * ctx->n_p_eval / ctx->t_p_eval_us);
  9112. fprintf(stream, "ts_sample: %.2f # tokens / second during sampling\n",
  9113. 1.0e6 * ctx->n_sample / ctx->t_sample_us);
  9114. }
  9115. // For internal test use
  9116. const std::vector<std::pair<std::string, struct ggml_tensor *>> & llama_internal_get_tensor_map(
  9117. struct llama_context * ctx
  9118. ) {
  9119. return ctx->model.tensors_by_name;
  9120. }
  9121. void llama_log_set(ggml_log_callback log_callback, void * user_data) {
  9122. g_state.log_callback = log_callback ? log_callback : llama_log_callback_default;
  9123. g_state.log_callback_user_data = user_data;
  9124. #ifdef GGML_USE_METAL
  9125. ggml_backend_metal_log_set_callback(g_state.log_callback, g_state.log_callback_user_data);
  9126. #endif
  9127. }
  9128. static void llama_log_internal_v(ggml_log_level level, const char * format, va_list args) {
  9129. va_list args_copy;
  9130. va_copy(args_copy, args);
  9131. char buffer[128];
  9132. int len = vsnprintf(buffer, 128, format, args);
  9133. if (len < 128) {
  9134. g_state.log_callback(level, buffer, g_state.log_callback_user_data);
  9135. } else {
  9136. char* buffer2 = new char[len+1];
  9137. vsnprintf(buffer2, len+1, format, args_copy);
  9138. buffer2[len] = 0;
  9139. g_state.log_callback(level, buffer2, g_state.log_callback_user_data);
  9140. delete[] buffer2;
  9141. }
  9142. va_end(args_copy);
  9143. }
  9144. static void llama_log_internal(ggml_log_level level, const char * format, ...) {
  9145. va_list args;
  9146. va_start(args, format);
  9147. llama_log_internal_v(level, format, args);
  9148. va_end(args);
  9149. }
  9150. static void llama_log_callback_default(ggml_log_level level, const char * text, void * user_data) {
  9151. (void) level;
  9152. (void) user_data;
  9153. fputs(text, stderr);
  9154. fflush(stderr);
  9155. }