llama.cpp 402 KB

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